Browse Source

Merge pull request #25 from chamilo/1.9.x

1.9.x
ycastillo 11 years ago
parent
commit
27ef038ee7
100 changed files with 6421 additions and 4979 deletions
  1. 58 58
      documentation/installation_guide.html
  2. 26 26
      documentation/installation_guide_es_ES.html
  3. 1 1
      license.txt
  4. 1 6
      main/admin/course_request_accepted.php
  5. 2 135
      main/admin/index.php
  6. 30 24
      main/admin/session_course_user_list.php
  7. 17 6
      main/admin/session_import.php
  8. 17 0
      main/admin/statistics/statistics.lib.php
  9. 5 2
      main/admin/user_edit.php
  10. 50 25
      main/admin/user_import.php
  11. 70 20
      main/admin/user_information.php
  12. 16 16
      main/document/document.inc.php
  13. 38 41
      main/document/document.php
  14. 105 90
      main/dropbox/dropbox_class.inc.php
  15. 14 15
      main/dropbox/dropbox_config.inc.php
  16. 93 106
      main/dropbox/dropbox_download.php
  17. 226 224
      main/dropbox/dropbox_functions.inc.php
  18. 139 51
      main/dropbox/dropbox_init.inc.php
  19. 49 96
      main/dropbox/dropbox_submit.php
  20. 64 141
      main/dropbox/index.php
  21. 2 2
      main/dropbox/recover_dropbox_files.php
  22. 1 1
      main/exercice/exercise.class.php
  23. 5 1
      main/inc/ajax/admin.ajax.php
  24. 216 7
      main/inc/ajax/model.ajax.php
  25. 92 74
      main/inc/introductionSection.inc.php
  26. 205 205
      main/inc/lib/classmanager.lib.php
  27. 37 25
      main/inc/lib/course.lib.php
  28. 177 102
      main/inc/lib/database.mysqli.lib.php
  29. 132 56
      main/inc/lib/document.lib.php
  30. 47 40
      main/inc/lib/fckeditor/editor/filemanager/connectors/php/config.php
  31. 6 24
      main/inc/lib/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php
  32. 42 54
      main/inc/lib/fckeditor/editor/plugins/ImageManager/config.inc.php
  33. 0 2
      main/inc/lib/fckeditor/editor/plugins/ImageManager/editor.php
  34. 23 25
      main/inc/lib/fckeditor/editor/plugins/ImageManager/editorFrame.php
  35. 6 14
      main/inc/lib/fckeditor/editor/plugins/ImageManager/manager.php
  36. 157 126
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/_ajax_get_details_listing.php
  37. 143 83
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/_ajax_get_thumbnail_listing.php
  38. 17 11
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/_ajax_load_folders.php
  39. 82 56
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_create_folder.php
  40. 14 7
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_delete_file.php
  41. 28 30
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_download.php
  42. 107 115
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_editor_reset.php
  43. 26 32
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_copy.php
  44. 29 32
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_cut.php
  45. 211 62
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_paste.php
  46. 105 75
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_upload.php
  47. 26 23
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_get_file_listing.php
  48. 18 11
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_get_folder_listing.php
  49. 244 205
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_editor.php
  50. 165 194
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_save.php
  51. 18 14
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_thumbnail.php
  52. 79 91
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_undo.php
  53. 46 44
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_login.php
  54. 39 34
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_preview.php
  55. 46 35
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_as_form.php
  56. 81 79
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_name.php
  57. 64 84
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_text.php
  58. 144 148
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_text_editor.php
  59. 677 676
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajaxfilemanager.php
  60. 0 5
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php
  61. 3 4
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.php
  62. 0 131
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.tinymce.php
  63. 0 11
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php
  64. 14 11
      main/inc/lib/fckeditor/fckeditor.php
  65. 6 18
      main/inc/lib/fckeditor/fcktemplates.xml.php
  66. 1 19
      main/inc/lib/fckeditor/myconfig.php
  67. 72 69
      main/inc/lib/fckeditor/repository.php
  68. 9 33
      main/inc/lib/fileDisplay.lib.php
  69. 2 2
      main/inc/lib/groupmanager.lib.php
  70. 10 10
      main/inc/lib/javascript/asciimath/ASCIIMathML.js
  71. 21 5
      main/inc/lib/main_api.lib.php
  72. 83 42
      main/inc/lib/message.lib.php
  73. 2 2
      main/inc/lib/model.lib.php
  74. 15 11
      main/inc/lib/notebook.lib.php
  75. 22 11
      main/inc/lib/notification.lib.php
  76. 96 87
      main/inc/lib/promotion.lib.php
  77. 777 82
      main/inc/lib/sessionmanager.lib.php
  78. 18 0
      main/inc/lib/text.lib.php
  79. 96 69
      main/inc/lib/timeline.lib.php
  80. 50 32
      main/inc/lib/tracking.lib.php
  81. 29 10
      main/inc/lib/usermanager.lib.php
  82. 23 7
      main/inc/local.inc.php
  83. 23 2
      main/install/configuration.dist.php
  84. 2 0
      main/lang/english/trad4all.inc.php
  85. 1 1
      main/lang/french/admin.inc.php
  86. 2 2
      main/lang/french/exercice.inc.php
  87. 1 1
      main/lang/french/forum.inc.php
  88. 1 0
      main/lang/french/install.inc.php
  89. 4 1
      main/lang/french/trad4all.inc.php
  90. 5 4
      main/lang/french/work.inc.php
  91. 43 0
      main/lang/slovak/admin.inc.php
  92. 2 0
      main/lang/slovak/create_course.inc.php
  93. 16 16
      main/lang/slovak/exercice.inc.php
  94. 41 4
      main/lang/slovak/install.inc.php
  95. 23 0
      main/lang/slovak/tracking.inc.php
  96. 1 1
      main/lang/slovak/trad4all.inc.php
  97. 1 0
      main/lang/spanish/trad4all.inc.php
  98. 14 6
      main/mySpace/company_reports.php
  99. 33 8
      main/mySpace/company_reports_resumed.php
  100. 281 280
      main/mySpace/index.php

+ 58 - 58
documentation/installation_guide.html

@@ -23,17 +23,17 @@
             <ul class="nav">
                 <li><a href="index.html">Home</a></li>
                 <li ><a href="readme.html">About</a></li>
-                <li ><a href="license.html">License</a></li>            
-                <li><a href="credits.html">Credits</a></li>            
-                <li><a href="dependencies.html">Dependencies</a></li>            
+                <li ><a href="license.html">License</a></li>
+                <li><a href="credits.html">Credits</a></li>
+                <li><a href="dependencies.html">Dependencies</a></li>
                 <li><a href="changelog.html">Changelog</a></li>
-            </ul>        
+            </ul>
             </div><!--/.nav-collapse -->
         </div>
     </div>
-</div>    
+</div>
 
-<div class="container">    
+<div class="container">
 <h1>Chamilo - Installation Guide</h1>
 
 <p>Thank you for downloading Chamilo</p>
@@ -102,9 +102,9 @@ For instance, on a Ubuntu server,&nbsp;use Shell or Synaptic following the
 
 <h3><span style="font-weight: bold;">MySQL or MariaDB database server</span></h3>
 
-You will need a login and password allowing to manage and create 
+You will need a login and password allowing to manage and create
 a database. Usually, the default configuration on local computers is to allow you to connect as root with an empty password. It is highly recommended to change the password and define a user with access to only a specific database. Please refer to the MySQL or MariaDB documentation in order to do this.<br />
-<span class="muted">Note that this has been greatly simplified since version 1.9, as it 
+<span class="muted">Note that this has been greatly simplified since version 1.9, as it
 previously required to choose between multiple databases and a deprecated
 single-database mode.</span><br />
 
@@ -125,7 +125,7 @@ single-database mode.</span><br />
 values. Consider changing the admin password to remember it.&nbsp;</li>
 </ol>
 <br />
-The following directories need to be readable, writeable and executable by your web server. 
+The following directories need to be readable, writeable and executable by your web server.
 <span class="muted">This usually requires no specific action on Windows servers, but will require a "chmod" under Linux and Mac. See instructions below.</span><br />Replace [chamilo] with the directory where your Chamilo installation is located):
 <ul>
   <li>[chamilo]/main/inc/conf/</li>
@@ -141,15 +141,15 @@ enable CSS styles package upload and sub-language definition:
   <li>[chamilo]/main/css/</li>
   <li>[chamilo]/main/lang/</li>
 </ul>
-Since Chamilo 1.8.8, you can also enable full-text indexing features which 
-require the php5-xapian PHP's extension module to be installed. If you do use 
+Since Chamilo 1.8.8, you can also enable full-text indexing features which
+require the php5-xapian PHP's extension module to be installed. If you do use
 it, you will need to allow your system to write into the sarchdb directory:
 <ul>
   <li>[chamilo]/searchdb</li>
-</ul> 
-If you find a tests/ directory at the root of your package, please delete it. 
-This is a development directory that has not been checked for security issues, 
-an it should *never* be accessible to final users on a production server. 
+</ul>
+If you find a tests/ directory at the root of your package, please delete it.
+This is a development directory that has not been checked for security issues,
+an it should *never* be accessible to final users on a production server.
 
 <p>On Linux, Mac OS X and BSD operating systems you can use the <em>chmod
 0775</em> command for this (although we recommend you seek advice from an
@@ -175,7 +175,7 @@ folders (by right-clicking on them).</p>
 Do not modify the home_*.html files directly. Instead,
 choose "Configure the homepage" in the Chamilo administration section.</p>
 
-<p><span style="font-weight: bold;">Windows</span> : with all-in-one packages 
+<p><span style="font-weight: bold;">Windows</span> : with all-in-one packages
 like XAMPP, you can install Chamilo easily. In this case (and unless you use it
 in production), the login and password for MySQL will probably remain empty.</p>
 
@@ -187,28 +187,28 @@ in production), the login and password for MySQL will probably remain empty.</p>
 <ul>
 
   <li><strong>Protect your configuration directory: </strong>
-make sure no one (but you) can overwrite it. You can find the config directory in 
+make sure no one (but you) can overwrite it. You can find the config directory in
 <em>(chamilo folder)</em>/main/inc/conf.
 Make it read-only (windows/xwindows: right-click the file to edit the
 properties. linux/bsd/macosx: use the chmod 0555 command). The config
-file is created by your web server (Apache + PHP, usually) so you may 
+file is created by your web server (Apache + PHP, usually) so you may
 need to be root user to change its permissions.</li>
 
   <li><strong>Protect your installation folder: </strong>
 if the <em>(chamilo 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, 
-delete it completely or edit its properties so no one can read or 
+out of the web directories so it is not accessible, change its name,
+delete it completely or edit its properties so no one can read or
 execute it.</li>
 
   <li><strong>For better security: </strong>
 making the files world-writeable will help you install, and it solves many
 issues for people without much admin experience. However, it's more
-secure to make a distinct user owner of all the chamilo files and folders, 
-and only give read access to the web server to all files, and write access 
-only to the directories previously mentioned. This way, these files need 
-only be readable and writeable by the Apache process owner, not by the 
+secure to make a distinct user owner of all the chamilo files and folders,
+and only give read access to the web server to all files, and write access
+only to the directories previously mentioned. This way, these files need
+only be readable and writeable by the Apache process owner, not by the
 entire world. It would also be adviseable to make all writeable directory
 refuse the interpretation of PHP files (except for the root of the courses
 directories). Don't hesitate to hire an experienced administrator to do that,
@@ -236,9 +236,9 @@ To get the best out of Chamilo, you need to finetune your PHP settings. Consider
 
 <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 : 
+  <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 the two values to optimise the server</li>
   <li>we recommend the following values : </li>
@@ -264,12 +264,12 @@ these ones:</p>
 
 <p>
 Past Chamilo versions required register_globals to be set to On. This is
-no longer necessary, this can (and should) be set to Off. 
+no longer necessary, this can (and should) be set to Off.
 <span class="muted">It is considered a bad choice in terms of security to set register_globals to On.</a></p>
 
-<p><strong>Note:</strong> if you are using PHP 5.3 or higher, you need to set 
+<p><strong>Note:</strong> if you are using PHP 5.3 or higher, you need to set
 your <em>date.timezone</em> setting to whatever your server's timezone is.
-For example, if your server is in the 'America/New_York' timezone, set this 
+For example, if your server is in the 'America/New_York' timezone, set this
 in your php.ini:</p>
 
 <div class="code">
@@ -306,7 +306,7 @@ date.timezone = 'America/New_York'
 
 
 <hr />
-<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Upgrade from a 
+<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Upgrade from a
 previous version of Chamilo LMS (1.*) or Dok€os (&lt;2.0)</h2>
 Before upgrading, we <b>heavily</b> recommend you do a full backup of the previous
 Chamilo or Dok€os directories and databases. If you are unsure how to achieve this
@@ -319,9 +319,9 @@ GNU/GPLv3 and we cannot be held responsible for what would happen to your data
 without professional supervision). This is why we *really* recommend you take
 a full backup of your system before you upgrade.</em>
 <br />
-<div class="muted"> NOTE: This version of Chamilo can only be used to upgrade from 
-smaller versions of Chamilo or Dok€os. For example, you cannot use the normal 
-upgrade scripts from Chamilo 1.9 to upgrade from Dok€os 2.0. If you need this, 
+<div class="muted"> NOTE: This version of Chamilo can only be used to upgrade from
+smaller versions of Chamilo or Dok€os. For example, you cannot use the normal
+upgrade scripts from Chamilo 1.9 to upgrade from Dok€os 2.0. If you need this,
 please contact one of the Chamilo Association's official providers <providers@chamilo.org>)</div>
 
 <p></p>
@@ -360,12 +360,12 @@ As this is only a minor version change from previous 1.9.* versions of Chamilo,
   <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>
-A bunch of Chamilo administrators have reported minor issues with the migration between versions considerably apart (like from Dok€os to Chamilo). 
+A bunch of Chamilo administrators have reported minor issues with the migration between versions considerably apart (like from Dok€os to Chamilo).
 This might include loosing some assignments or forum posts. To avoid any ugly effect on your users, we recommend you first establish a checklist
-of all the content that is critical to you, and that you keep a working copy of your previous site on the side. This way, it will be easier to 
+of all the content that is critical to you, and that you keep a working copy of your previous site on the side. This way, it will be easier to
 manage the transition by letting your users get access to their contents from the previous site and making it easier for you to compare the two.
 If you are experiencing difficulties, consider asking for help from a PHP developer or hiring an <a href="http://www.chamilo.org/en/providers" target="_blank">official Chamilo provider</a>. They will make sure
-you get the best our of your Chamilo migration. 
+you get the best our of your Chamilo migration.
 <br />
 
 <span class="muted">* Styles and images are located in the main/css or main/img
@@ -536,7 +536,7 @@ Newer distributions also allow downloading rpms for additional packages.</p>
 
 <h3><b>Activating LDAP in Chamilo</b></h3>
 
-<p class="muted">Note: The LDAP mechanism has been changed in 1.9. As a result, some of the following information might not be correct. Please check 
+<p class="muted">Note: The LDAP mechanism has been changed in 1.9. As a result, some of the following information might not be correct. Please check
 the configuration settings inside Chamilo to learn the details.</p>
 
 <p>
@@ -666,8 +666,8 @@ Here is an example:
 		&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>
@@ -679,22 +679,22 @@ Here is an example:
 
     </li>
 
-	
+
 	<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:
 	    <div class="code">
 	        sudo chmod a+x mimetex.cgi
 	    </div>
 	</li>
 	<li>6. Make sure that the file mimetex.cgi (or mimetex.exe) has been uploaded in <b>BINARY</b> format.
-	
-	       This is another common problem; the fix is just to re-upload the file in ASCII format. 
+
+	       This is another common problem; the fix is just to re-upload the file in ASCII format.
 	       You'll need to consult your FTP program's documentation to figure out how to switch modes.
-           BINARY mode is used for non-text items, such as executables (*.exe), zip files (*.zip), image files (*.jpg, *.gif) and the like. 
+           BINARY mode is used for non-text items, such as executables (*.exe), zip files (*.zip), image files (*.jpg, *.gif) and the like.
            ASCII mode needs to be used for text only documents, which includes *.txt, *.cgi, *.pl *.css, *.html, etc.
            <br />
-           You can also try to re upload the mimetex file using the "Upload file" in the "Filemanager" tool in CPanel/Plesk 
+           You can also try to re upload the mimetex file using the "Upload file" in the "Filemanager" tool in CPanel/Plesk
     </li>
-    
+
 </ul>
 
 <p>As a result of this procedure, a new button becomes available in your Chamilo online editor, that gives you possibility
@@ -745,7 +745,7 @@ You may need to alter the setting to be for example:</p>
     <li><div class="code">var AMTcgiloc = "http://mychamiloserver.org/cgi-bin/mimetex.cgi";</div></li>
     <li><div class="code">var AMTcgiloc = "http://mychamiloserver.org/cgi-bin/mathtex.cgi";</div></li>
     <li><div class="code">var AMTcgiloc = "http://www.mathtran.org/cgi-bin/mathtran?tex=";</div></li>
-    <li><div class="code">var AMTcgiloc = "http://chart.apis.google.com/chart?cht=tx&amp;chs=1x0&amp;chl=";</div></li>
+    <li><div class="code">var AMTcgiloc = "http://chart.googleapis.com/chart?cht=tx&amp;chs=1x0&amp;chl=";</div></li>
     <li>... or something else</li>
 </ul>
 <p>For testing how the variable <strong>AMTcgiloc</strong> may be set, there are some examples (as comments) inside the script.</p>
@@ -765,11 +765,11 @@ sudo apt-get install php5-xapian
 sudo /etc/init.d/apache2 restart
 </pre>
 
-Then go to your administration page -&gt; Configuration settings -&gt; Search 
-and enable the search tool. Follow the recommendations on the page to get the 
-complete indexing suite installed. Once you're done, all documents you import 
+Then go to your administration page -&gt; Configuration settings -&gt; Search
+and enable the search tool. Follow the recommendations on the page to get the
+complete indexing suite installed. Once you're done, all documents you import
 into your Chamilo portal in a recognized format will be indexed and searchable.
-Chamilo Administrators training (which you can ask any <a href="http://www.chamilo.org/en/providers">Chamilo's Official 
+Chamilo Administrators training (which you can ask any <a href="http://www.chamilo.org/en/providers">Chamilo's Official
 Provider</a> for) include a full review of the full-text search feature.
 </p>
 
@@ -789,23 +789,23 @@ Then go to your administration page -&gt; <i>Chamilo Rapid</i> and set the host
 <hr style="width: 100%; height: 2px;" />
 <h2><a name="12._Setting_cron_up"></a>Setting chronological tasks</h2>
 <p>
-Since Chamilo 1.8.8, a few tasks need to be executed regularly in order to get 
-the best out of your server resources. One of such tasks (and the only one 
-around at the time of Chamilo 1.8.8) is the sending of internal messaging 
+Since Chamilo 1.8.8, a few tasks need to be executed regularly in order to get
+the best out of your server resources. One of such tasks (and the only one
+around at the time of Chamilo 1.8.8) is the sending of internal messaging
 notifications by e-mail, i.e. when you receive an e-mail from another person or
 from a group inside the internal messaging system of Chamilo, if all e-mails are
-sent immediately, then you might not have the chance to receive them at your 
-pace, once a day or even once a week. For cases like this you, as a Chamilo 
+sent immediately, then you might not have the chance to receive them at your
+pace, once a day or even once a week. For cases like this you, as a Chamilo
 administrator, should setup a cron process on the server to check the queue of
 e-mails and send is timely.</p>
 <p>
 Setting up a cron task is easy and there are several ways to do it. We recommend
-you have a look at the <a href="http://drupal.org/cron">Drupal documentation 
+you have a look at the <a href="http://drupal.org/cron">Drupal documentation
 for setting up cron</a> and define your own cron process as:
 <pre>
 35 * * * * wget -O - -q -t 1 http://campus.example.com/main/cron/run.php
 </pre>
-Make sure you have a look into run.php as maybe you want to change a few 
+Make sure you have a look into run.php as maybe you want to change a few
 settings there.
 </p>
 

+ 26 - 26
documentation/installation_guide_es_ES.html

@@ -20,15 +20,15 @@
             <ul class="nav">
                 <li><a href="index.html">Home</a></li>
                 <li ><a href="readme.html">About</a></li>
-                <li ><a href="license.html">License</a></li>            
-                <li><a href="credits.html">Credits</a></li>            
-                <li><a href="dependencies.html">Dependencies</a></li>            
+                <li ><a href="license.html">License</a></li>
+                <li><a href="credits.html">Credits</a></li>
+                <li><a href="dependencies.html">Dependencies</a></li>
                 <li><a href="changelog.html">Changelog</a></li>
-            </ul>        
+            </ul>
             </div><!--/.nav-collapse -->
         </div>
     </div>
-</div>    
+</div>
 
 
 <div class="container">
@@ -36,13 +36,13 @@
     <li>
         <a href="index.html">Documentación</a>
         <span class="divider">/</span>
-    </li>    
+    </li>
     <li>Guía de Instalación</li>
-</ul>   
+</ul>
 <h1>Chamilo 1.9 - Guía de Instalación</h1>
 
 <p>Gracias por descargar Chamilo, la suite de aprendizaje de código abierto profesional.</p>
-<ul>  
+<ul>
   <li>Prueba Chamilo en <a href="http://campus.chamilo.org">nuesto Campus libre</a></li>
 </ul>
 
@@ -190,7 +190,7 @@ seleccione "Configurar la página de inicio" en la sección de administración d
   <li><strong>Proteger su directorio de instalación: </strong>si el (directorio de Chamilo) directorio /main/install sigue accesible, alguien podría instalar de nuevo sobre la versión existente (usted puede perder sus datos de esta manera). Por ello es muy importante que mueva el directorio a algún lugar fuera de los directorios web para que no se encuentre accesible, cambie su nombre, bórrelo completamente o edite sus propiedades para que nadie pueda leerlo o ejecutarlo.</li>
 
   <li><strong>Para mayor seguridad: </strong> hacer que todos los archivos posean permisos de escritura facilita la instalación y resuelve muchas dudas a las personas con poca experiencia en administración. Sin embargo, es más seguro hacer que el propietario de los archivos y carpetas de Chamilo sea un usuario distinto y conceder sólo al servidor web permisos de lectura sobre todos los ficheros, y permisos de escritura a los directorios previamente mencionados. De esta manera, estos archivos sólo necesitan ser accesibles y escribibles por el propietario el proceso Apache, no por el mundo entero. También sería recomendable hacer que todos los directorios con permisos de escritura rechazaran la interpretación de los archivos PHP ( a excepción de la raíz de los directorios de cursos). No dude en contratar a un administrador con experiencia para hacer eso, puede que sea un poco más caro ahora, pero estará feliz de no tener que perder todos sus datos por el ataque de un hacker a su sitio.</li>
-  
+
   <li><strong>Configurar su instalación de Chamilo: </strong>
 en la sección de administración de Chamilo, usted puede usar las Opciones de Configuración de Chamilo para ajustar el comportamiento de su instalación.</li>
 
@@ -259,7 +259,7 @@ date.timezone = 'America/Lima'
 <li>php-ctype</li>
 <li>php-gd</li>
 <li>php-iconv</li>
-<li>php-json</li> 
+<li>php-json</li>
 <li>php-mbstring</li>
 <li>php-intl</li>
 <li>php-curl</li>
@@ -369,7 +369,7 @@ directorio actual de la versión antigua</li>
 </p>
 <p>
 <em> NOTA: </em> La actualización desde 1.6.x a 1.9.x implica una revisión de
-los gráficos y estilos personalizados. La nueva versión usa un completo nuevo conjunto 
+los gráficos y estilos personalizados. La nueva versión usa un completo nuevo conjunto
 de iconos y estilos, lo cual significa que aquellos provenientes de la versión 1.6 no pueden ser
 simplemente reusados. La buena noticia es que la versión 1.9.x le permite crear
 su propio estilo en un directorio css separado, el cual se puede reusar en
@@ -603,9 +603,9 @@ Usted puede habilitar la escritura de ecuaciones matemáticas dentro del editor
 	(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 sólo a alguna de ellas (por ej., documentos y ejercicios)<br />
 	        <br />
 			</li>
@@ -617,34 +617,34 @@ Usted puede habilitar la escritura de ecuaciones matemáticas dentro del editor
     <li>6. Realice estos cambios:
 
 	<i>Agregar el directorio cgi-bin correspondiente a su configuración de Apache puede ser realizada 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 realizado 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/chamilo/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>
 	</li>
-	
+
 	<li>7. Asegurarse que el archivo mimetex.cgi (o mimetex.exe) ha sido subido al servidor usando el formato BINARY. Es posible que el servidor de un error 500 cuando se intenta entrar a cgi-bin/mimetex.cgi a pesar de que los permisos están correctos.
 	   Probar volviendo a subir el archivo usando FTP (ASCII format) o si no usando el "administrador de archivos" o CPanel. Si el error persiste contactar con el administrador del servidor para habilitar el acceso público del archivo cgi-bin/mimetex.cgi.
 	</li>
@@ -691,7 +691,7 @@ Podría necesitar modificar el ejemplo para tener algo como:</p>
         <li><div class="code">var AMTcgiloc = "http://mychamiloserver.org/cgi-bin/mimetex.cgi";</div></li>
         <li><div class="code">var AMTcgiloc = "http://mychamiloserver.org/cgi-bin/mathtex.cgi";</div></li>
         <li><div class="code">var AMTcgiloc = "http://www.mathtran.org/cgi-bin/mathtran?tex=";</div></li>
-        <li><div class="code">var AMTcgiloc = "http://chart.apis.google.com/chart?cht=tx&amp;chs=1x0&amp;chl=";</div></li>
+        <li><div class="code">var AMTcgiloc = "http://chart.googleapis.com/chart?cht=tx&amp;chs=1x0&amp;chl=";</div></li>
         <li>... o algo similar</li>
 </ul>
 <p>Para formas de probar como la variable <strong>AMTcgiloc</strong> tiene que ser configurada, existen unos ejemplos (en comentario) dentro del script.</p>

+ 1 - 1
license.txt

@@ -11,7 +11,7 @@ Copyright (c) 2003-2007 Ghent University (UGent)
 Copyright (c) 2001-2004 Universite catholique de Louvain (UCL)
 Copyright (c) 2003-2008 Vrije Universiteit Brussel (VUB)
 Copyright (c) 2004-2008 Hoogeschool Gent (HoGent)
-	
+
 For a full list of contributors detaining copyrights over parts of
 the Chamilo software, see "documentation/credits.html".
 The full license can be read in "documentation/license.html".

+ 1 - 6
main/admin/course_request_accepted.php

@@ -41,7 +41,6 @@ $course_validation_feature = api_get_setting('course_validation') == 'true';
 $delete_course_request = intval($_GET['delete_course_request']);
 $message = trim(Security::remove_XSS(stripslashes(urldecode($_GET['message']))));
 $is_error_message = !empty($_GET['is_error_message']);
-$keyword = Database::escape_string(trim($_GET['keyword']));
 
 if ($course_validation_feature) {
 
@@ -99,12 +98,8 @@ function get_number_of_requests() {
  * Get course data to display
  */
 function get_request_data($from, $number_of_items, $column, $direction) {
-    global $keyword;
-
+    $keyword = Database::escape_string(trim($_GET['keyword']));
     $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
-    $users_table = Database :: get_main_table(TABLE_MAIN_USER);
-    $course_users_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-
     $sql = "SELECT id AS col0,
                    code AS col1,
                    title AS col2,

+ 2 - 135
main/admin/index.php

@@ -307,6 +307,7 @@ $admin_ajax_url = api_get_path(WEB_AJAX_PATH).'admin.ajax.php';
 $tpl = new Template();
 $tpl->assign('web_admin_ajax_url', $admin_ajax_url);
 $tpl->assign('blocks', $blocks);
+// The template contains the call to the AJAX version checker
 $admin_template = $tpl->get_template('admin/settings_index.tpl');
 $content = $tpl->fetch($admin_template);
 $tpl->assign('content', $content);
@@ -334,138 +335,4 @@ function register_site() {
     // Reload the settings.
 }
 
-
-/**
- * Displays either the text for the registration or the message that the installation is (not) up to date
- *
- * @return string html code
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @version august 2006
- * @todo have a 6monthly re-registration
- */
-function version_check() {
-    $tbl_settings = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-    $sql = 'SELECT selected_value FROM  '.$tbl_settings.' WHERE variable="registered" ';
-    $result = Database::query($sql);
-    $row = Database::fetch_array($result, 'ASSOC');
-
-    // The site has not been registered yet.
-    $return = '';
-    if ($row['selected_value'] == 'false') {
-        $return .= get_lang('VersionCheckExplanation');
-        $return .= '<form class="well" action="'.api_get_self().'" id="VersionCheck" name="VersionCheck" method="post">';
-        $return .= '<label class="checkbox"><input type="checkbox" name="donotlistcampus" value="1" id="checkbox" />'.get_lang('HideCampusFromPublicPlatformsList');
-        $return .= '</label><button type="submit" class="btn btn-primary" name="Register" value="'.get_lang('EnableVersionCheck').'" id="register" >'.get_lang('EnableVersionCheck').'</button>';
-        $return .= '</form>';
-        check_system_version();
-    } else {
-        // site not registered. Call anyway
-        $return .= check_system_version();
-    }
-    return $return;
-}
-
-/**
- * Check if the current installation is up to date
- * The code is borrowed from phpBB and slighlty modified
- * @author The phpBB Group <support@phpbb.com> (the code)
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University (the modifications)
- * @author Yannick Warnier <ywarnier@beeznest.org> for the move to HTTP request
- * @copyright (C) 2001 The phpBB Group
- * @return language string with some layout (color)
- */
-function check_system_version() {
-    global $_configuration;
-    $system_version = trim($_configuration['system_version']); // the chamilo version of your installation
-
-    if (ini_get('allow_url_fopen') == 1) {
-        // The number of courses
-        $number_of_courses = Statistics::count_courses();
-
-        // The number of users
-        $number_of_users = Statistics::count_users();
-        $number_of_active_users = Statistics::count_users(null,null,null,true);
-
-        $data = array(
-            'url' => api_get_path(WEB_PATH),
-            'campus' => api_get_setting('siteName'),
-            'contact' => api_get_setting('emailAdministrator'),
-            'version' => $system_version,
-            'numberofcourses' => $number_of_courses,
-            'numberofusers' => $number_of_users,
-            'numberofactiveusers' => $number_of_active_users,
-            //The donotlistcampus setting recovery should be improved to make
-            // it true by default - this does not affect numbers counting
-            'donotlistcampus' => api_get_setting('donotlistcampus'),
-            'organisation' => api_get_setting('Institution'),
-            'language' => api_get_setting('platformLanguage'),
-            'adminname' => api_get_setting('administratorName').' '.api_get_setting('administratorSurname'),
-        );
-
-        $res = _http_request('version.chamilo.org', 80, '/version.php', $data);
-
-        if ($res != 0) {
-            $version_info = $res;
-
-            if ($system_version != $version_info) {
-                $output = '<br /><span style="color:red">' . get_lang('YourVersionNotUpToDate') . '. '.get_lang('LatestVersionIs').' <b>Chamilo '.$version_info.'</b>. '.get_lang('YourVersionIs').' <b>Chamilo '.$system_version. '</b>. '.str_replace('http://www.chamilo.org', '<a href="http://www.chamilo.org">http://www.chamilo.org</a>', get_lang('PleaseVisitOurWebsite')).'</span>';
-            } else {
-                $output = '<br /><span style="color:green">'.get_lang('VersionUpToDate').': Chamilo '.$version_info.'</span>';
-            }
-        } else {
-            $output = '<span style="color:red">' . get_lang('ImpossibleToContactVersionServerPleaseTryAgain') . '</span>';
-        }
-    } else {
-        $output = '<span style="color:red">' . get_lang('AllowurlfopenIsSetToOff') . '</span>';
-    }
-    return $output;
-}
-
-/**
- * Function to make an HTTP request through fsockopen (specialised for GET)
- * Derived from Jeremy Saintot: http://www.php.net/manual/en/function.fsockopen.php#101872
- * @param string IP or hostname
- * @param int    Target port
- * @param string URI (defaults to '/')
- * @param array  GET data
- * @param float  Timeout
- * @param bool   Include HTTP Request headers?
- * @param bool   Include HTTP Response headers?
- */
-function _http_request($ip, $port = 80, $uri = '/', $getdata = array(), $timeout = 1, $req_hdr = false, $res_hdr = false) {
-    $verb = 'GET';
-    $ret = '';
-    $getdata_str = count($getdata) ? '?' : '';
-
-    foreach ($getdata as $k => $v) {
-                $getdata_str .= urlencode($k) .'='. urlencode($v) . '&';
-    }
-
-    $crlf = "\r\n";
-    $req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf;
-    $req .= 'Host: '. $ip . $crlf;
-    $req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf;
-    $req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf;
-    $req .= 'Accept-Language: en-us,en;q=0.5' . $crlf;
-    $req .= 'Accept-Encoding: deflate' . $crlf;
-    $req .= 'Accept-Charset: utf-8;q=0.7,*;q=0.7' . $crlf;
-
-    $req .= $crlf;
-
-    if ($req_hdr) { $ret .= $req; }
-    if (($fp = @fsockopen($ip, $port, $errno, $errstr, $timeout)) == false) {
-        return "Error $errno: $errstr\n";
-    }
-
-    stream_set_timeout($fp, $timeout);
-    $r = @fwrite($fp, $req);
-    $line = @fread($fp,512);
-    $ret .= $line;
-    fclose($fp);
-
-    if (!$res_hdr) {
-        $ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);
-    }
-
-    return trim($ret);
-}
+// Note: version checking mechanism has now been moved to main/inc/ajax/admin.ajax.php

+ 30 - 24
main/admin/session_course_user_list.php

@@ -28,18 +28,17 @@ if (empty($id_session )) {
 $course_code    = Database::escape_string(trim($_GET['course_code']));
 $page           = intval($_GET['page']);
 $action         = $_REQUEST['action'];
-$default_sort = api_sort_by_first_name() ? 'firstname':'lastname';
+$default_sort   = api_sort_by_first_name() ? 'firstname':'lastname';
 $sort           = in_array($_GET['sort'], array('lastname','firstname','username')) ? $_GET['sort'] : $default_sort;
 $idChecked      = (is_array($_GET['idChecked']) ? $_GET['idChecked'] : (is_array($_POST['idChecked']) ? $_POST['idChecked'] : null));
-
 $direction      = isset($_GET['direction']) && in_array($_GET['direction'], array('desc','asc')) ? $_GET['direction'] : 'desc';
 
 if (is_array($idChecked)) {
-	$my_temp = array();
-	foreach ($idChecked as $id){
-		$my_temp[]= intval($id);// forcing the intval
-	}
-	$idChecked = $my_temp;
+    $my_temp = array();
+    foreach ($idChecked as $id) {
+        $my_temp[]= intval($id);// forcing the intval
+    }
+    $idChecked = $my_temp;
 }
 
 $sql = "SELECT s.name, c.title  FROM $tbl_session_rel_course src
@@ -48,16 +47,14 @@ $sql = "SELECT s.name, c.title  FROM $tbl_session_rel_course src
 		WHERE src.id_session='$id_session' AND src.course_code='".Database::escape_string($course_code)."' ";
 
 $result = Database::query($sql);
-
-if (!list($session_name,$course_title)=Database::fetch_row($result)) {
+if (!list($session_name,$course_title) = Database::fetch_row($result)) {
 	header('Location: session_course_list.php?id_session='.$id_session);
 	exit();
 }
 
-
 switch($action) {
     case 'delete':
-        if (is_array($idChecked) && count($idChecked)>0 ) {
+        if (is_array($idChecked) && count($idChecked)>0) {
             array_map('intval', $idChecked);
             $idChecked = implode(',',$idChecked);
         }
@@ -82,10 +79,24 @@ $from   = $page * $limit;
 $is_western_name_order = api_is_western_name_order();
 
 //scru.status<>2  scru.course_code='".$course_code."'
-$sql = "SELECT DISTINCT u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
-             FROM $tbl_session_rel_user s INNER JOIN $tbl_user u ON (u.user_id=s.id_user) LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id=scru.id_user AND  scru.course_code = '".$course_code."' )
-             WHERE s.id_session='$id_session'
-             ORDER BY $sort $direction LIMIT $from,".($limit+1);
+/*$sql = "SELECT DISTINCT
+         u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
+         FROM $tbl_session_rel_user s
+         INNER JOIN $tbl_user u ON (u.user_id=s.id_user)
+         LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id=scru.id_user AND  scru.course_code = '".$course_code."' )
+         WHERE s.id_session='$id_session'
+         ORDER BY $sort $direction
+         LIMIT $from,".($limit+1);*/
+
+$sql = "SELECT DISTINCT
+         u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
+         FROM $tbl_session_rel_user s
+         INNER JOIN $tbl_user u ON (u.user_id=s.id_user)
+         LEFT JOIN $tbl_session_rel_course_rel_user scru
+         ON (s.id_session = scru.id_session AND s.id_user = scru.id_user AND scru.course_code = '".$course_code."' )
+         WHERE s.id_session='$id_session'
+         ORDER BY $sort $direction
+         LIMIT $from,".($limit+1);
 
 if ($direction == 'desc') {
     $direction = 'asc';
@@ -94,16 +105,15 @@ if ($direction == 'desc') {
 }
 
 $result = Database::query($sql);
-$Users  = Database::store_result($result);
+$users  = Database::store_result($result);
 
-$nbr_results = sizeof($Users);
+$nbr_results = sizeof($users);
 
 $tool_name = get_lang('Session').': '.$session_name.' - '.get_lang('Course').': '.$course_title;
 
 $interbreadcrumb[] = array("url" => "index.php","name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array("url" => "session_list.php","name" => get_lang('SessionList'));
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id_session,"name" => get_lang('SessionOverview'));
-//$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);
 
@@ -132,7 +142,6 @@ if($nbr_results > $limit) {
 ?>
 </div>
 <br />
-
 <table class="data_table" width="100%">
 <tr>
   <th>&nbsp;</th>
@@ -146,16 +155,14 @@ if($nbr_results > $limit) {
   <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=username&direction=<?php echo urlencode($direction); ?>"><?php echo get_lang('Login');?></a></th>
   <th><?php echo get_lang('Actions');?></th>
 </tr>
-
 <?php
 $i=0;
+foreach ($users as $key => $enreg) {
 
-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) { ?>
@@ -182,9 +189,8 @@ foreach ($Users as $key=>$enreg) {
     <?php
         $i=$i ? 0 : 1;
 }
-unset($Users);
+unset($users);
 ?>
-
 </table>
 <br />
 <div align="left">

+ 17 - 6
main/admin/session_import.php

@@ -49,8 +49,8 @@ if ($_POST['formSent']) {
         $form_sent = $_POST['formSent'];
         $file_type = $_POST['file_type'];
         $send_mail = $_POST['sendMail'] ? 1 : 0;
-        //$updatesession = $_POST['updatesession'] ? 1 : 0;
-        $updatesession = 0;
+        $isOverwrite = $_POST['overwrite'] ? 1 : 0;
+        $deleteUsersNotInList = isset($_POST['delete_users_not_in_list']) ? true : false;
         $sessions = array();
 
         $session_counter = 0;
@@ -458,10 +458,20 @@ if ($_POST['formSent']) {
                 $error_message .= get_lang('XMLNotValid');
             }
         } else {
-
             // CSV
-
-            $result = SessionManager::importCSV($_FILES['import_file']['tmp_name'], $updatesession, api_get_user_id());
+            $result = SessionManager::importCSV(
+                $_FILES['import_file']['tmp_name'],
+                $isOverwrite,
+                api_get_user_id(),
+                null,
+                array(),
+                null,
+                null,
+                null,
+                1,
+                array(),
+                $deleteUsersNotInList
+            );
             $error_message = $result['error_message'];
             $session_counter = $result['session_counter'];
         }
@@ -512,10 +522,11 @@ if (!empty($error_message)) {
 $form = new FormValidator('import_sessions', 'post', api_get_self(), null, array('enctype' => 'multipart/form-data'));
 $form->addElement('hidden', 'formSent', 1);
 $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
-
 $form->addElement('radio', 'file_type', array(get_lang('FileType'), '<a href="example_session.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>'), 'CSV', 'csv');
 $form->addElement('radio', 'file_type', array(null, '<a href="example_session.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>'), 'XML', 'xml');
 
+$form->addElement('checkbox', 'overwrite', null, get_lang('IfSessionExistsUpdate'));
+$form->addElement('checkbox', 'delete_users_not_in_list', null, get_lang('DeleteUsersNotInList'));
 $form->addElement('checkbox', 'sendMail', null, get_lang('SendMailToUsers'));
 $form->addElement('button', 'submit', get_lang('ImportSession'));
 

+ 17 - 0
main/admin/statistics/statistics.lib.php

@@ -109,6 +109,23 @@ class Statistics {
         return $obj->number;
     }
 
+    /**
+     * Count sessions
+     * @return int Number of sessions counted
+     */
+    static function count_sessions() {
+        $session_table = Database :: get_main_table(TABLE_MAIN_SESSION);
+        $access_url_rel_session_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+        if (api_is_multiple_url_enabled()) {
+            $current_url_id = api_get_current_access_url_id();
+            $sql = "SELECT COUNT(id) AS number FROM ".$session_table." as s, ".$access_url_rel_session_table." as u WHERE u.session_id=s.id AND access_url_id='".$current_url_id."'";
+        } else {
+            $sql = "SELECT COUNT(id) AS number FROM ".$session_table." ";
+        }
+        $res = Database::query($sql);
+        $obj = Database::fetch_object($res);
+        return $obj->number;
+    }
     /**
      * Count activities from track_e_default_table
      * @return int Number of activities counted

+ 5 - 2
main/admin/user_edit.php

@@ -250,8 +250,11 @@ $group[] =$form->createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
 $group[] =$form->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']);
+// Registration User and Date
+$creatorInfo = api_get_user_info($user_data['creator_id']);
+$date = sprintf(get_lang('CreatedByXYOnZ'), 'user_information.php?user_id='.$user_data['creator_id'], $creatorInfo['username'], $user_data['registration_date']);
+$form->addElement('html', '<div class="control-group"><label class="control-label">'.get_lang('RegistrationDate').'</label><div class="controls">'.$date.'</div></div>');
+
 
 if (!$user_data['platform_admin']) {
 	// Expiration Date

+ 50 - 25
main/admin/user_import.php

@@ -2,7 +2,6 @@
 /* For licensing terms, see /license.txt */
 /**
  * This tool allows platform admins to add users by uploading a CSV or XML file
- * @todo Add some langvars to DLTT
  * @package chamilo.admin
  */
 
@@ -22,7 +21,8 @@ require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 // Set this option to true to enforce strict purification for usenames.
 $purification_option_for_usernames = false;
 
-function validate_data($users) {
+function validate_data($users)
+{
     global $defined_auth_sources;
     $errors = array();
     $usernames = array();
@@ -85,7 +85,8 @@ function validate_data($users) {
 /**
  * Add missing user-information (which isn't required, like password, username etc).
  */
-function complete_missing_data($user) {
+function complete_missing_data($user)
+{
     global $purification_option_for_usernames;
     // 1. Create a username if necessary.
     if (UserManager::is_username_empty($user['UserName'])) {
@@ -110,7 +111,7 @@ function complete_missing_data($user) {
 
 /**
  * Save the imported data
- * @param   array   List of users
+ * @param   array   $users List of users
  * @return  void
  * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
  */
@@ -196,7 +197,8 @@ function save_data($users)
  * @param string $file Path to the CSV-file
  * @return array All userinformation read from the file
  */
-function parse_csv_data($file) {
+function parse_csv_data($file)
+{
     $users = Import :: csv_to_array($file);
     foreach ($users as $index => $user) {
         if (isset ($user['Courses'])) {
@@ -208,30 +210,36 @@ function parse_csv_data($file) {
 }
 /**
  * XML-parser: handle start of element
+ * @param   string  $parser Deprecated?
+ * @param   string  $data The data to be parsed
  */
-function element_start($parser, $data) {
+function element_start($parser, $data)
+{
     $data = api_utf8_decode($data);
     global $user;
     global $current_tag;
     switch ($data) {
-        case 'Contact' :
+        case 'Contact':
             $user = array ();
             break;
-        default :
+        default:
             $current_tag = $data;
     }
 }
 
 /**
  * XML-parser: handle end of element
+ * @param   string  $parser Deprecated?
+ * @param   string  $data   The data to be parsed
  */
-function element_end($parser, $data) {
+function element_end($parser, $data)
+{
     $data = api_utf8_decode($data);
     global $user;
     global $users;
     global $current_value;
     switch ($data) {
-        case 'Contact' :
+        case 'Contact':
             if ($user['Status'] == '5') {
                 $user['Status'] = STUDENT;
             }
@@ -240,7 +248,7 @@ function element_end($parser, $data) {
             }
             $users[] = $user;
             break;
-        default :
+        default:
             $user[$data] = $current_value;
             break;
     }
@@ -248,8 +256,12 @@ function element_end($parser, $data) {
 
 /**
  * XML-parser: handle character data
+ * @param   string  $parser Parser (deprecated?)
+ * @param   string  $data The data to be parsed
+ * @return  void
  */
-function character_data($parser, $data) {
+function character_data($parser, $data)
+{
     $data = trim(api_utf8_decode($data));
     global $current_value;
     $current_value = $data;
@@ -258,12 +270,10 @@ function character_data($parser, $data) {
 /**
  * Read the XML-file
  * @param string $file Path to the XML-file
- * @return array All userinformation read from the file
+ * @return array All user information read from the file
  */
-function parse_xml_data($file) {
-    global $current_tag;
-    global $current_value;
-    global $user;
+function parse_xml_data($file)
+{
     global $users;
     $users = array();
     $parser = xml_parser_create('UTF-8');
@@ -276,10 +286,11 @@ function parse_xml_data($file) {
 }
 
 $this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script(true);
+api_protect_admin_script(true, null, 'login');
 
 
 $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
+
 if (is_array($extAuthSource)) {
     $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
 }
@@ -292,7 +303,7 @@ $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
 $user_id_error = array();
 $error_message = '';
 
-if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
+if ($_POST['formSent'] and $_FILES['import_file']['size'] !== 0) {
     $file_type = $_POST['file_type'];
     Security::clear_token();
     $tok = Security::get_token();
@@ -354,7 +365,9 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
         $warning_message = '<ul>';
         foreach ($errors as $index => $error_user) {
             $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
-            $warning_message .= '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
+            $warning_message .=
+                '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.
+                api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
             $warning_message .= '</li>';
         }
         $warning_message .= '</ul>';
@@ -384,8 +397,20 @@ $form->addElement('header', '', $tool_name);
 $form->addElement('hidden', 'formSent');
 $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
 $group = array();
-$group[] = $form->createElement('radio', 'file_type', '', 'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
-$group[] = $form->createElement('radio', 'file_type', null, 'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
+$group[] = $form->createElement(
+    'radio',
+    'file_type',
+    '',
+    'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)',
+    'csv'
+    );
+$group[] = $form->createElement(
+    'radio',
+    'file_type',
+    null,
+    'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)',
+    'xml'
+    );
 $form->addGroup($group, '', get_lang('FileType'), '<br/>');
 
 $group = array();
@@ -423,8 +448,8 @@ if ($count_fields > 0) {
 
     <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;
-<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;<br />
+<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<span style="color:red;"><?php if (count($list) > 0) echo implode(';', $list).';'; ?></span>Courses;
+<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<span style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></span>xxx1|xxx2|xxx3;<br />
 </pre>
     </blockquote>
 
@@ -443,7 +468,7 @@ if ($count_fields > 0) {
         <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<?php if ($result_xml != '') { echo '<br /><font style="color:red;">', $result_xml; echo '</font>'; } ?>&lt;/Status&gt;
+        &lt;Status&gt;user/teacher/drh<?php if ($result_xml != '') { echo '<br /><span style="color:red;">', $result_xml; echo '</span>'; } ?>&lt;/Status&gt;
         &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
         &lt;/Contact&gt;
 &lt;/Contacts&gt;

+ 70 - 20
main/admin/user_information.php

@@ -1,10 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *    @author Bart Mollet
- *    @package chamilo.admin
+ * Script showing information about a user (name, e-mail, courses and sessions)
+ * @author Bart Mollet
+ * @package chamilo.admin
+ */
+/**
+ * INIT SECTION
  */
-/* INIT SECTION */
 // name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
@@ -20,6 +23,10 @@ if (!isset($_GET['user_id'])) {
 }
 $user = api_get_user_info($_GET['user_id']);
 $tool_name = $user['complete_name'].(empty($user['official_code'])?'':' ('.$user['official_code'].')');
+
+/**
+ * Display
+ */
 Display::display_header($tool_name);
 
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
@@ -37,15 +44,25 @@ if (isset($_GET['action'])) {
     }
 }
 // only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
-$statusname = api_get_status_langvars();
 $login_as_icon = null;
 $editUser = null;
-if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
-    $login_as_icon = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user['user_id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>';
-    $editUser = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array()), api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user['user_id']);
+if (api_is_platform_admin()) {
+    $login_as_icon =
+        '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php'
+        .'?action=login_as&amp;user_id='.$user['user_id'].'&amp;'
+        .'sec_token='.$_SESSION['sec_token'].'">'
+        .Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>';
+    $editUser = Display::url(
+        Display::return_icon(
+            'edit.png',
+            get_lang('Edit'),
+            array()
+        ),
+        api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user['user_id']
+    );
 }
 echo '<div class="actions">
-        <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.intval($_GET['user_id']).'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.png',get_lang('Reporting'),'',  ICON_SIZE_MEDIUM).'
+        <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.intval($_GET['user_id']).'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.png', get_lang('Reporting'), '', ICON_SIZE_MEDIUM).'
         </a>
         '.$login_as_icon.'
         '.$editUser.'
@@ -54,9 +71,9 @@ echo '<div class="actions">
 echo Display::page_header($tool_name);
 
 // Getting the user image
-$sysdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'system',false,true);
+$sysdir_array = UserManager::get_user_picture_path_by_id($user['user_id'], 'system', false, true);
 $sysdir = $sysdir_array['dir'];
-$webdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'web',false,true);
+$webdir_array = UserManager::get_user_picture_path_by_id($user['user_id'], 'web', false, true);
 $webdir = $webdir_array['dir'];
 $fullurl = $webdir.$webdir_array['file'];
 $system_image_path = $sysdir.$webdir_array['file'];
@@ -65,10 +82,21 @@ $resizing = (($height > 200) ? 'height="200"' : '');
 $height += 30;
 $width += 30;
 $window_name = 'window'.uniqid('');
-$onclick = $window_name."=window.open('".$fullurl."','".$window_name."','alwaysRaised=yes, alwaysLowered=no,alwaysOnTop=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=".$width.",height=".$height.",left=200,top=20'); return false;";
-echo '<a href="javascript: void(0);" onclick="'.$onclick.'" ><img src="'.$fullurl.'" '.$resizing.' alt="'.$alt.'"/></a><br />';
-echo '<p>'. ($user['status'] == 1 ? get_lang('Teacher') : get_lang('Student')).'</p>';
+$onclick = $window_name."=window.open('".$fullurl."','".$window_name
+    ."','alwaysRaised=yes, alwaysLowered=no,alwaysOnTop=yes,toolbar=no,"
+    ."location=no,directories=no,status=no,menubar=no,scrollbars=no,"
+    ."resizable=no,width=".$width.",height=".$height.",left=200,top=20');"
+    ." return false;";
+echo '<a href="javascript: void(0);" onclick="'.$onclick.'" >'
+    .'<img src="'.$fullurl.'" '.$resizing.' alt="'.$alt.'"/></a><br />';
+echo '<p>'.($user['status'] == 1 ? get_lang('Teacher') : get_lang('Student'))
+    .'</p>';
 echo '<p>'.Display :: encrypted_mailto_link($user['mail'], $user['mail']).'</p>';
+// Show info about who created this user and when
+$creatorId = $user['creator_id'];
+$creatorInfo = api_get_user_info($creatorId);
+$registrationDate = $user['registration_date'];
+echo '<p>'.sprintf(get_lang('CreatedByXYOnZ'), 'user_information.php?user_id='.$creatorId, $creatorInfo['username'], api_get_utc_datetime($registrationDate)).'</p>';
 
 /**
  * Show the sessions and the courses in which this user is subscribed
@@ -139,10 +167,21 @@ if (count($sessions) > 0) {
             $session_item['date_end'] = null;
         }
 
-        $dates = array_filter(array($session_item['date_start'], $session_item['date_end']));
-        echo Display::page_subheader($session_item['session_name'], ' '.implode(' - ', $dates));
+        $dates = array_filter(
+            array($session_item['date_start'], $session_item['date_end'])
+        );
+        echo Display::page_subheader(
+            $session_item['session_name'],
+            ' '.implode(' - ', $dates)
+        );
 
-        Display :: display_sortable_table($header, $data, array (), array(), array ('user_id' => intval($_GET['user_id'])));
+        Display :: display_sortable_table(
+            $header,
+            $data,
+            array (),
+            array(),
+            array ('user_id' => intval($_GET['user_id']))
+        );
     }
 } else {
     echo '<p>'.get_lang('NoSessionsForThisUser').'</p>';
@@ -171,15 +210,20 @@ if (Database::num_rows($res) > 0) {
         $tools = '<a href="course_information.php?code='.$course->code.'">'.Display::return_icon('synthese_view.gif', get_lang('Overview')).'</a>'.
                 '<a href="'.api_get_path(WEB_COURSE_PATH).$course->directory.'">'.Display::return_icon('course_home.gif', get_lang('CourseHomepage')).'</a>' .
                 '<a href="course_edit.php?course_code='.$course->code.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-        if ( $course->status == STUDENT ) {
+        if ($course->status == STUDENT) {
             $tools .= '<a href="user_information.php?action=unsubscribe&course_code='.$course->code.'&user_id='.$user['user_id'].'">'.Display::return_icon('delete.png', get_lang('Delete')).'</a>';
-
         }
         $row[] = $tools;
         $data[] = $row;
     }
     echo Display::page_subheader(get_lang('Courses'));
-    Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
+    Display :: display_sortable_table(
+        $header,
+        $data,
+        array (),
+        array (),
+        array ('user_id' => intval($_GET['user_id']))
+    );
 } else {
     echo '<p>'.get_lang('NoCoursesForThisUser').'</p>';
 }
@@ -198,7 +242,13 @@ if (api_is_multiple_url_enabled()) {
             $data[] = $row;
         }
         echo '<p><b>'.get_lang('URLList').'</b></p>';
-        Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
+        Display :: display_sortable_table(
+            $header,
+            $data,
+            array (),
+            array (),
+            array ('user_id' => intval($_GET['user_id']))
+        );
     } else {
         echo '<p>'.get_lang('NoUrlForThisUser').'</p>';
     }

+ 16 - 16
main/document/document.inc.php

@@ -158,7 +158,7 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
             $url = $www . $path;
         }
         //$path = str_replace('%2F', '/',$url_path).'?'.api_get_cidreq();
-        $path = str_replace('%2F', '/', $url_path); //yox view hack otherwise the image can't be well read 
+        $path = str_replace('%2F', '/', $url_path); //yox view hack otherwise the image can't be well read
         $url = $www . $path;
 
         // Disabled fragment of code, there is a special icon for opening in a new window.
@@ -225,7 +225,7 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
             $force_download_html = ($size == 0) ? '' : '<a href="' . $forcedownload_link . '" style="float:right"' . $prevent_multiple_click . '>' . Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL) . '</a>';
         }
 
-        //Copy files to users myfiles        
+        //Copy files to users myfiles
         if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('users_copy_files') == 'true' && !api_is_anonymous()) {
             $copy_myfiles_link = ($filetype == 'file') ? api_get_self() . '?' . api_get_cidreq() . '&action=copytomyfiles&id=' . $document_data['id'] . $req_gid : api_get_self() . '?' . api_get_cidreq();
 
@@ -256,7 +256,7 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
                 return '<span style="float:left" ' . $visibility_class . '>' . $title . '</span>' . $force_download_html . $send_to . $copy_to_myfiles . $open_in_new_window_link . $pdf_icon;
             } elseif (
                     //Show preview
-                    //preg_match('/html$/i', urldecode($url))  || 
+                    //preg_match('/html$/i', urldecode($url))  ||
                     //preg_match('/htm$/i',  urldecode($url))  ||
                     preg_match('/swf$/i', urldecode($url)) ||
                     preg_match('/png$/i', urldecode($url)) ||
@@ -269,7 +269,7 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
             ) {
                 //yox view
                 //$url = 'showinframesmin.php?'.api_get_cidreq().'&id='.$document_data['id'].$req_gid;
-                //Simpler version of showinframesmin.php with no headers 
+                //Simpler version of showinframesmin.php with no headers
                 $url = 'show_content.php?' . api_get_cidreq() . '&id=' . $document_data['id'] . $req_gid . '&width=700&height=500';
                 $class = 'ajax';
                 if ($visibility == false) {
@@ -278,7 +278,7 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
                 return '<a href="' . $url . '" class="' . $class . '" title="' . $tooltip_title_alt . '" style="float:left">' . $title . '</a>' . $force_download_html . $send_to . $copy_to_myfiles . $open_in_new_window_link . $pdf_icon;
             } else {
                 $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'] . $req_gid;
-                //No plugin just the old and good showinframes.php page 			
+                //No plugin just the old and good showinframes.php page
                 return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" style="float:left" ' . $visibility_class . ' >' . $title . '</a>' . $force_download_html . $send_to . $copy_to_myfiles . $open_in_new_window_link . $pdf_icon;
             }
         } else {
@@ -297,7 +297,7 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
                     return $sound_preview;
                 } elseif (
                     //Show preview
-                    //preg_match('/html$/i', urldecode($url))  || 
+                    //preg_match('/html$/i', urldecode($url))  ||
                     //preg_match('/htm$/i',  urldecode($url))  ||
                     preg_match('/swf$/i', urldecode($url)) ||
                     preg_match('/png$/i', urldecode($url)) ||
@@ -556,10 +556,10 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
                 }
             }
         }
-        
-        //Move button        
+
+        //Move button
         if ($is_certificate_mode || in_array($path, DocumentManager::get_system_folders())) {
-            $modify_icons .= '&nbsp;' . Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';            
+            $modify_icons .= '&nbsp;' . Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
         } else {
             if (api_get_session_id()) {
                 if ($document_data['session_id'] == api_get_session_id()) {
@@ -571,7 +571,7 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
                 $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;move=' . $document_id . $req_gid . '">' . Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
             }
         }
-        
+
         //Visibility button
         if ($is_certificate_mode) {
             $modify_icons .= '&nbsp;' . Display::return_icon($visibility_icon . '.png', get_lang('VisibilityCannotBeChanged'), array(), ICON_SIZE_SMALL) . '</a>';
@@ -585,8 +585,8 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
                 $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;' . $visibility_command . '=' . $id . $req_gid . '&amp;' . $sort_params . '">' . Display::return_icon($visibility_icon . '.png', $tip_visibility, '', ICON_SIZE_SMALL) . '</a>';
             }
         }
-        
-        //Delete button    
+
+        //Delete button
         if (in_array($path, DocumentManager::get_system_folders())) {
             $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'), array(), ICON_SIZE_SMALL);
         } else {
@@ -683,7 +683,7 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
                 // 3. inside a subfolder of the folder you want to move
                 if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')) {
                     $path_displayed = $folder;
-                    // If document title is used, we have to display titles instead of real paths...                    
+                    // If document title is used, we have to display titles instead of real paths...
                     $path_displayed = get_titles_of_path($folder);
 
                     if (empty($path_displayed)) {
@@ -696,7 +696,7 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
         }
     } else {
         foreach ($folders as $folder) {
-            if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')) { // Cannot copy dir into his own subdir                
+            if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')) { // Cannot copy dir into his own subdir
                 $path_displayed = get_titles_of_path($folder);
                 $display_folder = substr($path_displayed, strlen($group_dir));
                 $display_folder = ($display_folder == '') ? get_lang('Documents') : $display_folder;
@@ -737,7 +737,7 @@ function get_titles_of_path($path) {
             // If this path has soon been stored here we don't need a new query
             $path_displayed .= $tmp_folders_titles[$tmp_path];
         } else {
-            $sql = 'SELECT title FROM ' . Database::get_course_table(TABLE_DOCUMENT) . ' 
+            $sql = 'SELECT title FROM ' . Database::get_course_table(TABLE_DOCUMENT) . '
                     WHERE c_id = ' . $course_id . ' AND path LIKE BINARY "' . $tmp_path . '"';
             $rs = Database::query($sql);
             $tmp_title = '/' . Database::result($rs, 0, 0);
@@ -772,7 +772,7 @@ function display_user_link_document($user_id, $name) {
 function create_dir_form($current_dir_id) {
     global $document_id;
 
-    $form = new FormValidator('create_dir_form', 'post', '', '', null, false);
+    $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq(), '', null, false);
     $form->addElement('hidden', 'create_dir', 1);
     $form->addElement('hidden', 'dir_id', intval($document_id));
     $form->addElement('hidden', 'id', intval($current_dir_id));

+ 38 - 41
main/document/document.php

@@ -72,7 +72,7 @@ function startApplet() {
     appletsource += "<param name=\"outputDir\" value=\"'.$base_work_dir.'\">";
     appletsource += "</applet>";
     document.getElementById("appletplace").innerHTML=appletsource;
-   // alert(appletsource);    
+   // alert(appletsource);
 }
 $(function() {
     $("#jcapture").click(function(){
@@ -84,8 +84,6 @@ $(function() {
 // Create directory certificates
 DocumentManager::create_directory_certificate_in_course(api_get_course_id());
 
-
-
 if (empty($course_info)) {
     api_not_allowed(true);
 }
@@ -169,7 +167,7 @@ switch ($action) {
         // Launch event
         event_download($document_data['url']);
         // Check visibility of document and paths
-        if (!($is_allowed_to_edit || $group_member_with_upload_rights) && !DocumentManager::is_visible_by_id($document_id, $course_info, api_get_session_id(), api_get_user_id())) {
+        if (!($is_allowed_to_edit || $group_member_with_upload_rights) && !DocumentManager::is_visible_by_id($document_id, $course_info, $session_id, api_get_user_id())) {
             api_not_allowed(true);
         }
         $full_file_name = $base_work_dir.$document_data['path'];
@@ -268,8 +266,8 @@ if (isset($document_id) && empty($action)) {
     if ($document_data) {
         $parent_id = $document_data['parent_id'];
 
-        //$visibility = DocumentManager::is_visible_by_id($document_id, $course_info, api_get_session_id(), api_get_user_id());
-        $visibility = DocumentManager::check_visibility_tree($document_id, api_get_course_id(), api_get_session_id(), api_get_user_id());
+        //$visibility = DocumentManager::is_visible_by_id($document_id, $course_info, $session_id, api_get_user_id());
+        $visibility = DocumentManager::check_visibility_tree($document_id, api_get_course_id(), $session_id, api_get_user_id());
 
         if (!empty($document_data['filetype']) && $document_data['filetype'] == 'file') {
             if ($visibility && api_is_allowed_to_session_edit()) {
@@ -307,7 +305,6 @@ if (isset($document_id) && empty($action)) {
         $curdirpath = '/';
     }
 
-
     $curdirpathurl = urlencode($curdirpath);
 
     // Check the path
@@ -409,7 +406,7 @@ if ($to_group_id != 0 && $curdirpath == '/') {
 //if (!$is_allowed_to_edit || api_is_coach()) { before
 
 if (!$is_allowed_to_edit && api_is_coach()) {
-    if ($curdirpath != '/' && !(DocumentManager::is_visible($curdirpath, $_course, api_get_session_id(), 'folder'))) {
+    if ($curdirpath != '/' && !(DocumentManager::is_visible($curdirpath, $_course, $session_id, 'folder'))) {
         api_not_allowed(true);
     }
 }
@@ -422,7 +419,7 @@ if ($session_id == 0) {
         $usf_dir_name = '/shared_folder';
         $to_group_id = 0;
         $visibility = 0;
-        create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        create_unexisting_directory($_course, api_get_user_id(), $session_id, $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
     }
     // Create dynamic user shared folder
     if (!file_exists($base_work_dir.'/shared_folder/sf_user_'.api_get_user_id())) {
@@ -430,7 +427,7 @@ if ($session_id == 0) {
         $usf_dir_name = '/shared_folder/sf_user_'.api_get_user_id();
         $to_group_id = 0;
         $visibility = 1;
-        create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        create_unexisting_directory($_course, api_get_user_id(), $session_id, $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
     }
 } else {
     //Create shared folder session
@@ -439,7 +436,7 @@ if ($session_id == 0) {
         $usf_dir_name = '/shared_folder_session_'.$session_id;
         $to_group_id = 0;
         $visibility = 0;
-        create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        create_unexisting_directory($_course, api_get_user_id(), $session_id, $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
     }
     //Create dynamic user shared folder into a shared folder session
     if (!file_exists($base_work_dir.'/shared_folder_session_'.$session_id.'/sf_user_'.api_get_user_id())) {
@@ -447,7 +444,7 @@ if ($session_id == 0) {
         $usf_dir_name = '/shared_folder_session_'.$session_id.'/sf_user_'.api_get_user_id();
         $to_group_id = 0;
         $visibility = 1;
-        create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        create_unexisting_directory($_course, api_get_user_id(), $session_id, $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
     }
 }
 
@@ -521,7 +518,7 @@ if (!empty($docs_and_folders)) {
                 if ($extension == 'ogg') {
                     $extension = 'oga';
                 }
-                //$("#jplayer_inspector_'.$count.'").jPlayerInspector({jPlayer:$("#jquery_jplayer_'.$count.'")});
+
                 $params = array('url' => $document_data['direct_url'],
                     'extension' => $extension,
                     'count' => $count
@@ -573,7 +570,7 @@ if (
         $my_get_move = intval($_REQUEST['move']);
 
         if (api_is_coach()) {
-            if (!DocumentManager::is_visible_by_id($my_get_move, $course_info, api_get_session_id(), api_get_user_id())) {
+            if (!DocumentManager::is_visible_by_id($my_get_move, $course_info, $session_id, api_get_user_id())) {
                 api_not_allowed();
             }
         }
@@ -618,7 +615,7 @@ if (
         }
 
         if (api_is_coach()) {
-            if (!DocumentManager::is_visible_by_id($_POST['move_file'], $_course, api_get_session_id(), api_get_user_id())) {
+            if (!DocumentManager::is_visible_by_id($_POST['move_file'], $_course, $session_id, api_get_user_id())) {
                 api_not_allowed();
             }
         }
@@ -672,7 +669,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
     if (isset($_GET['delete'])) {
         if (!$is_allowed_to_edit) {
             if (api_is_coach()) {
-                if (!DocumentManager::is_visible($_GET['delete'], $_course, api_get_session_id())) {
+                if (!DocumentManager::is_visible($_GET['delete'], $_course, $session_id)) {
                     api_not_allowed();
                 }
             }
@@ -685,10 +682,8 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         // Check whether the document is in the database
         if (!empty($document_data)) {
             if (DocumentManager::delete_document($_course, $_GET['delete'], $base_work_dir)) {
-                if (isset($_GET['delete_certificate_id']) && $_GET['delete_certificate_id'] == strval(intval($_GET['delete_certificate_id']))) {
-                    $default_certificate_id = $_GET['delete_certificate_id'];
-                    DocumentManager::remove_attach_certificate(api_get_course_id(), $default_certificate_id);
-                }
+                $certificateId = isset($_GET['delete_certificate_id']) ? $_GET['delete_certificate_id'] : null;
+                DocumentManager::remove_attach_certificate(api_get_course_id(), $certificateId);
                 Display::display_confirmation_message(get_lang('DocDeleted'));
             } else {
                 Display::display_error_message(get_lang('DocDeleteError'));
@@ -707,13 +702,12 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
                 continue;
             } else {
 
-                $documentId = DocumentManager::get_document_id($_course, $path);
-                $data = DocumentManager::get_document_data_by_id($documentId, $_course['code']);
+                $documentId = DocumentManager::get_document_id($_course, $path, $session_id);
+                $data = DocumentManager::get_document_data_by_id($documentId, $_course['code'], false, $session_id);
 
                 switch ($_POST['action']) {
                     case 'set_invisible':
                         $visibilityCommand = 'invisible';
-
                         if (api_item_property_update(
                             $_course,
                             TOOL_DOCUMENT,
@@ -751,18 +745,26 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
                         }
                         break;
                     case 'delete':
-
-                        foreach ($files as $path) {
+                        foreach ($files as $checkPath) {
                             if (!$is_allowed_to_edit) {
-                                if (DocumentManager::check_readonly($_course, api_get_user_id(), $path)) {
+                                if (DocumentManager::check_readonly(
+                                    $_course,
+                                    api_get_user_id(),
+                                    $checkPath,
+                                    null,
+                                    false,
+                                    $session_id
+                                )
+                                ) {
                                     Display::display_error_message(get_lang('CantDeleteReadonlyFiles'));
                                     break 2;
                                 }
                             }
                         }
 
-                        $delete_document = DocumentManager::delete_document($_course, $path, $base_work_dir);
-                        if (!empty($delete_document)) {
+                        $deleteDocument = DocumentManager::delete_document($_course, $path, $base_work_dir, $session_id);
+
+                        if (!empty($deleteDocument)) {
                             Display::display_confirmation_message(get_lang('DocDeleted').': '.$data['path']);
                         }
                         break;
@@ -795,7 +797,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
 
 
             if (!is_dir($dir_check)) {
-                $created_dir = create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $dir_name, $post_dir_name);
+                $created_dir = create_unexisting_directory($_course, api_get_user_id(), $session_id, $to_group_id, $to_user_id, $base_work_dir, $dir_name, $post_dir_name);
 
                 if ($created_dir) {
                     Display::display_confirmation_message('<span title="'.$created_dir.'">'.get_lang('DirCr').'</span>', false);
@@ -818,7 +820,6 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
 }
 
 /* 	VISIBILITY COMMANDS */
-//Only teacher
 if ($is_allowed_to_edit) {
     if ((isset($_GET['set_invisible']) && !empty($_GET['set_invisible'])) || (isset($_GET['set_visible']) && !empty($_GET['set_visible'])) && $_GET['set_visible'] != '*' && $_GET['set_invisible'] != '*') {
         // Make visible or invisible?
@@ -832,7 +833,7 @@ if ($is_allowed_to_edit) {
 
         if (!$is_allowed_to_edit) {
             if (api_is_coach()) {
-                if (!DocumentManager::is_visible_by_id($update_id, $_course, api_get_session_id(), api_get_user_id())) {
+                if (!DocumentManager::is_visible_by_id($update_id, $_course, $session_id, api_get_user_id())) {
                     api_not_allowed();
                 }
             }
@@ -953,7 +954,6 @@ if (api_get_group_id() != 0) {
     $folders = DocumentManager::get_all_document_folders($_course, api_get_group_id(), $is_allowed_to_edit || $group_member_with_upload_rights);
 }
 
-
 //$folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit || $group_member_with_upload_rights);
 if ($folders === false) {
     $folders = array();
@@ -994,7 +994,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
     /* CREATE NEW DOCUMENT OR NEW DIRECTORY / GO TO UPLOAD / DOWNLOAD ZIPPED FOLDER */
 
     // Create new document
-    
+
     if (!$is_certificate_mode) {
         ?>
         <a href="create_document.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
@@ -1020,7 +1020,6 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
             <?php
         }
 
-
         // Record an image clip from my webcam
         if (api_get_setting('enable_webcam_clip') == 'true') {
             ?>
@@ -1071,9 +1070,9 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         echo '<a href="upload.php?'.api_get_cidreq().'&id='.$current_folder_id.'">';
         echo Display::display_icon('upload_file.png', get_lang('UplUploadDocument'), '', ICON_SIZE_MEDIUM).'</a>';
     }
-    
-    echo '<a href="#" id="jcapture">';
-    echo Display::display_icon('capture.png', get_lang('CatchScreenCasts'), '', ICON_SIZE_MEDIUM).'</a>';
+
+    /*echo '<a href="#" id="jcapture">';
+    echo Display::display_icon('capture.png', get_lang('CatchScreenCasts'), '', ICON_SIZE_MEDIUM).'</a>';*/
 
     // Create directory
     if (!$is_certificate_mode) {
@@ -1082,7 +1081,6 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         <?php Display::display_icon('new_folder.png', get_lang('CreateDir'), '', ICON_SIZE_MEDIUM); ?></a>
         <?php
     }
-   
 }
 
 $table_footer = '';
@@ -1103,9 +1101,8 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
             $row['id'] = $document_data['id'];
             $row['type'] = $document_data['filetype'];
 
-            // If the item is invisible, wrap it in a span with class invisible
-
-            $is_visible = DocumentManager::is_visible_by_id($document_data['id'], $course_info, api_get_session_id(), api_get_user_id(), false);
+            // If the item is invisible, wrap it in a span with class invisible.
+            $is_visible = DocumentManager::is_visible_by_id($document_data['id'], $course_info, $session_id, api_get_user_id(), false);
 
             $invisibility_span_open = ($is_visible == 0) ? '<span class="muted">' : '';
             $invisibility_span_close = ($is_visible == 0) ? '</span>' : '';

+ 105 - 90
main/dropbox/dropbox_class.inc.php

@@ -56,62 +56,59 @@ class Dropbox_Work
     public $isOldWork;
     public $feedback_date, $feedback;
 
-	/**
-	 * Constructor calls private functions to create a new work or retreive an existing work from DB
-	 * depending on the number of parameters
-	 *
-	 * @param unknown_type $arg1
-	 * @param unknown_type $arg2
-	 * @param unknown_type $arg3
-	 * @param unknown_type $arg4
-	 * @param unknown_type $arg5
-	 * @param unknown_type $arg6
-	 * @return Dropbox_Work
-	 */
-	function Dropbox_Work($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null, $arg6 = null)
+    /**
+     * Constructor calls private functions to create a new work or retreive an existing work from DB
+     * depending on the number of parameters
+     *
+     * @param unknown_type $arg1
+     * @param unknown_type $arg2
+     * @param unknown_type $arg3
+     * @param unknown_type $arg4
+     * @param unknown_type $arg5
+     * @param unknown_type $arg6
+     * @return Dropbox_Work
+     */
+    public function Dropbox_Work($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null, $arg6 = null)
     {
-		if (func_num_args() > 1)  {
-		    $this->_createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
-		}  else  {
-			$this->_createExistingWork($arg1);
-		}
-	}
+        if (func_num_args() > 1) {
+            $this->_createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
+        } else {
+            $this->_createExistingWork($arg1);
+        }
+    }
 
 	/**
 	 * private function creating a new work object
 	 *
-	 * @param unknown_type $uploader_id
-	 * @param unknown_type $title
-	 * @param unknown_type $description
-	 * @param unknown_type $author
-	 * @param unknown_type $filename
-	 * @param unknown_type $filesize
+	 * @param int $uploader_id
+	 * @param string $title
+	 * @param string $description
+	 * @param string $author
+	 * @param string $filename
+	 * @param int $filesize
 	 *
 	 * @todo 	$author was originally a field but this has now been replaced by the first and lastname of the uploader (to prevent anonymous uploads)
 	 * 			As a consequence this parameter can be removed
 	 */
-	function _createNewWork($uploader_id, $title, $description, $author, $filename, $filesize) {
-		global $_user, $dropbox_cnf;
-		// Do some sanity checks
-		settype($uploader_id, 'integer') or die(get_lang('GeneralError').' (code 201)'); //set $uploader_id to correct type
-		//if (! isCourseMember($uploader_id)) die(); //uploader must be coursemember to be able to upload
-			//-->this check is done when submitting data so it isn't checked here
-
-		// Fill in the properties
-		$this->uploader_id = $uploader_id;
-		$this->uploaderName = getUserNameFromId($this->uploader_id);
-		$this->filename = $filename;
-		$this->filesize = $filesize;
-		$this->title = $title;
-		$this->description = $description;
-		$this->author = api_get_person_name($_user['firstName'], $_user['lastName']);
-		$this->last_upload_date = api_get_utc_datetime();
-
-		$course_id = api_get_course_int_id();
+	public function _createNewWork($uploader_id, $title, $description, $author, $filename, $filesize)
+    {
+        $_user = api_get_user_info();
+        $dropbox_cnf = getDropboxConf();
+
+        // Fill in the properties
+        $this->uploader_id = intval($uploader_id);
+        $this->uploaderName = getUserNameFromId($this->uploader_id);
+        $this->filename = $filename;
+        $this->filesize = $filesize;
+        $this->title = $title;
+        $this->description = $description;
+        $this->author = api_get_person_name($_user['firstName'], $_user['lastName']);
+        $this->last_upload_date = api_get_utc_datetime();
+        $course_id = api_get_course_int_id();
 
-		// Check if object exists already. If it does, the old object is used
-		// with updated information (authors, descriptio, upload_date)
-		$this->isOldWork = false;
+        // Check if object exists already. If it does, the old object is used
+        // with updated information (authors, description, upload_date)
+        $this->isOldWork = false;
 		$sql = "SELECT id, upload_date FROM ".$dropbox_cnf['tbl_file']."
 				WHERE c_id = $course_id AND filename = '".Database::escape_string($this->filename)."'";
         $result = Database::query($sql);
@@ -130,7 +127,7 @@ class Dropbox_Work
 					author 				= '".Database::escape_string($this->author)."',
 					last_upload_date 	= '".Database::escape_string($this->last_upload_date)."'
 					WHERE c_id = $course_id AND id='".Database::escape_string($this->id)."'";
-			$result = Database::query($sql);
+			Database::query($sql);
 		} else {
 			$this->upload_date = $this->last_upload_date;
 			$sql = "INSERT INTO ".$dropbox_cnf['tbl_file']." (c_id, uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, session_id)
@@ -143,34 +140,42 @@ class Dropbox_Work
 						, '".Database::escape_string($this->author)."'
 						, '".Database::escape_string($this->upload_date)."'
 						, '".Database::escape_string($this->last_upload_date)."'
-						, ".intval($_SESSION['id_session'])."
+						, ".api_get_session_id()."
 						)";
 
-        	$result = Database::query($sql);
+        	Database::query($sql);
 			$this->id = Database::insert_id(); // Get automatically inserted id
 		}
 
-		// Insert entries into person table
-		$sql = "INSERT INTO ".$dropbox_cnf['tbl_person']." (c_id, file_id, user_id)
-				VALUES ($course_id,
-						'".Database::escape_string($this->id)."'
-						, '".Database::escape_string($this->uploader_id)."'
-						)";
-        $result = Database::query($sql);	//if work already exists no error is generated
+        $sql = "SELECT count(file_id) as count FROM ".$dropbox_cnf['tbl_person']."
+				WHERE c_id = $course_id AND file_id = '".Database::escape_string($this->id)."' AND user_id = ".$this->uploader_id;
+        $result = Database::query($sql);
+        $row = Database::fetch_array($result);
+        if ($row['count'] == 0) {
+
+            // Insert entries into person table
+            $sql = "INSERT INTO ".$dropbox_cnf['tbl_person']." (c_id, file_id, user_id)
+                    VALUES ($course_id,
+                            '".Database::escape_string($this->id)."'
+                            , '".Database::escape_string($this->uploader_id)."'
+                            )";
+            Database::query($sql);
+        }
 	}
 
 	/**
 	 * private function creating existing object by retreiving info from db
 	 *
-	 * @param unknown_type $id
+	 * @param int $id
 	 */
-	function _createExistingWork($id) {
+	public function _createExistingWork($id)
+    {
 	    $course_id = api_get_course_int_id();
+        $dropbox_cnf = getDropboxConf();
 
-		global $_user, $dropbox_cnf;
+        $action = isset($_GET['action']) ? $_GET['action'] : null;
 
 		// Do some sanity checks
-		settype($id, 'integer') or die(get_lang('GeneralError').' (code 205)'); // Set $id to correct type
 		$id	= intval($id);
 
 		// Get the data from DB
@@ -204,7 +209,7 @@ class Dropbox_Work
 		$this->category = $res['cat_id'];
 
 		// Getting the feedback on the work.
-		if ($_GET['action'] == 'viewfeedback' AND $this->id == $_GET['id']) {
+		if ($action == 'viewfeedback' AND $this->id == $_GET['id']) {
 			$feedback2 = array();
 			$sql_feedback = "SELECT * FROM ".$dropbox_cnf['tbl_feedback']." WHERE c_id = $course_id AND file_id='".$id."' ORDER BY feedback_id ASC";
 			$result = Database::query($sql_feedback);
@@ -246,17 +251,19 @@ class Dropbox_SentWork extends Dropbox_Work
 	/**
 	 * private function creating a new SentWork object
 	 *
-	 * @param unknown_type $uploader_id
-	 * @param unknown_type $title
-	 * @param unknown_type $description
-	 * @param unknown_type $author
-	 * @param unknown_type $filename
-	 * @param unknown_type $filesize
-	 * @param unknown_type $recipient_ids
+	 * @param int $uploader_id
+	 * @param string $title
+	 * @param string $description
+	 * @param string $author
+	 * @param string $filename
+	 * @param int $filesize
+	 * @param array $recipient_ids
 	 */
-	function _createNewSentWork($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids)
+	public function _createNewSentWork($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids)
     {
-			global $dropbox_cnf;
+        $dropbox_cnf = getDropboxConf();
+        $_course = api_get_course_info();
+
 		// Call constructor of Dropbox_Work object
 		$this->Dropbox_Work($uploader_id, $title, $description, $author, $filename, $filesize);
 
@@ -274,9 +281,11 @@ class Dropbox_SentWork extends Dropbox_Work
 			$justSubmit = true;
 			$recipient_ids = array($uploader_id);
 		}
+
 		if (! is_array($recipient_ids) || count($recipient_ids) == 0) {
 			die(get_lang('GeneralError').' (code 209)');
 		}
+
 		foreach ($recipient_ids as $rec) {
 			if (empty($rec)) die(get_lang('GeneralError').' (code 210)');
 			//if (!isCourseMember($rec)) die(); //cannot sent document to someone outside of course
@@ -313,7 +322,6 @@ class Dropbox_SentWork extends Dropbox_Work
             }
 
 			// Update item_property table for each recipient
-			global $_course, $dropbox_cnf;
 			if (($ownerid = $this->uploader_id) > $dropbox_cnf['mailingIdBase']) {
 			    $ownerid = getUserOwningThisMailing($ownerid);
 			}
@@ -331,8 +339,7 @@ class Dropbox_SentWork extends Dropbox_Work
 	 */
 	function _createExistingSentWork ($id)
     {
-		global $dropbox_cnf;
-
+        $dropbox_cnf = getDropboxConf();
         $id = intval($id);
 
 		$course_id = api_get_course_int_id();
@@ -443,7 +450,8 @@ class Dropbox_Person
 	 * @param unknown_type $b
 	 * @return -1, 0 or 1 dependent of the result of the comparison.
 	 */
-	function _cmpWork($a, $b) {
+	function _cmpWork($a, $b)
+    {
 		$sort = $this->_orderBy;
 		$aval = $a->$sort;
 		$bval = $b->$sort;
@@ -466,7 +474,8 @@ class Dropbox_Person
 	 *
 	 * @param unknown_type $sort
 	 */
-	function orderSentWork($sort) {
+	function orderSentWork($sort)
+    {
 		switch($sort) {
 			case 'lastDate':
 				$this->_orderBy = 'last_upload_date';
@@ -530,7 +539,7 @@ class Dropbox_Person
 	 */
 	function deleteAllReceivedWork () {
 	    $course_id = api_get_course_int_id();
-		global $dropbox_cnf;
+        $dropbox_cnf = getDropboxConf();
 		// Delete entries in person table concerning received works
 		foreach ($this->receivedWork as $w) {
 			Database::query("DELETE FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND user_id='".$this->userId."' AND file_id='".$w->id."'");
@@ -543,7 +552,7 @@ class Dropbox_Person
 	 */
 	function deleteReceivedWorkFolder($id)
     {
-		global $dropbox_cnf;
+        $dropbox_cnf = getDropboxConf();
         $course_id = api_get_course_int_id();
 
 		$id = intval($id);
@@ -561,9 +570,10 @@ class Dropbox_Person
 	 *
 	 * @param integer $id
 	 */
-	function deleteReceivedWork($id) {
+	function deleteReceivedWork($id)
+    {
 	    $course_id = api_get_course_int_id();
-		global $dropbox_cnf;
+        $dropbox_cnf = getDropboxConf();
 		$id = intval($id);
 
 		// index check
@@ -574,8 +584,9 @@ class Dropbox_Person
 			   break;
 			}
 		}
+
 		if (!$found) {
-			if(!$this->deleteReceivedWorkFolder($id)) {
+			if (!$this->deleteReceivedWorkFolder($id)) {
 				die(get_lang('GeneralError').' (code 216)');
 			}
 		}
@@ -588,9 +599,10 @@ class Dropbox_Person
 	/**
 	 * Deletes all the sent dropbox files of this person
 	 */
-	function deleteAllSentWork() {
+	function deleteAllSentWork()
+    {
 	    $course_id = api_get_course_int_id();
-		global $dropbox_cnf;
+        $dropbox_cnf = getDropboxConf();
 		//delete entries in person table concerning sent works
 		foreach ($this->sentWork as $w) {
 			Database::query("DELETE FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND user_id='".$this->userId."' AND file_id='".$w->id."'");
@@ -604,10 +616,11 @@ class Dropbox_Person
 	 *
 	 * @param unknown_type $id
 	 */
-	function deleteSentWork($id) {
+	function deleteSentWork($id)
+    {
 	    $course_id = api_get_course_int_id();
+        $dropbox_cnf = getDropboxConf();
 
-		global $dropbox_cnf;
 		$id = intval($id);
 
 		// index check
@@ -636,10 +649,12 @@ class Dropbox_Person
 	 * @param unknown_type $id
 	 * @param unknown_type $text
 	 */
-	function updateFeedback($id, $text) {
+	function updateFeedback($id, $text)
+    {
 	    $course_id = api_get_course_int_id();
+        $_course = api_get_course_info();
+        $dropbox_cnf = getDropboxConf();
 
-		global $_course, $dropbox_cnf;
 		$id = intval($id);
 
 		// index check
@@ -678,11 +693,11 @@ class Dropbox_Person
 	 * @param string $type
 	 * @param string $value
 	 */
-	function filter_received_work($type, $value) {
-		global $dropbox_cnf;
-
+	function filter_received_work($type, $value)
+    {
+        $dropbox_cnf = getDropboxConf();
     	$new_received_work = array();
-		foreach ($this->receivedWork as $index => $work) {
+		foreach ($this->receivedWork as $work) {
 			switch ($type) {
 				case 'uploader_id':
 					if ($work->uploader_id == $value ||

+ 14 - 15
main/dropbox/dropbox_config.inc.php

@@ -1,17 +1,11 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-/**
- *  DEBUGGING VARS
- */
-$DEBUG = false; // TODO: Is this needed?
-
 /**
  *  DATABASE TABLE VARIABLES
  */
 $dropbox_cnf['tbl_user']        = Database::get_main_table(TABLE_MAIN_USER);
 $dropbox_cnf['tbl_course_user'] = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-
 $dropbox_cnf['tbl_post'] 		= Database::get_course_table(TABLE_DROPBOX_POST);
 $dropbox_cnf['tbl_file'] 		= Database::get_course_table(TABLE_DROPBOX_FILE);
 $dropbox_cnf['tbl_person'] 		= Database::get_course_table(TABLE_DROPBOX_PERSON);
@@ -23,19 +17,22 @@ $dropbox_cnf['tbl_feedback'] 	= Database::get_course_table(TABLE_DROPBOX_FEEDBAC
  *  INITIALISE OTHER VARIABLES & CONSTANTS
  */
 $dropbox_cnf['courseId'] 				= $_cid;
-$dropbox_cnf['sysPath'] 				= api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/dropbox'; //path to dropbox subdir in course containing the uploaded files
+//path to dropbox subdir in course containing the uploaded files
+$dropbox_cnf['sysPath'] 				= api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/dropbox';
 $dropbox_cnf['webPath'] 				= api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/dropbox';
-$dropbox_cnf['maxFilesize'] 			= api_get_setting('dropbox_max_filesize'); //file size limit as imposed by the platform admin (see Chamilo Config Settings on the platform administration section)
-//$dropbox_cnf['version'] 				= '1.4';
-$dropbox_cnf['allowOverwrite'] 			= string_2_boolean(api_get_setting('dropbox_allow_overwrite'));
-$dropbox_cnf['allowJustUpload'] 		= string_2_boolean(api_get_setting('dropbox_allow_just_upload'));
-$dropbox_cnf['allowStudentToStudent'] 	= string_2_boolean(api_get_setting('dropbox_allow_student_to_student'));
-$dropbox_cnf['allowGroup'] 				= string_2_boolean(api_get_setting('dropbox_allow_group'));
+
+//file size limit as imposed by the platform admin (see Chamilo Config Settings on the platform administration section)
+$dropbox_cnf['maxFilesize'] 			= api_get_setting('dropbox_max_filesize');
+$dropbox_cnf['allowOverwrite'] 			= api_string_2_boolean(api_get_setting('dropbox_allow_overwrite'));
+$dropbox_cnf['allowJustUpload'] 		= api_string_2_boolean(api_get_setting('dropbox_allow_just_upload'));
+$dropbox_cnf['allowStudentToStudent'] 	= api_string_2_boolean(api_get_setting('dropbox_allow_student_to_student'));
+$dropbox_cnf['allowGroup'] 				= api_string_2_boolean(api_get_setting('dropbox_allow_group'));
 
 /**
- * INITIALISE MAILING VARIABLES
+ * MAILING VARIABLES
  */
-$dropbox_cnf['allowMailing'] = string_2_boolean(api_get_setting('dropbox_allow_mailing'));  // false = no mailing functionality
+// false = no mailing functionality
+$dropbox_cnf['allowMailing'] = api_string_2_boolean(api_get_setting('dropbox_allow_mailing'));
 $dropbox_cnf['mailingIdBase'] = 10000000;  // bigger than any user_id,
 // allowing enough space for pseudo_ids as uploader_id, dest_user_id, user_id:
 // mailing pseudo_id = dropbox_cnf('mailingIdBase') + mailing id
@@ -45,3 +42,5 @@ $dropbox_cnf['mailingWhereUSERID'] = 'username';
 $dropbox_cnf['mailingWhereLOGINNAME'] = 'username';
 $dropbox_cnf['mailingFileRegexp'] = '/^(.+)\.\w{1,4}$/';
 $dropbox_cnf['sent_received_tabs'] = true;
+
+return $dropbox_cnf;

+ 93 - 106
main/dropbox/dropbox_download.php

@@ -6,10 +6,8 @@
 /**
  * Code
  */
-/*	INIT SECTION */
 
 // We cannot use dropbox_init.inc.php because this one already outputs data.
-
 $language_file = 'dropbox';
 
 // including the basic Chamilo initialisation file
@@ -32,137 +30,126 @@ $course_id = api_get_course_int_id();
 $user_id = api_get_user_id();
 
 if (isset($_GET['cat_id']) AND is_numeric($_GET['cat_id']) AND $_GET['action'] == 'downloadcategory' AND isset($_GET['sent_received'])) {
-	// step 1: constructingd' the sql statement. Due to the nature off the classes of the dropbox the categories for sent files are stored in the table
-	// dropbox_file while the categories for the received files are stored in dropbox_post. It would have been more elegant if these could be stored
-	// in dropbox_person (which stores the link file-person)
-	// Therefore we have to create to separate sql statements to find which files are in the categorie (depending if we zip-download a sent category or a
-	// received category)
-    
-	if ($_GET['sent_received'] == 'sent') {
-		// here we also incorporate the person table to make sure that deleted sent documents are not included.
-		$sql = "SELECT DISTINCT file.id, file.filename, file.title 
-                FROM ".$dropbox_cnf['tbl_file']." file INNER JOIN ".$dropbox_cnf['tbl_person']." person 
+    /** step 1: constructing the sql statement.
+    Due to the nature off the classes of the dropbox the categories for sent files are stored in the table
+    dropbox_file while the categories for the received files are stored in dropbox_post.
+    It would have been more elegant if these could be stored in dropbox_person (which stores the link file-person)
+    Therefore we have to create to separate sql statements to find which files are in the category
+    (depending if we zip-download a sent category or a received category)*/
+
+    if ($_GET['sent_received'] == 'sent') {
+        // here we also incorporate the person table to make sure that deleted sent documents are not included.
+        $sql = "SELECT DISTINCT file.id, file.filename, file.title
+                FROM ".$dropbox_cnf['tbl_file']." file INNER JOIN ".$dropbox_cnf['tbl_person']." person
                 ON (person.file_id=file.id AND file.c_id = $course_id AND person.c_id = $course_id)
-				WHERE 
-                    file.uploader_id = $user_id AND 
-                    file.cat_id='".intval($_GET['cat_id'])."'  AND 
+                WHERE
+                    file.uploader_id = $user_id AND
+                    file.cat_id='".intval($_GET['cat_id'])."'  AND
                     person.user_id = $user_id";
-	}
-    
-	if ($_GET['sent_received'] == 'received') {
-		$sql = "SELECT DISTINCT file.id, file.filename, file.title 
+    }
+
+    if ($_GET['sent_received'] == 'received') {
+        $sql = "SELECT DISTINCT file.id, file.filename, file.title
                 FROM ".$dropbox_cnf['tbl_file']." file INNER JOIN ".$dropbox_cnf['tbl_person']." person
                 ON (person.file_id=file.id AND file.c_id = $course_id AND person.c_id = $course_id)
                 INNER JOIN ".$dropbox_cnf['tbl_post']." post
                 ON (post.file_id = file.id AND post.c_id = $course_id AND file.c_id = $course_id)
-				WHERE 
-                    post.cat_id = ".intval($_GET['cat_id'])." AND 
+                WHERE
+                    post.cat_id = ".intval($_GET['cat_id'])." AND
                     post.dest_user_id = $user_id" ;
-	}    
-    
-	$result = Database::query($sql);
-	while ($row = Database::fetch_array($result)) {
-		$files_to_download[] = $row['id'];
-	}    
-	if (!is_array($files_to_download) OR empty($files_to_download)) {
-		header('location: index.php?view='.Security::remove_XSS($_GET['sent_received']).'&error=ErrorNoFilesInFolder');
-		exit;
-	}    
-	zip_download($files_to_download);
-	exit;
-}
-
+    }
 
+    $result = Database::query($sql);
+    while ($row = Database::fetch_array($result)) {
+        $files_to_download[] = $row['id'];
+    }
+    if (!is_array($files_to_download) OR empty($files_to_download)) {
+        header('location: index.php?view='.Security::remove_XSS($_GET['sent_received']).'&error=ErrorNoFilesInFolder');
+        exit;
+    }
+    zip_download($files_to_download);
+    exit;
+}
 /*	DOWNLOAD A FILE */
-
-/*		AUTHORIZATION */
+/* AUTHORIZATION */
 
 // Check if the id makes sense
 if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
-	Display::display_header($nameTools, 'Dropbox');
-	Display :: display_error_message(get_lang('Error'));
-	Display::display_footer();
-	exit;
+    Display::display_header($nameTools, 'Dropbox');
+    Display :: display_error_message(get_lang('Error'));
+    Display::display_footer();
+    exit;
 }
 
 // Check if the user is allowed to download the file
 $allowed_to_download = false;
 if (user_can_download_file($_GET['id'], api_get_user_id())) {
-	$allowed_to_download = true;
+    $allowed_to_download = true;
 }
 
 /*		ERROR IF NOT ALLOWED TO DOWNLOAD */
 
-
 if (!$allowed_to_download) {
-	Display::display_header($nameTools, 'Dropbox');
-	Display::display_error_message(get_lang('YouAreNotAllowedToDownloadThisFile'));
-	Display::display_footer();
+    Display::display_header($nameTools, 'Dropbox');
+    Display::display_error_message(get_lang('YouAreNotAllowedToDownloadThisFile'));
+    Display::display_footer();
 	exit;
-} else {    
-    /*      DOWNLOAD THE FILE */    
+} else {
+    /*      DOWNLOAD THE FILE */
     // the user is allowed to download the file
-	$_SESSION['_seen'][$_course['id']][TOOL_DROPBOX][] = intval($_GET['id']);
+    $_SESSION['_seen'][$_course['id']][TOOL_DROPBOX][] = intval($_GET['id']);
+
+    $work = new Dropbox_work($_GET['id']);
+    $path = dropbox_cnf('sysPath') . '/' . $work -> filename; //path to file as stored on server
 
-	$work = new Dropbox_work($_GET['id']);
-	$path = dropbox_cnf('sysPath') . '/' . $work -> filename; //path to file as stored on server
-	
     if (!Security::check_abs_path($path, dropbox_cnf('sysPath').'/')) {
-    	exit;
+        exit;
     }
-	$file = $work->title;	
-	$mimetype = DocumentManager::file_get_mime_type(true);
-	$fileinfo = pathinfo($file);
-	$extension = $fileinfo['extension'];
-	
-	if (!empty($extension) && isset($mimetype[$extension]) && $_GET['action'] != 'download') {		
-	    // give hint to browser about filetype
-    	header( 'Content-type: ' . $mimetype[$extension] . "\n");
-	} else {
-		//no information about filetype: force a download dialog window in browser
-		header( "Content-type: application/octet-stream\n");
-	}
-	
-	/*if (!in_array(strtolower($extension), array('doc', 'xls', 'ppt', 'pps', 'sxw', 'sxc', 'sxi'))) {
-		header('Content-Disposition: inline; filename='.$file); // bugs with open office
-	} else {
-		header('Content-Disposition: attachment; filename='.$file);
-	}*/
-	
-	header('Content-Disposition: attachment; filename='.$file);
-
-	/**
-	 * Note that if you use these two headers from a previous example:
-	 * header('Cache-Control: no-cache, must-revalidate');
-	 * header('Pragma: no-cache');
-	 * before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.
-	 * Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
-	 */
-	header("Pragma: \n");
-	header("Cache-Control: \n");
-	header("Cache-Control: public\n"); // IE cannot download from sessions without a cache
-
-	/*if (isset($_SERVER['HTTPS'])) {
-	    /**
-	     * We need to set the following headers to make downloads work using IE in HTTPS mode.
-	     *
-	    //header('Pragma: ');
-	    //header('Cache-Control: ');
-	    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
-	    header("Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT\n");
-	    header("Cache-Control: no-store, no-cache, must-revalidate\n"); // HTTP/1.1
-	    header("Cache-Control: post-check=0, pre-check=0\n", false);
-	}*/
-	
-	header('Content-Description: '.trim(htmlentities($file)));
-	header('Content-transfer-encoding: binary');
-	
-	header("Content-Length: " . filesize($path)."\n" );
-
-	$fp = fopen( $path, 'rb');
-	fpassthru($fp);
-	exit();
+    $file = $work->title;
+    $mimetype = DocumentManager::file_get_mime_type(true);
+    $fileinfo = pathinfo($file);
+    $extension = $fileinfo['extension'];
+
+    if (!empty($extension) && isset($mimetype[$extension]) && $_GET['action'] != 'download') {
+        // give hint to browser about filetype
+        header( 'Content-type: ' . $mimetype[$extension] . "\n");
+    } else {
+        //no information about filetype: force a download dialog window in browser
+        header( "Content-type: application/octet-stream\n");
+    }
+    header('Content-Disposition: attachment; filename='.$file);
+
+    /**
+     * Note that if you use these two headers from a previous example:
+     * header('Cache-Control: no-cache, must-revalidate');
+     * header('Pragma: no-cache');
+     * before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.
+     * Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
+     */
+    header("Pragma: \n");
+    header("Cache-Control: \n");
+    header("Cache-Control: public\n"); // IE cannot download from sessions without a cache
+
+    /*if (isset($_SERVER['HTTPS'])) {
+        /**
+         * We need to set the following headers to make downloads work using IE in HTTPS mode.
+         *
+        //header('Pragma: ');
+        //header('Cache-Control: ');
+        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
+        header("Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT\n");
+        header("Cache-Control: no-store, no-cache, must-revalidate\n"); // HTTP/1.1
+        header("Cache-Control: post-check=0, pre-check=0\n", false);
+    }*/
+
+    header('Content-Description: '.trim(htmlentities($file)));
+    header('Content-transfer-encoding: binary');
+
+    header("Content-Length: " . filesize($path)."\n" );
+
+    $fp = fopen( $path, 'rb');
+    fpassthru($fp);
+    exit();
 }
-
 //@todo clean this file the code below is useless there are 2 exits in previous conditions ... maybe a bad copy/paste/merge?
 exit;

+ 226 - 224
main/dropbox/dropbox_functions.inc.php

@@ -7,6 +7,7 @@
 * to one file 		-- Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @author Julio Montoya adding c_id support
 */
+use \ChamiloSession as Session;
 
 $this_section = SECTION_COURSES;
 
@@ -25,22 +26,24 @@ $(document).ready(function () {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function handle_multiple_actions() {
-	global $_user, $is_courseAdmin, $is_courseTutor;
-
-	// STEP 1: are we performing the actions on the received or on the sent files?
-	if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'download_received') {
-		$part = 'received';
-	} elseif ($_POST['action'] == 'delete_sent' || $_POST['action'] == 'download_sent') {
-		$part = 'sent';
-	}
+function handle_multiple_actions()
+{
+    $_user = api_get_user_info();
+    $is_courseAdmin = api_is_course_admin();
+    $is_courseTutor = api_is_course_tutor();
+
+    // STEP 1: are we performing the actions on the received or on the sent files?
+    if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'download_received') {
+        $part = 'received';
+    } elseif ($_POST['action'] == 'delete_sent' || $_POST['action'] == 'download_sent') {
+        $part = 'sent';
+    }
 
-	// STEP 2: at least one file has to be selected. If not we return an error message
-    $ids = Request::get('id', array());
-    if(count($ids)>0){        
+    // STEP 2: at least one file has to be selected. If not we return an error message
+    $ids = isset($_GET['id']) ? $_GET['id'] : array();
+    if (count($ids)>0) {
         $checked_file_ids = $_POST['id'];
-    }
-    else{      
+    } else {
         foreach ($_POST as $key => $value) {
             if (strstr($value, $part.'_') AND $key != 'view_received_category' AND $key != 'view_sent_category') {
                 $checked_files = true;
@@ -48,38 +51,38 @@ function handle_multiple_actions() {
             }
         }
     }
-	$checked_file_ids = $_POST['id'];
+    $checked_file_ids = $_POST['id'];
 
-	if (!is_array($checked_file_ids) || count($checked_file_ids) == 0) {
-		return get_lang('CheckAtLeastOneFile');
-	}
+    if (!is_array($checked_file_ids) || count($checked_file_ids) == 0) {
+        return get_lang('CheckAtLeastOneFile');
+    }
 
-	// STEP 3A: deleting
-	if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'delete_sent') {
-		$dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
-		foreach ($checked_file_ids as $key => $value) {
-			if ($_GET['view'] == 'received') {
-				$dropboxfile->deleteReceivedWork($value);
-				$message = get_lang('ReceivedFileDeleted');
-			}
-			if ($_GET['view'] == 'sent' OR empty($_GET['view'])) {
-				$dropboxfile->deleteSentWork($value);
-				$message = get_lang('SentFileDeleted');
-			}
-		}
-		return $message;
-	}
+    // STEP 3A: deleting
+    if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'delete_sent') {
+        $dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
+        foreach ($checked_file_ids as $key => $value) {
+            if ($_GET['view'] == 'received') {
+                $dropboxfile->deleteReceivedWork($value);
+                $message = get_lang('ReceivedFileDeleted');
+            }
+            if ($_GET['view'] == 'sent' OR empty($_GET['view'])) {
+                $dropboxfile->deleteSentWork($value);
+                $message = get_lang('SentFileDeleted');
+            }
+        }
+        return $message;
+    }
 
-	// STEP 3B: giving comment
-	if ($_POST['actions'] == 'comment') {
-		// This has not been implemented.
-		// The idea was that it would be possible to write the same feedback for the selected documents.
-	}
+    // STEP 3B: giving comment
+    if ($_POST['actions'] == 'comment') {
+        // This has not been implemented.
+        // The idea was that it would be possible to write the same feedback for the selected documents.
+    }
 
-	// STEP 3C: moving
-	if (strstr($_POST['action'], 'move_')) {
-        	// check move_received_n or move_sent_n command
-		if (strstr($_POST['action'], 'received')) {
+    // STEP 3C: moving
+    if (strstr($_POST['action'], 'move_')) {
+            // check move_received_n or move_sent_n command
+        if (strstr($_POST['action'], 'received')) {
               $part = 'received';
               $to_cat_id = str_replace('move_received_', '', $_POST['action']);
         } else {
@@ -87,16 +90,25 @@ function handle_multiple_actions() {
               $to_cat_id = str_replace('move_sent_', '', $_POST['action']);
         }
 
-		foreach ($checked_file_ids as $key => $value) {
-			store_move($value, $to_cat_id, $part);
-		}
-		return get_lang('FilesMoved');
+        foreach ($checked_file_ids as $key => $value) {
+            store_move($value, $to_cat_id, $part);
+        }
+        return get_lang('FilesMoved');
     }
 
-	// STEP 3D: downloading
-	if ($_POST['action'] == 'download_sent' || $_POST['action'] == 'download_received') {
-		zip_download($checked_file_ids);
-	}
+    // STEP 3D: downloading
+    if ($_POST['action'] == 'download_sent' || $_POST['action'] == 'download_received') {
+        zip_download($checked_file_ids);
+    }
+}
+
+/**
+ * Get conf settings
+ * @return array
+ */
+function getDropboxConf()
+{
+    return Session::read('dropbox_conf');
 }
 
 /**
@@ -107,18 +119,22 @@ function handle_multiple_actions() {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function delete_category($action, $id, $user_id = null) {
+function delete_category($action, $id, $user_id = null)
+{
     $course_id = api_get_course_int_id();
+    $is_courseAdmin = api_is_course_admin();
+    $is_courseTutor = api_is_course_tutor();
+    $dropbox_cnf = getDropboxConf();
 
-	global $dropbox_cnf;
-	global $is_courseAdmin, $is_courseTutor;
-    
     if (empty($user_id)) {
         $user_id = api_get_user_id();
     }
-    
+
     $cat = get_dropbox_category($id);
-    if (count($cat)==0) { return false; }
+    if (count($cat)==0) {
+        return false;
+    }
+
     if ($cat['user_id'] != $user_id && !api_is_platform_admin($user_id)) {
         return false;
     }
@@ -140,14 +156,14 @@ function delete_category($action, $id, $user_id = null) {
 
 	// step 1: delete the category
 	$sql = "DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE c_id = $course_id AND cat_id='".intval($id)."' AND $sentreceived='1'";
-	$result = Database::query($sql);
+	Database::query($sql);
 
 	// step 2: delete all the documents in this category
 	$sql = "SELECT * FROM ".$entries_table." WHERE c_id = $course_id AND cat_id='".intval($id)."'";
 	$result = Database::query($sql);
 
 	while($row = Database::fetch_array($result)) {
-		$dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
+		$dropboxfile = new Dropbox_Person($user_id, $is_courseAdmin, $is_courseTutor);
 		if ($action == 'deletereceivedcategory') {
 			$dropboxfile->deleteReceivedWork($row[$id_field]);
 		}
@@ -160,14 +176,16 @@ function delete_category($action, $id, $user_id = null) {
 
 /**
 * Displays the form to move one individual file to a category
-*
-* @return html code of the form that appears in a message box.
-*
+*@ return html code of the form that appears in a message box.
 * @author Julio Montoya - function rewritten
-
 */
-function display_move_form($part, $id, $target = array(), $extra_params = array()) {
-    $form = new FormValidator('form1', 'post', api_get_self().'?view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&view='.Security::remove_XSS($_GET['view']).'&'.$extra_params);
+function display_move_form($part, $id, $target = array(), $extra_params = array(), $viewReceivedCategory, $viewSentCategory, $view)
+{
+    $form = new FormValidator(
+        'form1',
+        'post',
+        api_get_self().'?view_received_category='.$viewReceivedCategory.'&view_sent_category='.$viewSentCategory.'&view='.$view.'&'.$extra_params
+    );
 	$form->addElement('header', get_lang('MoveFileTo'));
     $form->addElement('hidden', 'id', intval($id));
     $form->addElement('hidden', 'part', Security::remove_XSS($part));
@@ -179,7 +197,6 @@ function display_move_form($part, $id, $target = array(), $extra_params = array(
     $form->addElement('select', 'move_target', get_lang('MoveFileTo'), $options);
     $form->addElement('button', 'do_move', get_lang('MoveFile'));
     $form->display();
-
 }
 
 /**
@@ -194,12 +211,14 @@ function display_move_form($part, $id, $target = array(), $extra_params = array(
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function store_move($id, $target, $part) {
-	global $_user, $dropbox_cnf;
+function store_move($id, $target, $part)
+{
+    $_user = api_get_user_info();
+    $dropbox_cnf = getDropboxConf();
     $course_id = api_get_course_int_id();
 
 	if ((isset($id) AND $id != '') AND (isset($target) AND $target != '') AND (isset($part) AND $part != '')) {
-        
+
 		if ($part == 'received') {
 			$sql = "UPDATE ".$dropbox_cnf["tbl_post"]." SET cat_id='".Database::escape_string($target)."'
 						WHERE c_id = $course_id AND dest_user_id='".Database::escape_string($_user['user_id'])."'
@@ -229,7 +248,8 @@ function store_move($id, $target, $part) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function display_action_options($part, $categories, $current_category = 0) {
+function display_action_options($part, $categories, $current_category = 0)
+{
 	echo '<select name="actions">';
 	echo '<option value="download">'.get_lang('Download').'</option>';
 	echo '<option value="delete">'.get_lang('Delete').'</option>';
@@ -238,7 +258,7 @@ function display_action_options($part, $categories, $current_category = 0) {
 		if ($current_category != 0) {
 			echo '<option value="move_0">'.get_lang('Root').'</a>';
 		}
-		foreach ($categories as $key => $value) {
+		foreach ($categories as $value) {
 			if ($current_category != $value['cat_id']) {
 				echo '<option value="move_'.$value['cat_id'].'">'.$value['cat_name'].'</option>';
 			}
@@ -279,11 +299,11 @@ function display_file_checkbox($id, $part) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function get_dropbox_categories($filter = '') {
+function get_dropbox_categories($filter = '')
+{
     $course_id = api_get_course_int_id();
-	global $_user;
-	global $dropbox_cnf;
-
+    $_user = api_get_user_info();
+    $dropbox_cnf = getDropboxConf();
 	$return_array = array();
 
 	$session_id = api_get_session_id();
@@ -306,10 +326,11 @@ function get_dropbox_categories($filter = '') {
  * @param int The category ID
  * @return array The details of this category
  */
-function get_dropbox_category($id) {
-    global $dropbox_cnf;
+function get_dropbox_category($id)
+{
+    $dropbox_cnf = getDropboxConf();
     $course_id = api_get_course_int_id();
-    if (empty($id) or $id != intval($id)) { return array(); }    
+    if (empty($id) or $id != intval($id)) { return array(); }
     $sql = "SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE c_id = $course_id AND cat_id='".$id."'";
     $res = Database::query($sql);
     if ($res === false) {
@@ -333,10 +354,11 @@ function get_dropbox_category($id) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function store_addcategory() {
+function store_addcategory()
+{
     $course_id = api_get_course_int_id();
-	global $_user;
-	global $dropbox_cnf;
+    $_user = api_get_user_info();
+    $dropbox_cnf = getDropboxConf();
 
 	// check if the target is valid
 	if ($_POST['target'] == 'sent') {
@@ -389,8 +411,9 @@ function store_addcategory() {
  *
 * @version march 2006
 */
-function display_addcategory_form($category_name = '', $id = '', $action) {
-	global $dropbox_cnf;
+function display_addcategory_form($category_name = '', $id = '', $action)
+{
+    $dropbox_cnf = getDropboxConf();
     $course_id = api_get_course_int_id();
 	$title = get_lang('AddNewCategory');
 
@@ -427,7 +450,7 @@ function display_addcategory_form($category_name = '', $id = '', $action) {
 		$class = 'add';
 	}
 
-    $form = new FormValidator('add_new_category', 'post', api_get_self().'?view="'.Security::remove_XSS($_GET['view']));
+    $form = new FormValidator('add_new_category', 'post', api_get_self().'?view='.Security::remove_XSS($_GET['view']));
     $form->addElement('header', $title);
 
 	if (isset($id) AND $id != '') {
@@ -452,55 +475,37 @@ function display_addcategory_form($category_name = '', $id = '', $action) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function display_add_form() {
-	global $_user, $is_courseAdmin, $is_courseTutor, $course_info, $origin, $dropbox_unid;
-
-	$token = Security::get_token();
+function display_add_form($dropbox_unid, $viewReceivedCategory, $viewSentCategory, $view)
+{
+    $course_info = api_get_course_info();
+    $_user = api_get_user_info();
+    $is_courseAdmin = api_is_course_admin();
+    $is_courseTutor = api_is_course_tutor();
+    $origin = isset($_GET['origin']) ? $_GET['origin'] : null;
+
+    $token = Security::get_token();
 	$dropbox_person = new Dropbox_Person(api_get_user_id(), $is_courseAdmin, $is_courseTutor);
-	?>
-	<form method="post" action="index.php?view_received_category=<?php echo Security::remove_XSS($_GET['view_received_category']); ?>&view_sent_category=<?php echo Security::remove_XSS($_GET['view_sent_category']); ?>&view=<?php echo Security::remove_XSS($_GET['view']); ?>&<?php echo "origin=$origin"."&".api_get_cidreq(); ?>" enctype="multipart/form-data" onsubmit="javascript: return checkForm(this);">
-	<legend><?php echo get_lang('UploadNewFile'); ?></legend>
-
-	<div class="control-group">
-		<label>
-			<span class="form_required">*</span><?php echo get_lang('UploadFile'); ?>:
-		</label>
-		<div class="controls">
-				<input type="hidden" name="MAX_FILE_SIZE" value='<?php echo dropbox_cnf('maxFilesize'); ?>' />
-				<input type="file" name="file" size="20" <?php if (dropbox_cnf('allowOverwrite')) echo 'onChange="javascript: checkfile(this.value);"'; ?> />
-				<input type="hidden" name="dropbox_unid" value="<?php echo $dropbox_unid; ?>" />
-				<input type="hidden" name="sec_token" value="<?php echo $token; ?>" />
-				<?php
-				if ($origin == 'learnpath') {
-					echo '<input type="hidden" name="origin" value="learnpath" />';
-				}
-				?>
-		</div>
-	</div>
 
-	<?php
+    $form = new FormValidator(
+        'sent_form',
+        'post',
+        api_get_self().'?view_received_category='.$viewReceivedCategory.'&view_sent_category='.$viewSentCategory.'&view='.$view.'&'.api_get_cidreq(),
+        null,
+        array('enctype' => 'multipart/form-data', 'onsubmit' => 'javascript: return checkForm(this);')
+    );
+
+    $form->addElement('header', get_lang('UploadNewFile'));
+    $form->addElement('hidden', 'MAX_FILE_SIZE', dropbox_cnf('maxFilesize'));
+    $form->addElement('hidden', 'dropbox_unid', $dropbox_unid);
+    $form->addElement('hidden', 'sec_token', $token);
+    $form->addElement('hidden', 'origin', $origin);
+    $form->addElement('file', 'file', get_lang('UploadFile'), array('onChange' => 'javascript: checkfile(this.value);'));
+
 	if (dropbox_cnf('allowOverwrite')) {
-		?>
-		<div class="control-group">
-			<div class="controls">
-				<label class="checkbox">
-                    <input type="checkbox" name="cb_overwrite" id="cb_overwrite" value="true" />
-				<?php echo get_lang('OverwriteFile'); ?>
-				</label>
-			</div>
-		</div>
-		<?php
+        $form->addElement('checkbox', 'cb_overwrite',  null, get_lang('OverwriteFile'), array('id' => 'cb_overwrite'));
 	}
-	?>
 
-	<div class="control-group">
-		<label class="control-label">
-			<?php echo get_lang('SendTo'); ?>
-		</label>
-		<div class="controls">
-	<?php
-
-	//list of all users in this course and all virtual courses combined with it
+	// List of all users in this course and all virtual courses combined with it
 	if (api_get_session_id()) {
 		$complete_user_list_for_dropbox = array();
 		if (api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT) {
@@ -522,14 +527,14 @@ function display_add_form() {
     	}
     	$complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
     }
-    
-    echo '<select name="recipients[]" size="10" multiple class="span4">';	
+
 	/*
 		Create the options inside the select box:
 		List all selected users their user id as value and a name string as display
 	*/
 
 	$current_user_id = '';
+    $options = array();
 	foreach ($complete_user_list_for_dropbox as $current_user) {
 		if (($dropbox_person -> isCourseTutor
 				|| $dropbox_person -> isCourseAdmin
@@ -542,10 +547,12 @@ function display_add_form() {
 			}
 			$full_name = $current_user['lastcommafirst'];
 			$current_user_id = $current_user['user_id'];
-			echo '<option value="user_' . $current_user_id . '">' . $full_name . '</option>';
+            $options['user_' . $current_user_id] = $full_name;
+			//echo '<option value="user_' . $current_user_id . '">' . $full_name . '</option>';
 		}
 	}
 
+
 	/*
 	* Show groups
 	*/
@@ -556,42 +563,31 @@ function display_add_form() {
 		if (count($complete_group_list_for_dropbox) > 0) {
 			foreach ($complete_group_list_for_dropbox as $current_group) {
 				if ($current_group['number_of_members'] > 0) {
-					echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
+					//echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
+                    $options['group_'.$current_group['id']] = 'G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users');
 				}
 			}
 		}
     }
 
-    if (($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) && dropbox_cnf('allowMailing')) {
-		// echo '<option value="mailing">'.get_lang('MailingInSelect').'</option>';
-	}
-
     if (dropbox_cnf('allowJustUpload')) {
     	//echo '<option value="upload">'.get_lang('JustUploadInSelect').'</option>';
-    	echo '<option value="user_'.$_user['user_id'].'">'.get_lang('JustUploadInSelect').'</option>';
+    	//echo '<option value="user_'.$_user['user_id'].'">'.get_lang('JustUploadInSelect').'</option>';
+        $options['user_'.$_user['user_id']] = get_lang('JustUploadInSelect');
     }
 
-	echo '</select>
-		</div>
-	</div>';
-
-	echo '
-		<div class="control-group">
-			<div class="controls">
-				<button type="Submit" class="upload" name="submitWork">'.get_lang('Upload', '').'</button>
-			</div>
-		</div>
-	';
-
-	echo '</form>';
+    $form->addElement('select', 'recipients', get_lang('SendTo'), $options, array('multiple' => 'multiple', 'size' => '10', 'class' => 'span4'));
+    $form->addElement('button', 'submitWork', get_lang('Upload'));
+    $form->display();
 }
 
 /**
 * returns username or false if user isn't registered anymore
 * @todo check if this function is still necessary. There might be a library function for this.
 */
-function getUserNameFromId($id) {
-	global $dropbox_cnf;
+function getUserNameFromId($id)
+{
+    $dropbox_cnf = getDropboxConf();
 
     $mailingId = $id - dropbox_cnf('mailingIdBase');
     if ($mailingId > 0) {
@@ -612,7 +608,8 @@ function getUserNameFromId($id) {
 * returns loginname or false if user isn't registered anymore
 * @todo check if this function is still necessary. There might be a library function for this.
 */
-function getLoginFromId($id) {
+function getLoginFromId($id)
+{
     $id = intval($id);
     $sql = "SELECT username
 			FROM " . dropbox_cnf('tbl_user') . "
@@ -625,12 +622,12 @@ function getLoginFromId($id) {
 
 /**
 * @return boolean indicating if user with user_id=$user_id is a course member
-* @todo eliminate global
 * @todo check if this function is still necessary. There might be a library function for this.
 */
-function isCourseMember($user_id) {
-    global $_course;
-	$course_code = $_course['sysCode'];
+function isCourseMember($user_id)
+{
+    $_course = api_get_course_info();
+	$course_code = $_course['code'];
 	$is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code, true);
 	return $is_course_member;
 }
@@ -639,26 +636,25 @@ function isCourseMember($user_id) {
 * Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
 * If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
 */
-function removeUnusedFiles() {
+function removeUnusedFiles()
+{
     $course_id = api_get_course_int_id();
 
     // select all files that aren't referenced anymore
     $sql = "SELECT DISTINCT f.id, f.filename
 			FROM " . dropbox_cnf('tbl_file') . " f
-			LEFT JOIN " . dropbox_cnf('tbl_person') . " p 
+			LEFT JOIN " . dropbox_cnf('tbl_person') . " p
             ON (f.id = p.file_id)
 			WHERE p.user_id IS NULL AND
-                  f.c_id = $course_id 
+                  f.c_id = $course_id
             ";
     $result = Database::query($sql);
     while ($res = Database::fetch_array($result)) {
-        
 		//delete the selected files from the post and file tables
         $sql = "DELETE FROM " . dropbox_cnf('tbl_post') . " WHERE c_id = $course_id AND file_id = '" . $res['id'] . "'";
         Database::query($sql);
         $sql = "DELETE FROM " . dropbox_cnf('tbl_file') . " WHERE c_id = $course_id AND id ='" . $res['id'] . "'";
         Database::query($sql);
-
 		//delete file from server
         @unlink( dropbox_cnf('sysPath') . '/' . $res['filename']);
     }
@@ -676,17 +672,18 @@ function removeUnusedFiles() {
 *
 * @todo check if this function is still necessary.
 */
-function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '') {
+function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
+{
     $course_id = api_get_course_int_id();
+    $dropbox_cnf = getDropboxConf();
 
-	global $dropbox_cnf;
     $mailingPseudoId = intval($mailingPseudoId);
     $sql = "SELECT f.uploader_id
 			FROM " . $dropbox_cnf['tbl_file'] . " f
 			LEFT JOIN " . $dropbox_cnf['tbl_post'] . " p ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
-			WHERE 
-                p.dest_user_id = '" . $mailingPseudoId . "' AND 
-                p.c_id = $course_id 
+			WHERE
+                p.dest_user_id = '" . $mailingPseudoId . "' AND
+                p.c_id = $course_id
             ";
     $result = Database::query($sql);
 
@@ -701,9 +698,10 @@ function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '') {
 * @author René Haentjens, Ghent University
 * @todo check if this function is still necessary.
 */
-function removeMoreIfMailing($file_id) {
+function removeMoreIfMailing($file_id)
+{
     $course_id = api_get_course_int_id();
-	global $dropbox_cnf;
+    $dropbox_cnf = getDropboxConf();
     // when deleting a mailing zip-file (posted to mailingPseudoId):
     // 1. the detail window is no longer reachable, so
     //    for all content files, delete mailingPseudoId from person-table
@@ -734,23 +732,28 @@ function removeMoreIfMailing($file_id) {
 *
 * @author René Haentjens, Ghent University
 */
-function dropbox_cnf($variable) {
-    return $GLOBALS['dropbox_cnf'][$variable];
+function dropbox_cnf($variable)
+{
+    $dropbox_cnf = getDropboxConf();
+    return $dropbox_cnf[$variable];
 }
 
-function store_add_dropbox() {
-	global $dropbox_cnf;
-	global $_user;
-	global $_course;
+/**
+ * @return array|null|string
+ */
+function store_add_dropbox()
+{
+    $_course = api_get_course_info();
+    $_user = api_get_user_info();
+    $dropbox_cnf = getDropboxConf();
 
 	// Validating the form data
 
     // there are no recipients selected
 	if (!isset($_POST['recipients']) || count( $_POST['recipients']) <= 0) {
         return get_lang('YouMustSelectAtLeastOneDestinee');
-    }
-    // Check if all the recipients are valid
-    else {
+    } else {
+        // Check if all the recipients are valid
         $thisIsAMailing = false;
         $thisIsJustUpload = false;
 	    foreach ($_POST['recipients'] as $rec) {
@@ -782,7 +785,6 @@ function store_add_dropbox() {
 		return get_lang('NoFileSpecified');
 	}
 
-
 	// are we overwriting a previous file or sending a new one
 
 	$dropbox_overwrite = false;
@@ -806,9 +808,9 @@ function store_add_dropbox() {
 	if (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
 		return get_lang('TheFileIsNotUploaded');
 	}
-    
+
     $upload_ok = process_uploaded_file($_FILES['file'], true);
-        
+
     if (!$upload_ok) {
         return null;
     }
@@ -819,7 +821,7 @@ function store_add_dropbox() {
 	$dropbox_filename = replace_dangerous_char($dropbox_filename);
 	// Transform any .php file in .phps fo security
 	$dropbox_filename = php2phps($dropbox_filename);
-    
+
 	//filter extension
     if (!filter_extension($dropbox_filename)) {
     	return get_lang('UplUnableToSaveFileFilteredExtension');
@@ -828,7 +830,7 @@ function store_add_dropbox() {
 	// set title
 	$dropbox_title = $dropbox_filename;
 	// set author
-	if ($_POST['authors'] == '') {
+	if (!isset($_POST['authors'])) {
 		$_POST['authors'] = getUserNameFromId($_user['user_id']);
 	}
 
@@ -882,7 +884,7 @@ function store_add_dropbox() {
 		}
 	}
 
-	new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
+	new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
 
 	Security::clear_token();
     return get_lang('FileUploadSucces');
@@ -926,7 +928,8 @@ function display_user_link_work($user_id, $name = '') {
 * @version march 2006
 */
 function feedback($array) {
-	foreach ($array as $key => $value) {
+    $output = null;
+	foreach ($array as $value) {
 		$output .= format_feedback($value);
 	}
 	$output .= feedback_form();
@@ -942,8 +945,9 @@ function feedback($array) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function format_feedback($feedback) {
-	$output .= display_user_link_work($feedback['author_user_id']);
+function format_feedback($feedback)
+{
+	$output = display_user_link_work($feedback['author_user_id']);
 	$output .= '&nbsp;&nbsp;'.api_convert_and_format_date($feedback['feedback_date'], DATE_TIME_FORMAT_LONG).'<br />';
 	$output .= '<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
 	return $output;
@@ -956,8 +960,9 @@ function format_feedback($feedback) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function feedback_form() {
-	$return = get_lang('AddNewFeedback').'<br />';	
+function feedback_form()
+{
+	$return = get_lang('AddNewFeedback').'<br />';
 	$number_users_who_see_file = check_if_file_exist($_GET['id']);
 	if ($number_users_who_see_file) {
 		$token = Security::get_token();
@@ -972,34 +977,34 @@ function feedback_form() {
 }
 
 function user_can_download_file($id, $user_id) {
-    global $dropbox_cnf;
+    $dropbox_cnf = getDropboxConf();
     $course_id = api_get_course_int_id();
     $id = intval($id);
     $user_id = intval($user_id);
-    
-    $sql = "SELECT file_id FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND user_id = $user_id AND file_id = ".$id;    
+
+    $sql = "SELECT file_id FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND user_id = $user_id AND file_id = ".$id;
 	$result = Database::query($sql);
 	$number_users_who_see_file = Database::num_rows($result);
-    
+
     $sql = "SELECT file_id FROM ".$dropbox_cnf["tbl_post"]."  WHERE c_id = $course_id AND dest_user_id = $user_id AND file_id = ".$id;
     $result = Database::query($sql);
-	$count = Database::num_rows($result);    
+	$count = Database::num_rows($result);
     return $number_users_who_see_file > 0 || $count > 0;
 }
 
 // we now check if the other users have not delete this document yet. If this is the case then it is useless to see the
 	// add feedback since the other users will never get to see the feedback.
 function check_if_file_exist($id) {
-    global $dropbox_cnf;
+    $dropbox_cnf = getDropboxConf();
     $id = intval($id);
     $course_id = api_get_course_int_id();
-    $sql = "SELECT file_id FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND file_id = ".$id;    
+    $sql = "SELECT file_id FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND file_id = ".$id;
 	$result = Database::query($sql);
 	$number_users_who_see_file = Database::num_rows($result);
-    
+
     $sql = "SELECT file_id FROM ".$dropbox_cnf["tbl_post"]."  WHERE c_id = $course_id AND file_id = ".$id;
     $result = Database::query($sql);
-	$count = Database::num_rows($result);    
+	$count = Database::num_rows($result);
     return $number_users_who_see_file > 0 || $count > 0;
 }
 
@@ -1011,8 +1016,9 @@ function check_if_file_exist($id) {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @version march 2006
 */
-function store_feedback() {
-	global $dropbox_cnf;
+function store_feedback()
+{
+    $dropbox_cnf = getDropboxConf();
 	if (!is_numeric($_GET['id'])) {
 		return get_lang('FeedbackError');
 	}
@@ -1039,17 +1045,10 @@ function store_feedback() {
 * @version march 2006
 */
 function zip_download($array) {
-	global $_course;
-	global $dropbox_cnf;
-	global $files;
+	$_course = api_get_course_info();
+    $dropbox_cnf = getDropboxConf();
 
     $course_id = api_get_course_int_id();
-
-	$sys_course_path = api_get_path(SYS_COURSE_PATH);
-
-	// place to temporarily stash the zipfiles
-	$temp_zip_dir = api_get_path(SYS_COURSE_PATH);
-
 	$array = array_map('intval', $array);
 
 	// note: we also have to add the check if the user has received or sent this file.
@@ -1058,7 +1057,7 @@ function zip_download($array) {
             ON (person.file_id=file.id AND file.c_id = $course_id AND person.c_id = $course_id)
             INNER JOIN ".$dropbox_cnf['tbl_post']." post
             ON (post.file_id = file.id AND post.c_id = $course_id AND file.c_id = $course_id)
-			WHERE   file.id IN (".implode(', ',$array).") AND 
+			WHERE   file.id IN (".implode(', ',$array).") AND
                     file.id = person.file_id AND
                     (person.user_id = '".api_get_user_id()."' OR post.dest_user_id = '".api_get_user_id()."' ) ";
 	$result = Database::query($sql);
@@ -1070,7 +1069,7 @@ function zip_download($array) {
 	// Step 3: create the zip file and add all the files to it
 	$temp_zip_file = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
 	$zip_folder = new PclZip($temp_zip_file);
-	foreach ($files as $key => $value) {
+	foreach ($files as $value) {
 		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'], PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
 	}
 	$name = 'dropbox-'.api_get_utc_datetime().'.zip';
@@ -1100,7 +1099,8 @@ function my_pre_add_callback($p_event, &$p_header) {
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, March 2006
  * @author Ivan Tcholakov, 2010, code for html metadata has been added.
  */
-function generate_html_overview($files, $dont_show_columns = array(), $make_link = array()) {
+function generate_html_overview($files, $dont_show_columns = array(), $make_link = array())
+{
 	$return = '<!DOCTYPE html'."\n";
 	$return .= "\t".'PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'."\n";
 	$return .= "\t".'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
@@ -1113,7 +1113,7 @@ function generate_html_overview($files, $dont_show_columns = array(), $make_link
 	$return .= "<table border=\"1px\">\n";
 
 	$counter = 0;
-	foreach ($files as $key => $value) {
+	foreach ($files as $value) {
 
 		// Adding the header.
 		if ($counter == 0) {
@@ -1157,11 +1157,12 @@ function generate_html_overview($files, $dont_show_columns = array(), $make_link
 * @version march 2006
 */
 function get_total_number_feedback($file_id = '') {
-	global $dropbox_cnf;
+    $dropbox_cnf = getDropboxConf();
 	$course_id = api_get_course_int_id();
 	$sql = "SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']."
 			WHERE c_id = $course_id GROUP BY file_id";
 	$result = Database::query($sql);
+    $return = array();
 	while ($row=Database::fetch_array($result)) {
 		$return[$row['file_id']] = $row['total'];
 	}
@@ -1198,23 +1199,24 @@ function check_number_feedback($key, $array) {
  *
  * @todo consider moving this function to a more appropriate place.
  */
-function get_last_tool_access($tool, $course_code='', $user_id='') {
-	global $_course, $_user;
-
+function get_last_tool_access($tool, $course_code = '', $user_id='')
+{
 	// The default values of the parameters
-	if ($course_code == '') {
-		$course_code = $_course['id'];
+	if (empty($course_code)) {
+        $course_code = api_get_course_id();
 	}
-	if ($user_id == '') {
-		$user_id = $_user['user_id'];
+	if (empty($user_id)) {
+		$user_id = api_get_user_id();
 	}
 
 	// the table where the last tool access is stored (=track_e_lastaccess)
-	$table_last_access = Database::get_statistic_table('track_e_lastaccess');
+	$table_last_access = Database::get_main_table('track_e_lastaccess');
 
-	$sql = "SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
-				AND access_cours_code='".Database::escape_string($course_code)."'
-				AND access_tool='".Database::escape_string($tool)."'
+	$sql = "SELECT access_date FROM $table_last_access
+	        WHERE
+	            access_user_id='".Database::escape_string($user_id)."' AND
+	            access_cours_code='".Database::escape_string($course_code)."' AND
+	            access_tool='".Database::escape_string($tool)."'
 				ORDER BY access_date DESC
 				LIMIT 1";
 	$result = Database::query($sql);

+ 139 - 51
main/dropbox/dropbox_init.inc.php

@@ -1,6 +1,96 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+
+/**
+ * @desc The dropbox is a personal (peer to peer) file exchange module that allows
+ * you to send documents to a certain (group of) users.
+ *
+ * @version 1.3
+ *
+ * @author Jan Bols <jan@ivpv.UGent.be>, main programmer, initial version
+ * @author René Haentjens <rene.haentjens@UGent.be>, several contributions
+ * @author Roan Embrechts, virtual course support
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University (see history version 1.3)
+ *
+ * @package chamilo.dropbox
+ *
+ * @todo complete refactoring. Currently there are about at least 3 sql queries needed for every individual dropbox document.
+ *			first we find all the documents that were sent (resp. received) by the user
+ *			then for every individual document the user(s)information who received (resp. sent) the document is searched
+ *			then for every individual document the feedback is retrieved
+ * @todo 	the implementation of the dropbox categories could (on the database level) have been done more elegantly by storing the category
+ *			in the dropbox_person table because this table stores the relationship between the files (sent OR received) and the users
+ */
+
+/**
+HISTORY
+Version 1.1
+------------
+- dropbox_init1.inc.php: changed include statements to require statements. This way if a file is not found, it stops the execution of a script instead of continuing with warnings.
+- dropbox_init1.inc.php: the include files "claro_init_global.inc.php" & "debug.lib.inc.php" are first checked for their existence before including them. If they don't exist, in the .../include dir, they get loaded from the .../inc dir. This change is necessary because the UCL changed the include dir to inc.
+- dropbox_init1.inc.php: the databasetable name in the variable $dropbox_cnf["introTbl"] is chnged from "introduction" to "tool_intro"
+- install.php: after submit, checks if the database uses accueil or tool_list as a tablename
+- index.php: removed the behaviour of only the teachers that are allowed to delete entries
+- index.php: added field "lastUploadDate" in table dropbox_file to store information about last update when resubmiting a file
+- dropbox.inc.php: added $lang["lastUpdated"]
+- index.php: entries in received list show when file was last updated if it is updated
+- index.php: entries in sent list show when file was last resent if it was resent
+- dropbox_submit.php: add a unique id to every uploaded file
+- index.php: add POST-variable to the upload form with overwrite data when user decides to overwrite the previous sent file with new file
+- dropbox_submit.php: add sanity checks on POST['overwrite'] data
+- index.php: remove title field in upload form
+- dropbox_submit.php: remove use of POST['title'] variable
+- dropbox_init1.inc.php: added $dropbox_cnf["version"] variable
+- dropbox_class.inc.php: add $this->lastUploadDate to Dropbox_work class
+- dropbox.inc.php: added $lang['emptyTable']
+- index.php: if the received or sent list is empty, a message is displayed
+- dropbox_download.php: the $file var is set equal to the title-field of the filetable. So not constructed anymore by substracting the username from the filename
+- index.php: add check to see if column lastUploadDate exists in filetable
+- index.php: moved javascripts from dropbox_init2.inc.php to index.php
+- index.php: when specifying an uploadfile in the form, a checkbox allowing the user to overwrite a previously sent file is shown when the specified file has the same name as a previously uploaded file of that user.
+- index.php: assign all the metadata (author, description, date, recipient, sender) of an entry in a list to the class="dropbox_detail" and add css to html-header
+- index.php: assign all dates of entries in list to the class="dropbox_date" and add CSS
+- index.php: assign all persons in entries of list to the class="dropbox_person" and add CSS
+- dropbox.inc.php: added $lang['dropbox_version'] to indicate the lates version. This must be equal to the $dropbox_cnf['version'] variable.
+- dropbox_init1.inc.php: if the newest lang file isn't loaded by claro_init_global.inc.php from the .../lang dir it will be loaded locally from the .../plugin/dropbox/ dir. This way an administrator must not install the dropbox.inc.php in the .../lang/english dir, but he can leave it in the local .../plugin/dropbox/ dir. However if you want to present multiple language translations of the file you must still put the file in the /lang/ dir, because there is no language management system inside the .../plugin/dropbox dir.
+- mime.inc.php: created this file. It contains an array $mimetype with all the mimetypes that are used by dropbox_download.php to give hinst to the browser during download about content
+- dropbox_download.php: remove https specific headers because they're not necessary
+- dropbox_download.php: use application/octet-stream as the default mime and inline as the default Content-Disposition
+- dropbox.inc.php: add lang vars for "order by" action
+- dropbox_class.inc.php: add methods orderSentWork, orderReceivedWork en _cmpWork and propery _orderBy to class Dropbox_person to take care of sorting
+- index.php: add selectionlist to headers of sent/received lists to select "order by" and add code to keep selected value in sessionvar.
+- index.php: moved part of a <a> hyperlink to previous line to remove the underlined space between symbol and title of a work entry in the sent/received list
+- index.php: add filesize info in sent/received lists
+- dropbox_submit.php: resubmit prevention only for GET action, because it gives some annoying behaviour in POST situation: white screen in IE6
+
+Version 1.2
+-----------
+- adapted entire dropbox tool so it can be used as a default tool in Dokeos 1.5
+- index.php: add event registration to log use of tool in stats tables
+- index.php: upload form checks for correct user selection and file specification before uploading the script
+- dropbox_init1.inc.php: added dropbox_cnf["allowOverwrite"] to allow or disallow overwriting of files
+- index.php: author name textbox is automatically filled in
+- mailing functionality (René Haentjens)
+- allowStudentToStudent and allowJustUpload options (id.)
+- help in separate window (id.)
+
+Version 1.3 (Patrick Cool)
+--------------------------
+- sortable table
+- categories
+- fixing a security hole
+- tabs (which can be disabled: see $dropbox_cnf['sent_received_tabs'])
+- same action on multiple documents ([zip]download, move, delete)
+- consistency with the docuements tool (open/download file, icons of documents, ...)
+- zip download of complete folder
+
+Version 1.4 (Yannick Warnier)
+-----------------------------
+- removed all self-built database tables names
+ */
+
+
 /**
  * First initialisation file with initialisation of variables and
  * without outputting anything to browser.
@@ -23,6 +113,7 @@
  				extended feedback
  * @package chamilo.dropbox
  */
+
 /**
  * Code
  */
@@ -32,18 +123,16 @@ use \ChamiloSession as Session;
 
 $language_file = array('dropbox', 'document');
 
-// This var disables the link in the breadcrumbs on top of the page
-//$noPHP_SELF = true;
-
 // including the basic Chamilo initialisation file
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
+$is_allowed_in_course = api_is_allowed_in_course();
+$is_courseTutor = api_is_course_tutor();
+$is_courseAdmin = api_is_course_admin();
 $current_course_tool  = TOOL_DROPBOX;
 
 // the dropbox configuration parameters
-require_once 'dropbox_config.inc.php';
-
-// the dropbox sanity files (adds a new table and some new fields)
-//require_once 'dropbox_sanity.inc.php';
+$dropbox_cnf = require_once 'dropbox_config.inc.php';
+Session::write('dropbox_conf', $dropbox_cnf);
 
 // the dropbox file that contains additional functions
 require_once 'dropbox_functions.inc.php';
@@ -54,12 +143,8 @@ require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 // protecting the script
 api_protect_course_script();
 
-
 /*	Libraries */
 
-// including the library for the sortable table
-//require_once api_get_path(LIBRARY_PATH).'tablesort.lib.php';moved to autoload
-
 // including the library for the dropbox
 require_once 'dropbox_class.inc.php';
 
@@ -68,14 +153,17 @@ require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';  // we use
 require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php'; // the function choose_image is used
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
-
 /*	Virtual course support */
 
 $user_id = api_get_user_id();
 $course_code = api_get_course_id();
-$course_info = Database::get_course_info($course_code);
-
+$course_info = api_get_course_info($course_code);
 $session_id = api_get_session_id();
+
+$action = isset($_GET['action']) ? $_GET['action'] : null;
+$view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : null;
+$postAction = isset($_POST['action']) ? $_POST['action'] : null;
+
 if (empty($session_id)) {
     $is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code, false);
 } else {
@@ -88,7 +176,7 @@ if (empty($session_id)) {
 // off all the documents that have already been sent.
 // @todo consider moving the javascripts in a function that displays the javascripts
 // only when it is needed.
-if ($_GET['action'] == 'add') {
+if ($action == 'add') {
 	$dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
 }
 
@@ -130,17 +218,20 @@ $javascript = "<script type=\"text/javascript\">
 	";
 
 if (dropbox_cnf('allowOverwrite')) {
+    //sentArray keeps list of all files still available in the sent files list
+    //of the user.
+    //This is used to show or hide the overwrite file-radio button of the upload form
+
 	$javascript .= "
-		var sentArray = new Array(";	//sentArray keeps list of all files still available in the sent files list
-										//of the user.
-										//This is used to show or hide the overwrite file-radio button of the upload form
-	for ($i = 0; $i < count($dropbox_person->sentWork); $i++) {
-		if ($i > 0) {
-		    $javascript .= ", ";
-		}
-		$javascript .= "'".$dropbox_person->sentWork[$i]->title."'";
-		//echo '***'.$dropbox_person->sentWork[$i]->title;
-	}
+		var sentArray = new Array(";
+    if (isset($dropbox_person)) {
+        for ($i = 0; $i < count($dropbox_person->sentWork); $i++) {
+            if ($i > 0) {
+                $javascript .= ", ";
+            }
+            $javascript .= "'".$dropbox_person->sentWork[$i]->title."'";
+        }
+    }
 	$javascript .= ");
 
 		function checkfile(str)
@@ -188,9 +279,7 @@ if (dropbox_cnf('allowOverwrite')) {
 
 $javascript .= "
 	</script>";
-
 $htmlHeadXtra[] = $javascript;
-
 $htmlHeadXtra[] =
 "<script type=\"text/javascript\">
 function confirmation (name)
@@ -209,26 +298,26 @@ $htmlHeadXtra[] = '<meta http-equiv="cache-control" content="no-cache">
 	<meta http-equiv="expires" content="-1">';
 
 $checked_files = false;
-if (!$_GET['view'] OR $_GET['view'] == 'received') {
+if (!$view OR $view == 'received') {
 	$part = 'received';
-} elseif ($_GET['view'] = 'sent') {
+} elseif ($view = 'sent') {
 	$part = 'sent';
 } else {
-	header ('location: index.php?view='.$_GET['view'].'&error=Error');
+	header ('location: index.php?view='.$view.'&error=Error');
 }
 
-if (($_POST['action'] == 'download_received' || $_POST['action'] == 'download_sent') and !$_POST['store_feedback']) {
-	$checked_file_ids = $_POST['id'];
-	if (!is_array($checked_file_ids) || count($checked_file_ids) == 0) {
-		header ('location: index.php?view='.$_GET['view'].'&error=CheckAtLeastOneFile');
-	} else {
-		handle_multiple_actions();
-	}
-	exit;
+if (($postAction == 'download_received' || $postAction == 'download_sent') and !$_POST['store_feedback']) {
+    $checked_file_ids = $_POST['id'];
+    if (!is_array($checked_file_ids) || count($checked_file_ids) == 0) {
+        header ('location: index.php?view='.$view.'&error=CheckAtLeastOneFile');
+    } else {
+        handle_multiple_actions();
+    }
+    exit;
 }
 
 /*
- *         AUTHORISATION SECTION
+ * AUTHORISATION SECTION
  * Prevents access of all users that are not course members
  */
 
@@ -243,25 +332,25 @@ if ((!$is_allowed_in_course || !$is_course_member) && !api_is_allowed_to_edit(nu
 
 /*	BREADCRUMBS */
 
-if ($_GET['view'] == 'received') {
+if ($view == 'received') {
 	$interbreadcrumb[] = array('url' => '../dropbox/index.php', 'name' => get_lang('Dropbox', ''));
 	$nameTools = get_lang('ReceivedFiles');
 
-	if ($_GET['action'] == 'addreceivedcategory') {
+	if ($action == 'addreceivedcategory') {
 		$interbreadcrumb[] = array('url' => '../dropbox/index.php?view=received', 'name' => get_lang('ReceivedFiles'));
 		$nameTools = get_lang('AddNewCategory');
 	}
 }
 
-if ($_GET['view'] == 'sent' OR empty($_GET['view'])) {
+if ($view == 'sent' OR empty($view)) {
 	$interbreadcrumb[] = array('url' => '../dropbox/index.php', 'name' => get_lang('Dropbox', ''));
 	$nameTools = get_lang('SentFiles');
 
-	if ($_GET['action'] == 'addsentcategory') {
+	if ($action == 'addsentcategory') {
 		$interbreadcrumb[] = array('url' => '../dropbox/index.php?view=sent', 'name' => get_lang('SentFiles'));
 		$nameTools = get_lang('AddNewCategory');
 	}
-	if ($_GET['action'] == 'add') {
+	if ($action == 'add') {
 		$interbreadcrumb[] = array ('url' => '../dropbox/index.php?view=sent', 'name' => get_lang('SentFiles'));
 		$nameTools = get_lang('UploadNewFile');
 	}
@@ -269,11 +358,10 @@ if ($_GET['view'] == 'sent' OR empty($_GET['view'])) {
 
 /*	HEADER & TITLE */
 
-if ($origin != 'learnpath') {
+if (isset($origin) && $origin == 'learnpath') {
+    // if we come from the learning path we have to include the stylesheet and the required javascripts manually.
+    echo '<link rel="stylesheet" type="text/css" href="', api_get_path(WEB_CODE_PATH), 'css/default.css">';
+    echo $javascript;
+} else {
     Display::display_header($nameTools, 'Dropbox');
-} else { // if we come from the learning path we have to include the stylesheet and the required javascripts manually.
-	echo '<link rel="stylesheet" type="text/css" href="', api_get_path(WEB_CODE_PATH), 'css/default.css">';
-	echo $javascript;
 }
-
-// api_display_tool_title($nameTools);

+ 49 - 96
main/dropbox/dropbox_submit.php

@@ -95,55 +95,55 @@ if (isset($_POST['submitWork'])) {
             // Transform any .php file in .phps fo security
             $dropbox_filename = php2phps($dropbox_filename);
             if (!filter_extension($dropbox_filename)) {
-            	$error = true;
-            	$errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
+                $error = true;
+                $errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
             } else {
-	            // set title
-	            $dropbox_title = $dropbox_filename;
-
-	            // set author
-	            if ($_POST['authors'] == '') {
-	                $_POST['authors'] = getUserNameFromId($_user['user_id']);
-	            }
-
-				if ($dropbox_overwrite) {
-					$dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
-
-					foreach ($dropbox_person->sentWork as $w) {
-						if ($w->title == $dropbox_filename) {
-						    if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
-								$error = true;
-								$errormsg = get_lang('MailingNonMailingError');
-							}
-							if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
-								$error = true;
-								$errormsg = get_lang('MailingJustUploadSelectNoOther');
-							}
-							$dropbox_filename = $w->filename;
-							$found = true;
-							break;
-						}
-					}
-				} else {
-					// rename file to login_filename_uniqueId format
-					$dropbox_filename = getLoginFromId( $_user['user_id']) . '_' . $dropbox_filename . '_'.uniqid('');
-				}
-
-				if (!is_dir(dropbox_cnf('sysPath'))) {
-					//The dropbox subdir doesn't exist yet so make it and create the .htaccess file
-	                mkdir(dropbox_cnf('sysPath'), api_get_permissions_for_new_directories()) or die(get_lang('ErrorCreatingDir').' (code 404)');
-					$fp = fopen(dropbox_cnf('sysPath').'/.htaccess', 'w') or die(get_lang('ErrorCreatingDir').' (code 405)');
-					fwrite($fp, "AuthName AllowLocalAccess
-	                             AuthType Basic
-
-	                             order deny,allow
-	                             deny from all
-
-	                             php_flag zlib.output_compression off") or die(get_lang('ErrorCreatingDir').' (code 406)');
-	            }
-
-				if ($error) {}
-				elseif ($thisIsAMailing) {
+                // set title
+                $dropbox_title = $dropbox_filename;
+
+                // set author
+                if ($_POST['authors'] == '') {
+                    $_POST['authors'] = getUserNameFromId($_user['user_id']);
+                }
+
+                if ($dropbox_overwrite) {
+                    $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
+
+                    foreach ($dropbox_person->sentWork as $w) {
+                        if ($w->title == $dropbox_filename) {
+                            if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
+                                $error = true;
+                                $errormsg = get_lang('MailingNonMailingError');
+                            }
+                            if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
+                                $error = true;
+                                $errormsg = get_lang('MailingJustUploadSelectNoOther');
+                            }
+                            $dropbox_filename = $w->filename;
+                            $found = true;
+                            break;
+                        }
+                    }
+                } else {
+                    // rename file to login_filename_uniqueId format
+                    $dropbox_filename = getLoginFromId( $_user['user_id']) . '_' . $dropbox_filename . '_'.uniqid('');
+                }
+
+                if (!is_dir(dropbox_cnf('sysPath'))) {
+                    //The dropbox subdir doesn't exist yet so make it and create the .htaccess file
+                    mkdir(dropbox_cnf('sysPath'), api_get_permissions_for_new_directories()) or die(get_lang('ErrorCreatingDir').' (code 404)');
+                    $fp = fopen(dropbox_cnf('sysPath').'/.htaccess', 'w') or die(get_lang('ErrorCreatingDir').' (code 405)');
+                    fwrite($fp, "AuthName AllowLocalAccess
+                                 AuthType Basic
+
+                                 order deny,allow
+                                 deny from all
+
+                                 php_flag zlib.output_compression off") or die(get_lang('ErrorCreatingDir').' (code 406)');
+                }
+
+				if ($error) {
+                } elseif ($thisIsAMailing) {
 				    if (preg_match(dropbox_cnf('mailingZipRegexp'), $dropbox_title)) {
 			            $newWorkRecipients = dropbox_cnf('mailingIdBase');
 					} else {
@@ -172,7 +172,7 @@ if (isset($_POST['submitWork'])) {
 				// After uploading the file, create the db entries
 
 	        	if (!$error) {
-		            @move_uploaded_file( $dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename)
+		            @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename)
 		            	or die(get_lang('UploadError').' (code 407)');
 		            new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $newWorkRecipients);
 	        	}
@@ -180,11 +180,9 @@ if (isset($_POST['submitWork'])) {
         }
     } //end if(!$error)
 
-
     /**
      * SUBMIT FORM RESULTMESSAGE
      */
-
     if (!$error) {
 		$return_message = get_lang('FileUploadSucces');
     } else {
@@ -192,51 +190,6 @@ if (isset($_POST['submitWork'])) {
     }
 }
 
-function findRecipient($thisFile) {
-	// string result = error message, array result = [user_id, lastname, firstname, status]
-	global $nameParts, $preFix, $preLen, $postFix, $postLen;
-    if (preg_match(dropbox_cnf('mailingFileRegexp'), $thisFile, $matches)) {
-        $thisName = $matches[1];
-        if (api_substr($thisName, 0, $preLen) == $preFix) {
-            if ($postLen == 0 || api_substr($thisName, -$postLen) == $postFix) {
-	            $thisRecip = api_substr($thisName, $preLen, api_strlen($thisName) - $preLen - $postLen);
-	            if ($thisRecip) {
-	            	return getUser($thisRecip);
-	            }
-	            return ' <'.get_lang('MailingFileNoRecip', '').'>';
-            } else {
-	            return ' <'.get_lang('MailingFileNoPostfix', '').$postFix.'>';
-            }
-        } else {
-            return ' <'.get_lang('MailingFileNoPrefix', '').$preFix.'>';
-        }
-    } else {
-        return ' <'.get_lang('MailingFileFunny', '').'>';
-    }
-}
-
-function getUser($thisRecip) {
-	// string result = error message, array result = [user_id, lastname, firstname]
-
-	global $var, $sel;
-    if (isset($students)) {
-        unset($students);
-    }
-
-    $result = Database::query($sel . $thisRecip . "'");
-    while ( ($res = Database::fetch_array($result))) {$students[] = $res;}
-    Database::free_result($result);
-
-	if (count($students) == 1) {
-    	return($students[0]);
-	} elseif (count($students) > 1) {
-    	return ' <'.get_lang('MailingFileRecipDup', '').$var."= $thisRecip>";
-	} else {
-    	return ' <'.get_lang('MailingFileRecipNotFound', '').$var."= $thisRecip>";
-	}
-}
-
-
 /**
  * DELETE RECEIVED OR SENT FILES - EDIT FEEDBACK
  * - DELETE ALL RECEIVED FILES

+ 64 - 141
main/dropbox/index.php

@@ -1,109 +1,23 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-/**
- * @desc The dropbox is a personal (peer to peer) file exchange module that allows
- * you to send documents to a certain (group of) users.
- *
- * @version 1.3
- *
- * @author Jan Bols <jan@ivpv.UGent.be>, main programmer, initial version
- * @author René Haentjens <rene.haentjens@UGent.be>, several contributions
- * @author Roan Embrechts, virtual course support
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University (see history version 1.3)
- *
- * @package chamilo.dropbox
- *
- * @todo complete refactoring. Currently there are about at least 3 sql queries needed for every individual dropbox document.
- *			first we find all the documents that were sent (resp. received) by the user
- *			then for every individual document the user(s)information who received (resp. sent) the document is searched
- *			then for every individual document the feedback is retrieved
- * @todo 	the implementation of the dropbox categories could (on the database level) have been done more elegantly by storing the category
- *			in the dropbox_person table because this table stores the relationship between the files (sent OR received) and the users
- */
-
-/**
-					HISTORY
-Version 1.1
-------------
-- dropbox_init1.inc.php: changed include statements to require statements. This way if a file is not found, it stops the execution of a script instead of continuing with warnings.
-- dropbox_init1.inc.php: the include files "claro_init_global.inc.php" & "debug.lib.inc.php" are first checked for their existence before including them. If they don't exist, in the .../include dir, they get loaded from the .../inc dir. This change is necessary because the UCL changed the include dir to inc.
-- dropbox_init1.inc.php: the databasetable name in the variable $dropbox_cnf["introTbl"] is chnged from "introduction" to "tool_intro"
-- install.php: after submit, checks if the database uses accueil or tool_list as a tablename
-- index.php: removed the behaviour of only the teachers that are allowed to delete entries
-- index.php: added field "lastUploadDate" in table dropbox_file to store information about last update when resubmiting a file
-- dropbox.inc.php: added $lang["lastUpdated"]
-- index.php: entries in received list show when file was last updated if it is updated
-- index.php: entries in sent list show when file was last resent if it was resent
-- dropbox_submit.php: add a unique id to every uploaded file
-- index.php: add POST-variable to the upload form with overwrite data when user decides to overwrite the previous sent file with new file
-- dropbox_submit.php: add sanity checks on POST['overwrite'] data
-- index.php: remove title field in upload form
-- dropbox_submit.php: remove use of POST['title'] variable
-- dropbox_init1.inc.php: added $dropbox_cnf["version"] variable
-- dropbox_class.inc.php: add $this->lastUploadDate to Dropbox_work class
-- dropbox.inc.php: added $lang['emptyTable']
-- index.php: if the received or sent list is empty, a message is displayed
-- dropbox_download.php: the $file var is set equal to the title-field of the filetable. So not constructed anymore by substracting the username from the filename
-- index.php: add check to see if column lastUploadDate exists in filetable
-- index.php: moved javascripts from dropbox_init2.inc.php to index.php
-- index.php: when specifying an uploadfile in the form, a checkbox allowing the user to overwrite a previously sent file is shown when the specified file has the same name as a previously uploaded file of that user.
-- index.php: assign all the metadata (author, description, date, recipient, sender) of an entry in a list to the class="dropbox_detail" and add css to html-header
-- index.php: assign all dates of entries in list to the class="dropbox_date" and add CSS
-- index.php: assign all persons in entries of list to the class="dropbox_person" and add CSS
-- dropbox.inc.php: added $lang['dropbox_version'] to indicate the lates version. This must be equal to the $dropbox_cnf['version'] variable.
-- dropbox_init1.inc.php: if the newest lang file isn't loaded by claro_init_global.inc.php from the .../lang dir it will be loaded locally from the .../plugin/dropbox/ dir. This way an administrator must not install the dropbox.inc.php in the .../lang/english dir, but he can leave it in the local .../plugin/dropbox/ dir. However if you want to present multiple language translations of the file you must still put the file in the /lang/ dir, because there is no language management system inside the .../plugin/dropbox dir.
-- mime.inc.php: created this file. It contains an array $mimetype with all the mimetypes that are used by dropbox_download.php to give hinst to the browser during download about content
-- dropbox_download.php: remove https specific headers because they're not necessary
-- dropbox_download.php: use application/octet-stream as the default mime and inline as the default Content-Disposition
-- dropbox.inc.php: add lang vars for "order by" action
-- dropbox_class.inc.php: add methods orderSentWork, orderReceivedWork en _cmpWork and propery _orderBy to class Dropbox_person to take care of sorting
-- index.php: add selectionlist to headers of sent/received lists to select "order by" and add code to keep selected value in sessionvar.
-- index.php: moved part of a <a> hyperlink to previous line to remove the underlined space between symbol and title of a work entry in the sent/received list
-- index.php: add filesize info in sent/received lists
-- dropbox_submit.php: resubmit prevention only for GET action, because it gives some annoying behaviour in POST situation: white screen in IE6
-
-Version 1.2
------------
-- adapted entire dropbox tool so it can be used as a default tool in Dokeos 1.5
-- index.php: add event registration to log use of tool in stats tables
-- index.php: upload form checks for correct user selection and file specification before uploading the script
-- dropbox_init1.inc.php: added dropbox_cnf["allowOverwrite"] to allow or disallow overwriting of files
-- index.php: author name textbox is automatically filled in
-- mailing functionality (René Haentjens)
-- allowStudentToStudent and allowJustUpload options (id.)
-- help in separate window (id.)
-
-Version 1.3 (Patrick Cool)
---------------------------
-- sortable table
-- categories
-- fixing a security hole
-- tabs (which can be disabled: see $dropbox_cnf['sent_received_tabs'])
-- same action on multiple documents ([zip]download, move, delete)
-- consistency with the docuements tool (open/download file, icons of documents, ...)
-- zip download of complete folder
-
-Version 1.4 (Yannick Warnier)
------------------------------
-- removed all self-built database tables names
-
-
- */
-
-/*	INIT SECTION */
-
 // The file that contains all the initialisation stuff (and includes all the configuration stuff)
 require_once 'dropbox_init.inc.php';
 
 // get the last time the user accessed the tool
 if ($_SESSION[$_course['id']]['last_access'][TOOL_DROPBOX] == '') {
-	$last_access = get_last_tool_access(TOOL_DROPBOX, $_course['code'], $_user['user_id']);
+	$last_access = get_last_tool_access(TOOL_DROPBOX);
 	$_SESSION[$_course['id']]['last_access'][TOOL_DROPBOX] = $last_access;
 } else {
 	$last_access = $_SESSION[$_course['id']]['last_access'][TOOL_DROPBOX];
 }
 
+$postAction = isset($_POST['action']) ? $_POST['action'] : null;
+$view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : null;
+$viewReceivedCategory = isset($_GET['view_received_category']) ? Security::remove_XSS($_GET['view_received_category']) : null;
+$viewSentCategory = isset($_GET['view_sent_category']) ? Security::remove_XSS($_GET['view_sent_category']) : null;
+
+
 // Do the tracking
 event_access_tool(TOOL_DROPBOX);
 
@@ -138,7 +52,7 @@ if ($action == 'add') {
 	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
 		api_not_allowed();
 	}
-	display_add_form();
+	display_add_form($dropbox_unid, $viewReceivedCategory, $viewSentCategory, $view);
 }
 
 if (isset($_POST['submitWork'])) {
@@ -183,7 +97,7 @@ if (isset($_POST['StoreCategory'])) {
 	}
 	if ($return_information['type'] == 'error') {
 		Display :: display_error_message(get_lang('FormHasErrorsPleaseComplete').'<br />'.$return_information['message']);
-		display_addcategory_form($_POST['category_name'], $_POST['edit_id'], $_POST['action']);
+		display_addcategory_form($_POST['category_name'], $_POST['edit_id'], $postAction);
 	}
 }
 
@@ -193,7 +107,15 @@ if (($action == 'movesent' OR $action == 'movereceived') AND isset($_GET['move_i
 	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
 		api_not_allowed();
 	}
-	display_move_form(str_replace('move', '', $action), $_GET['move_id'], get_dropbox_categories(str_replace('move', '', $action)), $sort_params);
+	display_move_form(
+        str_replace('move', '', $action),
+        $_GET['move_id'],
+        get_dropbox_categories(str_replace('move', '', $action)),
+        $sort_params,
+        $viewReceivedCategory,
+        $viewSentCategory,
+        $view
+    );
 }
 if (isset($_POST['do_move'])) {
 	Display :: display_confirmation_message(store_move($_POST['id'], $_POST['move_target'], $_POST['part']));
@@ -229,9 +151,9 @@ if (($action == 'deletereceivedcategory' OR $action == 'deletesentcategory') AND
 // only the download has is handled separately in dropbox_init_inc.php because this has to be done before the headers are sent
 // (which also happens in dropbox_init.inc.php
 
-if (!isset($_POST['feedback']) && (strstr($_POST['action'], 'move_received') OR
-    $_POST['action'] == 'delete_received' OR $_POST['action'] == 'download_received' OR
-    $_POST['action'] == 'delete_sent' OR $_POST['action'] == 'download_sent')) {
+if (!isset($_POST['feedback']) && (strstr($postAction, 'move_received') OR
+    $postAction == 'delete_received' OR $postAction == 'download_received' OR
+    $postAction == 'delete_sent' OR $postAction == 'download_sent')) {
 
 	$display_message = handle_multiple_actions();
 	Display :: display_normal_message($display_message);
@@ -272,12 +194,12 @@ if ($action != 'add') {
 	}
 
 	// ACTIONS
-	if ($_GET['view'] == 'received' OR !$dropbox_cnf['sent_received_tabs']) {
+	if ($view == 'received' OR !$dropbox_cnf['sent_received_tabs']) {
 		//echo '<h3>'.get_lang('ReceivedFiles').'</h3>';
 
 		// This is for the categories
-		if (isset($_GET['view_received_category']) AND $_GET['view_received_category'] != '') {
-			$view_dropbox_category_received = Security::remove_XSS($_GET['view_received_category']);
+		if (isset($viewReceivedCategory) AND $viewReceivedCategory != '') {
+			$view_dropbox_category_received = $viewReceivedCategory;
 		} else {
 			$view_dropbox_category_received = 0;
 		}
@@ -287,32 +209,32 @@ if ($action != 'add') {
 		if (api_get_session_id() == 0) {
 			echo '<div class="actions">';
 			if ($view_dropbox_category_received != 0  && api_is_allowed_to_session_edit(false, true)) {
-				echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category=0&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
+				echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category=0&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
 				echo get_lang('Category').': <strong>'.Security::remove_XSS($dropbox_categories[$view_dropbox_category_received]['cat_name']).'</strong> ';
 				$movelist[0] = 'Root'; // move_received selectbox content
 			} else {
-				echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=addreceivedcategory&view='.Security::remove_XSS($_GET['view']).'">'.Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM).'</a>';
+				echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=addreceivedcategory&view='.$view.'">'.Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM).'</a>';
 			}
 			echo '</div>';
 		} else {
 			if (api_is_allowed_to_session_edit(false, true)) {
 				echo '<div class="actions">';
 				if ($view_dropbox_category_received != 0 && api_is_allowed_to_session_edit(false, true)) {
-					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category=0&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
+					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category=0&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
 					echo get_lang('Category').': <strong>'.Security::remove_XSS($dropbox_categories[$view_dropbox_category_received]['cat_name']).'</strong> ';
 					$movelist[0] = 'Root'; // move_received selectbox content
 				} else {
-					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=addreceivedcategory&view='.Security::remove_XSS($_GET['view']).'">'.Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM).'</a>';
+					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=addreceivedcategory&view='.$view.'">'.Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM).'</a>';
 				}
 				echo '</div>';
 			}
 		}
 	}
 
-	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
+	if (!$view OR $view == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
 		// This is for the categories
-		if (isset($_GET['view_sent_category']) AND $_GET['view_sent_category'] != '') {
-			$view_dropbox_category_sent = $_GET['view_sent_category'];
+		if (isset($viewSentCategory) AND $viewSentCategory != '') {
+			$view_dropbox_category_sent = $viewSentCategory;
 		} else {
 			$view_dropbox_category_sent = 0;
 		}
@@ -322,13 +244,13 @@ if ($action != 'add') {
 		if (api_get_session_id() == 0) {
 			echo '<div class="actions">';
 			if ($view_dropbox_category_sent != 0) {
-				echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category=0&amp;view='.Security::remove_XSS($_GET['view']).'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
+				echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category=0&amp;view='.$view.'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
 				echo get_lang('Category').': <strong>'.Security::remove_XSS($dropbox_categories[$view_dropbox_category_sent]['cat_name']).'</strong> ';
 			} else {
-				echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".Security::remove_XSS($_GET['view'])."&amp;action=addsentcategory\">".Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM)."</a>\n";
+				echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".$view."&amp;action=addsentcategory\">".Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM)."</a>\n";
 			}
-			if (empty($_GET['view_sent_category'])) {
-				echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".Security::remove_XSS($_GET['view'])."&amp;action=add\">".Display::return_icon('upload_file.png', get_lang('UploadNewFile'),'',ICON_SIZE_MEDIUM)."</a>";
+			if (empty($viewSentCategory)) {
+				echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".$view."&amp;action=add\">".Display::return_icon('upload_file.png', get_lang('UploadNewFile'),'',ICON_SIZE_MEDIUM)."</a>";
 			}
 			echo '</div>';
 		} else {
@@ -336,12 +258,12 @@ if ($action != 'add') {
 				echo '<div class="actions">';
 				if ($view_dropbox_category_sent != 0) {
 					echo get_lang('CurrentlySeeing').': <strong>'.Security::remove_XSS($dropbox_categories[$view_dropbox_category_sent]['cat_name']).'</strong> ';
-					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category=0&amp;view='.Security::remove_XSS($_GET['view']).'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
+					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category=0&amp;view='.$view.'">'.Display::return_icon('folder_up.png', get_lang('Up').' '.get_lang('Root'),'',ICON_SIZE_MEDIUM)."</a>";
 				} else {
-					echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".Security::remove_XSS($_GET['view'])."&amp;action=addsentcategory\">".Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM)."</a>\n";
+					echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".$view."&amp;action=addsentcategory\">".Display::return_icon('new_folder.png', get_lang('AddNewCategory'),'',ICON_SIZE_MEDIUM)."</a>\n";
 				}
-				if (empty($_GET['view_sent_category'])) {
-					echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".Security::remove_XSS($_GET['view'])."&amp;action=add\">".Display::return_icon('upload_file.png', get_lang('UploadNewFile'),'',ICON_SIZE_MEDIUM)."</a>";
+				if (empty($viewSentCategory)) {
+					echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&view=".$view."&amp;action=add\">".Display::return_icon('upload_file.png', get_lang('UploadNewFile'),'',ICON_SIZE_MEDIUM)."</a>";
 				}
 				echo '</div>';
 			}
@@ -354,9 +276,9 @@ if ($action != 'add') {
 ?>
 
 <ul class="nav nav-tabs">
-    <li <?php if (!$_GET['view'] OR $_GET['view'] == 'sent') { echo 'class="active"'; } ?> >
+    <li <?php if (!$view OR $view == 'sent') { echo 'class="active"'; } ?> >
         <a href="index.php?<?php echo api_get_cidreq(); ?>&view=sent" ><?php echo get_lang('SentFiles'); ?></a></li>
-    <li <?php if ($_GET['view'] == 'received') { echo 'class="active"'; } ?> >
+    <li <?php if ($view == 'received') { echo 'class="active"'; } ?> >
         <a href="index.php?<?php echo api_get_cidreq(); ?>&view=received"  ><?php echo get_lang('ReceivedFiles'); ?></a></li>
 </ul>
 
@@ -365,10 +287,10 @@ if ($action != 'add') {
 
 	/*	RECEIVED FILES */
 
-	if ($_GET['view'] == 'received' OR !$dropbox_cnf['sent_received_tabs']) {
+	if ($view == 'received' OR !$dropbox_cnf['sent_received_tabs']) {
 		// This is for the categories
-		if (isset($_GET['view_received_category']) AND $_GET['view_received_category'] != '') {
-			$view_dropbox_category_received = $_GET['view_received_category'];
+		if (isset($viewReceivedCategory) AND $viewReceivedCategory != '') {
+			$view_dropbox_category_received = $viewReceivedCategory;
 		} else {
 			$view_dropbox_category_received = 0;
 		}
@@ -453,16 +375,16 @@ if ($action != 'add') {
 				$dropbox_file_data[] = date_to_str_ago($last_upload_date).'<br /><span class="dropbox_date">'.api_format_date($last_upload_date).'</span>';
 
 				$action_icons = check_number_feedback($dropbox_file->id, $number_feedback).' '.get_lang('Feedback').'
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('discuss.png', get_lang('Comment'),'',ICON_SIZE_SMALL).'</a>
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=movereceived&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletereceivedfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('discuss.png', get_lang('Comment'),'',ICON_SIZE_SMALL).'</a>
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=movereceived&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=deletereceivedfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.
                                     Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
 
 				// This is a hack to have an additional row in a sortable table
 
 				if ($action == 'viewfeedback' AND isset($_GET['id']) and is_numeric($_GET['id']) AND $dropbox_file->id == $_GET['id']) {
 					$action_icons .= "</td></tr>"; // Ending the normal row of the sortable table
-					$action_icons .= '<tr><td colspan="2"><a href="index.php?"'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category'])."&amp;view_sent_category=".Security::remove_XSS($_GET['view_sent_category'])."&amp;view=".Security::remove_XSS($_GET['view']).'&'.$sort_params."\">".get_lang('CloseFeedback')."</a></td><td colspan=\"7\">".feedback($dropbox_file->feedback2)."</td></tr>";
+					$action_icons .= '<tr><td colspan="2"><a href="index.php?"'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory."&amp;view_sent_category=".$viewSentCategory."&amp;view=".$view.'&'.$sort_params."\">".get_lang('CloseFeedback')."</a></td><td colspan=\"7\">".feedback($dropbox_file->feedback2)."</td></tr>";
 				}
 				if (api_get_session_id() == 0) {
 					$dropbox_file_data[] = $action_icons;
@@ -484,14 +406,14 @@ if ($action != 'add') {
 					$movelist[$category['cat_id']] = $category['cat_name'];
 					$dropbox_category_data[] = $category['cat_id']; // This is where the checkbox icon for the files appear
 					// The icon of the category
-					$link_open = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$category['cat_id'].'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'">';
+					$link_open = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$category['cat_id'].'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'">';
 					$dropbox_category_data[] = $link_open.build_document_icon_tag('folder', $category['cat_name']).'</a>';
 					$dropbox_category_data[] = '<a href="dropbox_download.php?'.api_get_cidreq().'&cat_id='.$category['cat_id'].'&amp;action=downloadcategory&amp;sent_received=received">'.Display::return_icon('save_pack.png', get_lang('Save'), array('style' => 'float:right;'),ICON_SIZE_SMALL).'</a>'.$link_open.$category['cat_name'].'</a>';
 					$dropbox_category_data[] = '';
 					$dropbox_category_data[] = '';
 					$dropbox_category_data[] = '';
-					$dropbox_category_data[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=editcategory&amp;id='.$category['cat_id'].'">'.Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>
-										  <a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletereceivedcategory&amp;id='.$category['cat_id'].'" onclick="javascript: return confirmation(\''.Security::remove_XSS($category['cat_name']).'\');">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
+					$dropbox_category_data[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=editcategory&amp;id='.$category['cat_id'].'">'.Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>
+										  <a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=deletereceivedcategory&amp;id='.$category['cat_id'].'" onclick="javascript: return confirmation(\''.Security::remove_XSS($category['cat_name']).'\');">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
 				}
 				if (is_array($dropbox_category_data) && count($dropbox_category_data) > 0) {
 					$dropbox_data_recieved[] = $dropbox_category_data;
@@ -499,7 +421,7 @@ if ($action != 'add') {
 			}
 		}
 		// Displaying the table
-		$additional_get_parameters = array('view' => $_GET['view'], 'view_received_category' => $_GET['view_received_category'], 'view_sent_category' => $_GET['view_sent_category']);
+		$additional_get_parameters = array('view' => $view, 'view_received_category' => $viewReceivedCategory, 'view_sent_category' => $viewSentCategory);
 		$selectlist = array('delete_received' => get_lang('Delete'), 'download_received' => get_lang('Download'));
 		if (is_array($movelist)) {
 			foreach ($movelist as $catid => $catname){
@@ -516,10 +438,10 @@ if ($action != 'add') {
 
 	/*	SENT FILES */
 
-	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
+	if (!$view OR $view == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
 		// This is for the categories
-		if (isset($_GET['view_sent_category']) AND $_GET['view_sent_category'] != '') {
-			$view_dropbox_category_sent = $_GET['view_sent_category'];
+		if (isset($viewSentCategory) AND $viewSentCategory != '') {
+			$view_dropbox_category_sent = $viewSentCategory;
 		} else {
 			$view_dropbox_category_sent = 0;
 		}
@@ -588,6 +510,7 @@ if ($action != 'add') {
 				$dropbox_file_data[] = '<a href="dropbox_download.php?'.api_get_cidreq().'&id='.$dropbox_file->id.'&amp;action=download">'.Display::return_icon('save.png', get_lang('Save'), array('style' => 'float:right;'),ICON_SIZE_SMALL).'</a>'.$link_open.$dropbox_file->title.'</a><br />'.$dropbox_file->description;
 				$file_size = $dropbox_file->filesize;
 				$dropbox_file_data[] = format_file_size($file_size);
+                $receivers_celldata = null;
 				foreach ($dropbox_file->recipients as $recipient) {
 					$receivers_celldata = display_user_link_work($recipient['user_id'], $recipient['name']).', '.$receivers_celldata;
 				}
@@ -600,14 +523,14 @@ if ($action != 'add') {
 				$receivers_celldata = '';
 
 				$action_icons = check_number_feedback($dropbox_file->id, $number_feedback).' '.get_lang('Feedback').'
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('discuss.png', get_lang('Comment'),'',ICON_SIZE_SMALL).'</a>
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=movesent&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletesentfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('discuss.png', get_lang('Comment'),'',ICON_SIZE_SMALL).'</a>
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=movesent&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=deletesentfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
 				// This is a hack to have an additional row in a sortable table
 				if ($action == 'viewfeedback' && isset($_GET['id']) && is_numeric($_GET['id']) && $dropbox_file->id == $_GET['id']) {
 					$action_icons .= "</td></tr>\n"; // ending the normal row of the sortable table
 					$action_icons .= "<tr><td colspan=\"2\">";
-					$action_icons .= "<a href=\"index.php?".api_get_cidreq()."&view_received_category=".Security::remove_XSS($_GET['view_received_category'])."&view_sent_category=".Security::remove_XSS($_GET['view_sent_category'])."&view=".Security::remove_XSS($_GET['view']).'&'.$sort_params."\">".get_lang('CloseFeedback')."</a>";
+					$action_icons .= "<a href=\"index.php?".api_get_cidreq()."&view_received_category=".$viewReceivedCategory."&view_sent_category=".$viewSentCategory."&view=".$view.'&'.$sort_params."\">".get_lang('CloseFeedback')."</a>";
 					$action_icons .= "</td><td colspan=\"7\">".feedback($dropbox_file->feedback2)."</td></tr>";
 				}
 				$dropbox_file_data[] = $action_icons;
@@ -624,7 +547,7 @@ if ($action != 'add') {
 				$dropbox_category_data = array();
 				if ($category['sent'] == '1') {
 					$dropbox_category_data[] = $category['cat_id']; // This is where the checkbox icon for the files appear.
-					$link_open = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.$category['cat_id'].'&amp;view='.Security::remove_XSS($_GET['view']).'">';
+					$link_open = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$category['cat_id'].'&amp;view='.$view.'">';
 					$dropbox_category_data[] = $link_open.build_document_icon_tag('folder', Security::remove_XSS($category['cat_name'])).'</a>';
 					$dropbox_category_data[] = '<a href="dropbox_download.php?'.api_get_cidreq().'&cat_id='.$category['cat_id'].'&amp;action=downloadcategory&amp;sent_received=sent">'.Display::return_icon('save_pack.png', get_lang('Save'), array('style' => 'float:right;'),ICON_SIZE_SMALL).'</a>'.$link_open.Security::remove_XSS($category['cat_name']).'</a>';
 					//$dropbox_category_data[] = '';
@@ -632,9 +555,9 @@ if ($action != 'add') {
 					//$dropbox_category_data[] = '';
 					$dropbox_category_data[] = '';
 					$dropbox_category_data[] = '';
-					$dropbox_category_data[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=editcategory&id='.$category['cat_id'].'">'.
+					$dropbox_category_data[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=editcategory&id='.$category['cat_id'].'">'.
                                     Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletesentcategory&amp;id='.$category['cat_id'].'" onclick="javascript: return confirmation(\''.Security::remove_XSS($category['cat_name']).'\');">'.
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$viewReceivedCategory.'&amp;view_sent_category='.$viewSentCategory.'&amp;view='.$view.'&amp;action=deletesentcategory&amp;id='.$category['cat_id'].'" onclick="javascript: return confirmation(\''.Security::remove_XSS($category['cat_name']).'\');">'.
                                     Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
 				}
 				if (is_array($dropbox_category_data) && count($dropbox_category_data) > 0) {
@@ -643,7 +566,7 @@ if ($action != 'add') {
 			}
 		}
 		// Displaying the table
-		$additional_get_parameters = array('view' => Security::remove_XSS($_GET['view']), 'view_received_category' => Security::remove_XSS($_GET['view_received_category']), 'view_sent_category' => Security::remove_XSS($_GET['view_sent_category']));
+		$additional_get_parameters = array('view' => $view, 'view_received_category' => $viewReceivedCategory, 'view_sent_category' => $viewSentCategory);
 		$selectlist = array('delete_received' => get_lang('Delete'), 'download_received' => get_lang('Download'));
 		if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
 			$selectlist = array('download_received' => get_lang('Download'));

+ 2 - 2
main/dropbox/recover_dropbox_files.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 require_once 'dropbox_init.inc.php';
 
 $file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
@@ -38,7 +39,6 @@ if (Database::num_rows($result)) {
         $sql = "SELECT * FROM $person_tbl WHERE c_id = $course_id AND user_id = $user_id AND file_id = {$file['id']}";
         $result_person = Database::query($sql);
         if (Database::num_rows($result_person) == 0 ) {
-
             $rows[] = array(
                     $file['filename'],
                     api_convert_and_format_date($file['upload_date']),
@@ -49,4 +49,4 @@ if (Database::num_rows($result)) {
     $headers = array(get_lang('Filename'), get_lang('UploadedDate'), get_lang('Action'));
     echo Display::table($headers, $rows);
 }
-Display::display_footer();
+Display::display_footer();

+ 1 - 1
main/exercice/exercise.class.php

@@ -1229,7 +1229,7 @@ class Exercise {
      */
     function processCreation($form, $type='') {
 
-        $this->updateTitle($form->getSubmitValue('exerciseTitle'));
+        $this->updateTitle(htmlentities($form->getSubmitValue('exerciseTitle')));
         $this->updateDescription($form->getSubmitValue('exerciseDescription'));
         $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
         $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));

+ 5 - 1
main/inc/ajax/admin.ajax.php

@@ -91,6 +91,9 @@ function check_system_version()
         $number_of_users = Statistics::count_users();
         $number_of_active_users = Statistics::count_users(null, null, null, true);
 
+        // The number of sessions
+        $number_of_sessions = Statistics::count_sessions();
+
         $data = array(
             'url' => api_get_path(WEB_PATH),
             'campus' => api_get_setting('siteName'),
@@ -99,6 +102,7 @@ function check_system_version()
             'numberofcourses' => $number_of_courses,
             'numberofusers' => $number_of_users,
             'numberofactiveusers' => $number_of_active_users,
+            'numberofsessions' => $number_of_sessions,
             //The donotlistcampus setting recovery should be improved to make
             // it true by default - this does not affect numbers counting
             'donotlistcampus' => api_get_setting('donotlistcampus'),
@@ -137,7 +141,7 @@ function check_system_version()
  * @param bool   Include HTTP Request headers?
  * @param bool   Include HTTP Response headers?
  */
-function _http_request($ip, $port = 80, $uri = '/', $getdata = array(), $timeout = 1, $req_hdr = false, $res_hdr = false)
+function _http_request($ip, $port = 80, $uri = '/', $getdata = array(), $timeout = 5, $req_hdr = false, $res_hdr = false)
 {
     $verb = 'GET';
     $ret = '';

+ 216 - 7
main/inc/ajax/model.ajax.php

@@ -31,6 +31,7 @@ if (!in_array($sord, array('asc','desc'))) {
     $sord = 'desc';
 }
 
+// Actions allowed to other roles.
 if (!in_array(
     $action,
     array(
@@ -45,7 +46,8 @@ if (!in_array(
         'get_user_skill_ranking',
         'get_usergroups_teacher',
         'get_user_course_report_resumed',
-        'get_user_course_report'
+        'get_user_course_report',
+        'get_sessions_tracking'
     )
 )) {
     api_protect_admin_script(true);
@@ -159,7 +161,12 @@ switch ($action) {
         if ($action == 'get_user_course_report') {
             $count = CourseManager::get_count_user_list_from_course_code(false, null, $courseCodeList, $userIdList);
         } else {
-            $count = CourseManager::get_count_user_list_from_course_code(true, 'ruc', $courseCodeList, $userIdList);
+            $count = CourseManager::get_count_user_list_from_course_code(
+                true,
+                array('ruc'),
+                $courseCodeList,
+                $userIdList
+            );
         }
         break;
     case 'get_course_exercise_medias':
@@ -220,6 +227,14 @@ switch ($action) {
         $hotpot_path = $_REQUEST['path'];
         $count = get_count_exam_hotpotatoes_results($hotpot_path);
         break;
+    case 'get_sessions_tracking':
+        if (api_is_drh()) {
+            $count = SessionManager::get_sessions_followed_by_drh(api_get_user_id(), null, null, true);
+        } else {
+            // Sessions for the coach
+            $count = Tracking::get_sessions_coached_by_user(api_get_user_id(), null, null, true);
+        }
+        break;
     case 'get_sessions':
         $courseId = isset($_GET['course_id']) && !empty($_GET['course_id']) ? intval($_GET['course_id']) : null;
         if (!empty($courseId)) {
@@ -228,7 +243,16 @@ switch ($action) {
         $count = SessionManager::get_count_admin($where_condition);
         break;
     case 'get_session_lp_progress':
-        $count = SessionManager::get_count_session_lp_progress($_GET['session_id']);
+    case 'get_session_progress':
+        $courses = SessionManager::get_course_list_by_session_id(intval($_GET['session_id']));
+        //TODO let select course
+        $course = current($courses);
+        $users = CourseManager::get_student_list_from_course_code($course['code'], true, intval($_GET['session_id']));
+        $count = count($users);
+        break;
+    case 'get_exercise_progress':
+        $records = SessionManager::get_exercise_progress(intval($_GET['session_id']));
+        $count = count($records);
         break;
     /*case 'get_extra_fields':
         $type = $_REQUEST['type'];
@@ -318,7 +342,12 @@ switch ($action) {
         break;
     case 'get_user_course_report_resumed':
         $columns = array(
-            'extra_ruc', 'training_hours', 'count_users', 'count_users_registered', 'average_hours_per_user', 'count_certificates'
+            'extra_ruc',
+            'training_hours',
+            'count_users',
+            'count_users_registered',
+            'average_hours_per_user',
+            'count_certificates'
         );
 
         $column_names = array(
@@ -330,6 +359,18 @@ switch ($action) {
             get_lang('CountCertificates')
         );
 
+        $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
+
+        if (!empty($extra_fields)) {
+            foreach ($extra_fields as $extra) {
+                if ($extra['1'] == 'ruc') {
+                    continue;
+                }
+                $columns[] = $extra['1'];
+                $column_names[] = $extra['3'];
+            }
+        }
+
         $result = CourseManager::get_user_list_from_course_code(
             null,
             null,
@@ -339,10 +380,11 @@ switch ($action) {
             null,
             true,
             true,
-            'ruc',
+            array('ruc'),
             $courseCodeList,
             $userIdList
         );
+
         $new_result = array();
         if (!empty($result)) {
             foreach ($result as $row) {
@@ -363,6 +405,7 @@ switch ($action) {
             get_lang('Approved'),
             get_lang('CourseAdvance')
         );
+
         $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
         if (!empty($extra_fields)) {
             foreach ($extra_fields as $extra) {
@@ -384,6 +427,7 @@ switch ($action) {
             $courseCodeList,
             $userIdList
         );
+
         break;
 	case 'get_user_skill_ranking':
         $columns = array('photo', 'firstname', 'lastname', 'skills_acquired', 'currently_learning', 'rank');
@@ -482,6 +526,57 @@ switch ($action) {
 		$columns = array('firstname', 'lastname', 'username', 'group_name', 'exe_date',  'score', 'actions');
 		$result = get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $where_condition); //get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $where_condition);
 		break;
+    case 'get_sessions_tracking':
+        if (api_is_drh()) {
+            $sessions = SessionManager::get_sessions_followed_by_drh(api_get_user_id(), $start, $limit);
+        } else {
+            // Sessions for the coach
+            $sessions = Tracking::get_sessions_coached_by_user(api_get_user_id(), $start, $limit);
+        }
+
+        $columns =  array(
+            'name',
+            'date',
+            'course_per_session',
+            'student_per_session',
+            'details'
+        );
+
+        $result = array();
+        if (!empty($sessions)) {
+            foreach ($sessions as $session) {
+                if (api_drh_can_access_all_session_content()) {
+                    $count_courses_in_session = count(SessionManager::get_course_list_by_session_id($session['id']));
+                } else {
+                    $count_courses_in_session = count(Tracking::get_courses_followed_by_coach($user_id, $session['id']));
+                }
+
+                $count_users_in_session = count(SessionManager::get_users_by_session($session['id'], 0));
+                $session_date = array();
+                if (!empty($session['date_start']) && $session['date_start'] != '0000-00-00') {
+                    $session_date[] = get_lang('From').' '.api_format_date($session['date_start'], DATE_FORMAT_SHORT);
+                }
+
+                if (!empty($session['date_end']) && $session['date_end'] != '0000-00-00') {
+                    $session_date[] = get_lang('Until').' '.api_format_date($session['date_end'], DATE_FORMAT_SHORT);
+                }
+
+                if (empty($session_date)) {
+                    $session_date_string = '-';
+                } else {
+                    $session_date_string = implode(' ', $session_date);
+                }
+                $sessionUrl = api_get_path(WEB_CODE_PATH).'mySpace/index.php?session_id='.$session['id'];
+                $result[] = array(
+                    'name' => $session['name'],
+                    'date' => $session_date_string,
+                    'course_per_session' => $count_courses_in_session,
+                    'student_per_session' => $count_users_in_session,
+                    'details' => Display::url(Display::return_icon('2rightarrow.gif'), $sessionUrl)
+                );
+            }
+        }
+        break;
     case 'get_sessions':
         $columns = array(
             'name', 'nbr_courses', 'nbr_users', 'category_name', 'date_start','date_end', 'coach_name', 'session_active', 'visibility'
@@ -495,15 +590,65 @@ switch ($action) {
             )
         );
         break;
-    case 'get_session_lp_progress':
+    case 'get_exercise_progress':
+        $sessionId = 0;
+        if (isset($_GET['session_id']) && !empty($_GET['session_id']))
+        {
+            $sessionId = intval($_GET['session_id']);
+            $courses = SessionManager::get_course_list_by_session_id($sessionId);
+            //TODO let select course
+            $course = current($courses);
+        }
+
         $columns = array(
-            'username', 'firstname', 'lastname', 'name', 'progress'
+            'session',
+            'exercise_id',
+            'quiz_title',
+            'username',
+            'lastname',
+            'firstname',
+            'time',
+            'question_id',
+            'question',
+            'answer',
+            'correct'
+        );
+
+        $result = SessionManager::get_exercise_progress($sessionId,
+            array(
+                'where' => $where_condition,
+                'order' => "$sidx $sord",
+                'limit'=> "$start , $limit"
+            )
         );
+        break;
+    case 'get_session_lp_progress':
         $sessionId = 0;
         if (isset($_GET['session_id']) && !empty($_GET['session_id']))
         {
             $sessionId = intval($_GET['session_id']);
+            $courses = SessionManager::get_course_list_by_session_id($sessionId);
+            //TODO let select course
+            $course = current($courses);
+        }
+
+        /**
+         * Add lessons of course
+         *
+         */
+        $columns = array(
+            'username',
+            'firstname',
+            'lastname',
+        );
+        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+        $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
+        foreach ($lessons as $lesson_id => $lesson)
+        {
+            $columns[] = $lesson_id;
         }
+        $columns[] = 'total';
+
         $result = SessionManager::get_session_lp_progress($sessionId,
             array(
                 'where' => $where_condition,
@@ -512,6 +657,67 @@ switch ($action) {
             )
         );
         break;
+    case 'get_session_progress':
+        $columns = array(
+            'lastname',
+            'firstname',
+            'username',
+            #'profile',
+            'total',
+            'courses',
+            'lessons',
+            'exercises',
+            'forums',
+            'homeworks',
+            'wikis',
+            'surveys',
+            //course description
+            'course_description_progress',
+            //exercises
+            'lessons_total' ,
+            'lessons_done' ,
+            'lessons_left' ,
+            'lessons_progress',
+            //exercises
+            'exercises_total' ,
+            'exercises_done' ,
+            'exercises_left' ,
+            'exercises_progress' ,
+            //forums
+            'forums_total' ,
+            'forums_done' ,
+            'forums_left' ,
+            'forums_progress' ,
+            //assignments
+            'assignments_total' ,
+            'assignments_done' ,
+            'assignments_left' ,
+            'assignments_progress' ,
+            //Wiki
+            'wiki_total',
+            'wiki_revisions',
+            'wiki_read',
+            'wiki_unread',
+            'wiki_progress',
+            //surveys
+            'surveys_total' ,
+            'surveys_done' ,
+            'surveys_left' ,
+            'surveys_progress' ,
+            );
+        $sessionId = 0;
+        if (isset($_GET['session_id']) && !empty($_GET['session_id']))
+        {
+            $sessionId = intval($_GET['session_id']);
+        }
+        $result = SessionManager::get_session_progress($sessionId,
+            array(
+                'where' => $where_condition,
+                'order' => "$sidx $sord",
+                'limit'=> "$start , $limit"
+            )
+        );
+        break;
     case 'get_timelines':
         $columns = array('headline', 'actions');
 
@@ -711,7 +917,10 @@ $allowed_actions = array(
     'get_usergroups_teacher',
     'get_gradebooks',
     'get_sessions',
+    'get_sessions_tracking',
     'get_session_lp_progress',
+    'get_session_progress',
+    'get_exercise_progress',
     'get_exercise_results',
     'get_hotpotatoes_exercise_results',
     'get_work_teacher',

+ 92 - 74
main/inc/introductionSection.inc.php

@@ -37,12 +37,14 @@ $intro_cmdEdit = empty($_GET['intro_cmdEdit']) ? '' : $_GET['intro_cmdEdit'];
 $intro_cmdUpdate = isset($_POST['intro_cmdUpdate']);
 $intro_cmdDel = empty($_GET['intro_cmdDel']) ? '' : $_GET['intro_cmdDel'];
 $intro_cmdAdd = empty($_GET['intro_cmdAdd']) ? '' : $_GET['intro_cmdAdd'];
+$courseId = api_get_course_id();
 
-if (!empty ($GLOBALS['_cid'])) {
-	$form = new FormValidator('introduction_text', 'post', api_get_self().'?'.api_get_cidreq());
+if (!empty($courseId)) {
+    $form = new FormValidator('introduction_text', 'post', api_get_self().'?'.api_get_cidreq());
 } else {
-	$form = new FormValidator('introduction_text');
+    $form = new FormValidator('introduction_text');
 }
+
 $renderer =& $form->defaultRenderer();
 $renderer->setElementTemplate('<div style="width: 80%; margin: 0px auto; padding-bottom: 10px; ">{element}</div>');
 
@@ -53,29 +55,29 @@ $height = '300';
 // The global variable $fck_attribute has been deprecated. It stays here for supporting old external code.
 global $fck_attribute;
 if (is_array($fck_attribute)) {
-	if (isset($fck_attribute['ToolbarSet'])) {
-		$toolbar_set = $fck_attribute['ToolbarSet'];
-	}
-	if (isset($fck_attribute['Width'])) {
-		$toolbar_set = $fck_attribute['Width'];
-	}
-	if (isset($fck_attribute['Height'])) {
-		$toolbar_set = $fck_attribute['Height'];
-	}
+    if (isset($fck_attribute['ToolbarSet'])) {
+        $toolbar_set = $fck_attribute['ToolbarSet'];
+    }
+    if (isset($fck_attribute['Width'])) {
+        $toolbar_set = $fck_attribute['Width'];
+    }
+    if (isset($fck_attribute['Height'])) {
+        $toolbar_set = $fck_attribute['Height'];
+    }
 }
 
 if (is_array($editor_config)) {
-	if (!isset($editor_config['ToolbarSet'])) {
-		$editor_config['ToolbarSet'] = $toolbar_set;
-	}
-	if (!isset($editor_config['Width'])) {
-		$editor_config['Width'] = $width;
-	}
-	if (!isset($editor_config['Height'])) {
-		$editor_config['Height'] = $height;
-	}
+    if (!isset($editor_config['ToolbarSet'])) {
+        $editor_config['ToolbarSet'] = $toolbar_set;
+    }
+    if (!isset($editor_config['Width'])) {
+        $editor_config['Width'] = $width;
+    }
+    if (!isset($editor_config['Height'])) {
+        $editor_config['Height'] = $height;
+    }
 } else {
-	$editor_config = array('ToolbarSet' => $toolbar_set, 'Width' => $width, 'Height' => $height);
+    $editor_config = array('ToolbarSet' => $toolbar_set, 'Width' => $width, 'Height' => $height);
 }
 
 $form->add_html_editor('intro_content', null, null, false, $editor_config);
@@ -85,45 +87,61 @@ $form->addElement('style_submit_button', 'intro_cmdUpdate', get_lang('SaveIntroT
 $course_id = api_get_course_int_id();
 
 if ($intro_editAllowed) {
-	$moduleId = Database::escape_string($moduleId);
-	
-	/* Replace command */
-	if ($intro_cmdUpdate) {
-		if ($form->validate()) {
-			$form_values = $form->exportValues();
-			$intro_content = Security::remove_XSS(stripslashes(api_html_entity_decode($form_values['intro_content'])), COURSEMANAGERLOWSECURITY);			
-			if (!empty($intro_content)) {
-				$sql = "REPLACE $TBL_INTRODUCTION SET c_id = $course_id, id='$moduleId',intro_text='".Database::escape_string($intro_content)."', session_id='".intval($session_id)."'";				
-				Database::query($sql);
-				$introduction_section .= Display::return_message(get_lang('IntroductionTextUpdated'),'confirmation', false);
-			} else {
-				$intro_cmdDel = true;	// got to the delete command
-			}
-		} else {
-			$intro_cmdEdit = true;
-		}
-	}
+    $moduleId = Database::escape_string($moduleId);
 
-	/* Delete Command */
-	if ($intro_cmdDel) {
-		Database::query("DELETE FROM $TBL_INTRODUCTION WHERE c_id = $course_id AND id='".$moduleId."' AND session_id='".intval($session_id)."'");
-		$introduction_section .= Display::return_message(get_lang('IntroductionTextDeleted'), 'confirmation');
-	}
+    /* Replace command */
+    if ($intro_cmdUpdate) {
+        if ($form->validate()) {
+            $form_values = $form->exportValues();
+            $intro_content = Security::remove_XSS(stripslashes(api_html_entity_decode($form_values['intro_content'])), COURSEMANAGERLOWSECURITY);
+            if (!empty($intro_content)) {
+                $sql = "REPLACE $TBL_INTRODUCTION SET c_id = $course_id, id='$moduleId',intro_text='".Database::escape_string($intro_content)."', session_id='".intval($session_id)."'";
+                Database::query($sql);
+                $introduction_section .= Display::return_message(get_lang('IntroductionTextUpdated'),'confirmation', false);
+            } else {
+                $intro_cmdDel = true;	// got to the delete command
+            }
+        } else {
+            $intro_cmdEdit = true;
+        }
+    }
+
+    /* Delete Command */
+    if ($intro_cmdDel) {
+        Database::query("DELETE FROM $TBL_INTRODUCTION WHERE c_id = $course_id AND id='".$moduleId."' AND session_id='".intval($session_id)."'");
+        $introduction_section .= Display::return_message(get_lang('IntroductionTextDeleted'), 'confirmation');
+    }
 }
 
 
 /*	INTRODUCTION MICRO MODULE - DISPLAY SECTION */
 
 /* Retrieves the module introduction text, if exist */
-
-$sql = "SELECT intro_text FROM $TBL_INTRODUCTION 
-        WHERE c_id = $course_id AND id='".Database::escape_string($moduleId)."' AND session_id = '".intval($session_id)."'";
+/* @todo use a lib to query the $TBL_INTRODUCTION table */
+// Getting course intro
+$intro_content = null;
+$sql = "SELECT intro_text FROM $TBL_INTRODUCTION
+        WHERE c_id = $course_id AND id='".Database::escape_string($moduleId)."' AND session_id = 0";
 $intro_dbQuery = Database::query($sql);
 if (Database::num_rows($intro_dbQuery) > 0) {
-	$intro_dbResult = Database::fetch_array($intro_dbQuery);    
-	$intro_content = $intro_dbResult['intro_text'];	
-} else {
-	$intro_content = '';
+    $intro_dbResult = Database::fetch_array($intro_dbQuery);
+    $intro_content = $intro_dbResult['intro_text'];
+}
+
+// Getting session intro
+if (!empty($session_id)) {
+    $sql = "SELECT intro_text FROM $TBL_INTRODUCTION
+        WHERE c_id = $course_id AND id='".Database::escape_string($moduleId)."' AND session_id = '".intval($session_id)."'";
+    $intro_dbQuery = Database::query($sql);
+    $introSessionContent = null;
+    if (Database::num_rows($intro_dbQuery) > 0) {
+        $intro_dbResult = Database::fetch_array($intro_dbQuery);
+        $introSessionContent = $intro_dbResult['intro_text'];
+    }
+    // If the course session intro exists replace it.
+    if (!empty($introSessionContent)) {
+        $intro_content = $introSessionContent;
+    }
 }
 
 /* Determines the correct display */
@@ -176,41 +194,41 @@ if ($tool == TOOL_COURSE_HOMEPAGE && !isset($_GET['intro_cmdEdit'])) {
 	}
 
 	if (!empty($thematic_advance_info)) {
-		
-		$thematic_advance = get_lang('CourseThematicAdvance').'&nbsp;'.$thematic->get_total_average_of_thematic_advances().'%';		
+
+		$thematic_advance = get_lang('CourseThematicAdvance').'&nbsp;'.$thematic->get_total_average_of_thematic_advances().'%';
 		if (api_is_allowed_to_edit(null, true)) {
 			//$thematic_advance = '<a href="'.api_get_path(WEB_CODE_PATH).'course_progress/index.php?action=thematic_details&'.api_get_cidreq().'">'.get_lang('CourseThematicAdvance').'&nbsp;'.$thematic->get_total_average_of_thematic_advances().'%</a>';
-		}		
+		}
 		$thematic_info = $thematic->get_thematic_list($thematic_advance_info['thematic_id']);
-		
+
 		$thematic_advance_info['start_date'] = api_get_local_time($thematic_advance_info['start_date']);
 		$thematic_advance_info['start_date'] = api_format_date($thematic_advance_info['start_date'], DATE_TIME_FORMAT_LONG);
-		
+
 		$thematic_description_html = '<div class="thematic-postit">
-								  	  <div class="thematic-postit-top"><h3><a class="thematic-postit-head" style="" href="#"> '.$thematic_advance.'</h3></a></div>						 
+								  	  <div class="thematic-postit-top"><h3><a class="thematic-postit-head" style="" href="#"> '.$thematic_advance.'</h3></a></div>
 								  	  <div class="thematic-postit-center" style="display:none">';
-		$thematic_description_html .= '<div><strong>'.$thematic_info['title'].'</strong></div>';			
+		$thematic_description_html .= '<div><strong>'.$thematic_info['title'].'</strong></div>';
 		$thematic_description_html .= '<div style="font-size:8pt;"><strong>'.$thematic_advance_info['start_date'].'</strong></div>';
 		$thematic_description_html .= '<div>'.$thematic_advance_info['content'].'</div>';
 		$thematic_description_html .= '<div>'.get_lang('DurationInHours').' : '.$thematic_advance_info['duration'].'</div>';
-		
-        
+
+
 		if (!empty($thematic_advance_info2)){
 			$thematic_info2 = $thematic->get_thematic_list($thematic_advance_info2['thematic_id']);
-		
+
 			$thematic_advance_info2['start_date'] = api_get_local_time($thematic_advance_info2['start_date']);
 			$thematic_advance_info2['start_date'] = api_format_date($thematic_advance_info2['start_date'], DATE_TIME_FORMAT_LONG);
-														  								
-			$thematic_description_html .= '<div><strong>'.$thematic_info2['title'].'</strong></div>';			
+
+			$thematic_description_html .= '<div><strong>'.$thematic_info2['title'].'</strong></div>';
 			$thematic_description_html .= '<div style="font-size:8pt;"><strong>'.$thematic_advance_info2['start_date'].'</strong></div>';
 			$thematic_description_html .= '<div>'.$thematic_advance_info2['content'].'</div>';
 			$thematic_description_html .= '<div>'.get_lang('DurationInHours').' : '.$thematic_advance_info2['duration'].'</div>';
-			$thematic_description_html .= '<br />';								  	
-		}								  	
+			$thematic_description_html .= '<br />';
+		}
 		$thematic_description_html .= '</div>
 								  <div class="thematic-postit-bottom"></div>
 								  </div>';
-	} 
+	}
 }
 
 $introduction_section .= '<div class="row"><div class="span12">';
@@ -218,7 +236,7 @@ $introduction_section .=  $thematic_description_html;
 $introduction_section .=  '</div>';
 
 $introduction_section .=  '<div class="span12">';
-if ($intro_dispDefault) {	
+if ($intro_dispDefault) {
 	$intro_content = $intro_content;
 	if (!empty($intro_content))	{
 		$introduction_section .=  $intro_content;
@@ -226,13 +244,13 @@ if ($intro_dispDefault) {
 }
 $introduction_section .=  '</div>';
 
-if ($intro_dispCommand) {    
+if ($intro_dispCommand) {
 	if (empty($intro_content)) {
 		// Displays "Add intro" commands
 		$introduction_section .=  '<div id="courseintro_empty">';
-		if (!empty ($GLOBALS['_cid'])) {			
-			$introduction_section .=  "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;intro_cmdAdd=1\">";            
-            $introduction_section .=  Display::return_icon('introduction_add.gif', get_lang('AddIntro')).' ';            		
+		if (!empty ($GLOBALS['_cid'])) {
+			$introduction_section .=  "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;intro_cmdAdd=1\">";
+            $introduction_section .=  Display::return_icon('introduction_add.gif', get_lang('AddIntro')).' ';
 			$introduction_section .=  "</a>";
 		} else {
 			$introduction_section .= "<a href=\"".api_get_self()."?intro_cmdAdd=1\">\n".get_lang('AddIntro')."</a>";
@@ -243,10 +261,10 @@ if ($intro_dispCommand) {
 		// Displays "edit intro && delete intro" commands
 		$introduction_section .=  '<div id="courseintro_empty">';
 		if (!empty ($GLOBALS['_cid'])) {
-			$introduction_section .=  "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;intro_cmdEdit=1\">".Display::return_icon('edit.png',get_lang('Modify'),'',ICON_SIZE_SMALL)."</a>";			
+			$introduction_section .=  "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;intro_cmdEdit=1\">".Display::return_icon('edit.png',get_lang('Modify'),'',ICON_SIZE_SMALL)."</a>";
 			$introduction_section .=  "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;intro_cmdDel=1\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,$charset))."')) return false;\">".Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL)."</a>";
 		} else {
-			$introduction_section .=  "<a href=\"".api_get_self()."?intro_cmdEdit=1\">".Display::return_icon('edit.png',get_lang('Modify'),'',ICON_SIZE_SMALL)."</a>";			
+			$introduction_section .=  "<a href=\"".api_get_self()."?intro_cmdEdit=1\">".Display::return_icon('edit.png',get_lang('Modify'),'',ICON_SIZE_SMALL)."</a>";
 			$introduction_section .=  "<a href=\"".api_get_self()."?intro_cmdDel=1\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,$charset))."')) return false;\">".Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL)."</a>";
 		}
 		$introduction_section .=  "</div>";

+ 205 - 205
main/inc/lib/classmanager.lib.php

@@ -1,227 +1,227 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-* This is the class library for this application.
-* @package	 chamilo.library
+* This is the static class library for this application.
+* @package     chamilo.library
 */
 /**
  * Code
  */
 class ClassManager
 {
-	/**
-	 * Get class information
-	 * note: This function can't be named get_class() because that's a standard
-	 * php-function.
-	 */
-	function get_class_info($class_id) {
+    /**
+     * Get class information
+     * note: This function can't be named get_class() because that's a standard
+     * php-function.
+     */
+    public static function get_class_info($class_id) {
         $class_id = intval($class_id);        
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$sql = "SELECT * FROM $table_class WHERE id='".$class_id."'";
-		$res = Database::query($sql);
-		return Database::fetch_array($res, 'ASSOC');
-	}
-	/**
-	 * Change the name of a class
-	 * @param string $name The new name
-	 * @param int $class_id The class id
-	 */
-	function set_name($name, $class_id) {
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $sql = "SELECT * FROM $table_class WHERE id='".$class_id."'";
+        $res = Database::query($sql);
+        return Database::fetch_array($res, 'ASSOC');
+    }
+    /**
+     * Change the name of a class
+     * @param string $name The new name
+     * @param int $class_id The class id
+     */
+    public static function set_name($name, $class_id) {
         $class_id = intval($class_id);        
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$sql = "UPDATE $table_class SET name='".Database::escape_string($name)."' WHERE id='".$class_id."'";
-		$res = Database::query($sql);
-	}
-	/**
-	 * Create a class
-	 * @param string $name
-	 */
-	function create_class($name) {
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$sql = "INSERT INTO $table_class SET name='".Database::escape_string($name)."'";
-		Database::query($sql);
-		return Database::affected_rows() == 1;
-	}
-	/**
-	 * Check if a classname is allready in use
-	 * @param string $name
-	 */
-	function class_name_exists($name) {
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$sql = "SELECT * FROM $table_class WHERE name='".Database::escape_string($name)."'";
-		$res = Database::query($sql);
-		return Database::num_rows($res) != 0;
-	}
-	/**
-	 * Delete a class
-	 * @param int $class_id
-	 * @todo Add option to unsubscribe class-members from the courses where the
-	 * class was subscibed to
-	 */
-	function delete_class($class_id) {
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $sql = "UPDATE $table_class SET name='".Database::escape_string($name)."' WHERE id='".$class_id."'";
+        $res = Database::query($sql);
+    }
+    /**
+     * Create a class
+     * @param string $name
+     */
+    public static function create_class($name) {
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $sql = "INSERT INTO $table_class SET name='".Database::escape_string($name)."'";
+        Database::query($sql);
+        return Database::affected_rows() == 1;
+    }
+    /**
+     * Check if a classname is allready in use
+     * @param string $name
+     */
+    public static function class_name_exists($name) {
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $sql = "SELECT * FROM $table_class WHERE name='".Database::escape_string($name)."'";
+        $res = Database::query($sql);
+        return Database::num_rows($res) != 0;
+    }
+    /**
+     * Delete a class
+     * @param int $class_id
+     * @todo Add option to unsubscribe class-members from the courses where the
+     * class was subscibed to
+     */
+    public static function delete_class($class_id) {
         $class_id = intval($class_id);        
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$table_class_course = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-		$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-		$sql = "DELETE FROM $table_class_user WHERE class_id = '".$class_id."'";
-		Database::query($sql);
-		$sql = "DELETE FROM $table_class_course WHERE class_id = '".$class_id."'";
-		Database::query($sql);
-		$sql = "DELETE FROM $table_class WHERE id = '".$class_id."'";
-		Database::query($sql);
-	}
-	/**
-	 * Get all users from a class
-	 * @param int $class_id
-	 * @return array
-	 */
-	function get_users($class_id) {        
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $table_class_course = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
+        $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+        $sql = "DELETE FROM $table_class_user WHERE class_id = '".$class_id."'";
+        Database::query($sql);
+        $sql = "DELETE FROM $table_class_course WHERE class_id = '".$class_id."'";
+        Database::query($sql);
+        $sql = "DELETE FROM $table_class WHERE id = '".$class_id."'";
+        Database::query($sql);
+    }
+    /**
+     * Get all users from a class
+     * @param int $class_id
+     * @return array
+     */
+    public static function get_users($class_id) {
         $class_id = intval($class_id);        
-		$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-		$table_user = Database :: get_main_table(TABLE_MAIN_USER);
-		$sql = "SELECT * FROM $table_class_user cu, $table_user u WHERE cu.class_id = '".$class_id."' AND cu.user_id = u.user_id";
-		$res = Database::query($sql);
-		$users = array ();
-		while ($user = Database::fetch_array($res, 'ASSOC')) {
-			$users[] = $user;
-		}
-		return $users;
-	}
-	/**
-	 * Add a user to a class. If the class is subscribed to a course, the new
-	 * user will also be subscribed to that course.
-	 * @param int $user_id The user id
-	 * @param int $class_id The class id
-	 */
-	function add_user($user_id, $class_id) {
-		$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+        $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
+        $sql = "SELECT * FROM $table_class_user cu, $table_user u WHERE cu.class_id = '".$class_id."' AND cu.user_id = u.user_id";
+        $res = Database::query($sql);
+        $users = array ();
+        while ($user = Database::fetch_array($res, 'ASSOC')) {
+            $users[] = $user;
+        }
+        return $users;
+    }
+    /**
+     * Add a user to a class. If the class is subscribed to a course, the new
+     * user will also be subscribed to that course.
+     * @param int $user_id The user id
+     * @param int $class_id The class id
+     */
+    public static function add_user($user_id, $class_id) {
+        $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
         $user_id  = intval($user_id);
         $class_id = intval($class_id);
-		$sql = "INSERT IGNORE INTO $table_class_user SET user_id = '".$user_id."', class_id='".$class_id."'";
-		Database::query($sql);
-		$courses = ClassManager :: get_courses($class_id);
-		foreach ($courses as $index => $course) {
-			CourseManager :: subscribe_user($user_id, $course['course_code']);
-		}
-	}
-	/**
-	 * Unsubscribe a user from a class. If the class is also subscribed in a
-	 * course, the user will be unsubscribed from that course
-	 * @param int $user_id The user id
-	 * @param int $class_id The class id
-	 */
-	function unsubscribe_user($user_id, $class_id) {
+        $sql = "INSERT IGNORE INTO $table_class_user SET user_id = '".$user_id."', class_id='".$class_id."'";
+        Database::query($sql);
+        $courses = ClassManager :: get_courses($class_id);
+        foreach ($courses as $index => $course) {
+            CourseManager :: subscribe_user($user_id, $course['course_code']);
+        }
+    }
+    /**
+     * Unsubscribe a user from a class. If the class is also subscribed in a
+     * course, the user will be unsubscribed from that course
+     * @param int $user_id The user id
+     * @param int $class_id The class id
+     */
+    public static function unsubscribe_user($user_id, $class_id) {
         $class_id = intval($class_id);        
         $user_id  = intval($user_id);
         
-		$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-		$table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-		$courses = ClassManager :: get_courses($class_id);
-		if (count($courses) != 0) {
-			$course_codes = array ();
-			foreach ($courses as $index => $course) {
-				$course_codes[] = $course['course_code'];
-				$sql = "SELECT DISTINCT user_id FROM $table_class_user t1, $table_course_class t2 WHERE t1.class_id=t2.class_id AND course_code = '".$course['course_code']."' AND user_id = $user_id AND t2.class_id<>'$class_id'";
-				$res = Database::query($sql);
-				if (Database::num_rows($res) == 0 && CourseManager :: get_user_in_course_status($user_id, $course['course_code']) == STUDENT)
-				{
-					CourseManager :: unsubscribe_user($user_id, $course['course_code']);
-				}
-			}
-		}
-		$sql = "DELETE FROM $table_class_user WHERE user_id='".$user_id."' AND class_id = '".$class_id."'";
-		Database::query($sql);
-	}
-	/**
-	 * Get all courses in which a class is subscribed
-	 * @param int $class_id
-	 * @return array
-	 */
-	function get_courses($class_id) {
+        $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+        $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
+        $courses = ClassManager :: get_courses($class_id);
+        if (count($courses) != 0) {
+            $course_codes = array ();
+            foreach ($courses as $index => $course) {
+                $course_codes[] = $course['course_code'];
+                $sql = "SELECT DISTINCT user_id FROM $table_class_user t1, $table_course_class t2 WHERE t1.class_id=t2.class_id AND course_code = '".$course['course_code']."' AND user_id = $user_id AND t2.class_id<>'$class_id'";
+                $res = Database::query($sql);
+                if (Database::num_rows($res) == 0 && CourseManager :: get_user_in_course_status($user_id, $course['course_code']) == STUDENT)
+                {
+                    CourseManager :: unsubscribe_user($user_id, $course['course_code']);
+                }
+            }
+        }
+        $sql = "DELETE FROM $table_class_user WHERE user_id='".$user_id."' AND class_id = '".$class_id."'";
+        Database::query($sql);
+    }
+    /**
+     * Get all courses in which a class is subscribed
+     * @param int $class_id
+     * @return array
+     */
+    public static function get_courses($class_id) {
         $class_id = intval($class_id);       
-		$table_class_course = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-		$table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-		$sql = "SELECT * FROM $table_class_course cc, $table_course c WHERE cc.class_id = '".$class_id."' AND cc.course_code = c.code";
-		$res = Database::query($sql);
-		$courses = array ();
-		while ($course = Database::fetch_array($res, 'ASSOC')) {
-			$courses[] = $course;
-		}
-		return $courses;
-	}
-	/**
-	 * Subscribe all members of a class to a course
-	 * @param  int $class_id The class id
-	 * @param string $course_code The course code
-	 */
-	function subscribe_to_course($class_id, $course_code) {
-		$tbl_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-		$tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-		$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$sql = "INSERT IGNORE INTO $tbl_course_class SET course_code = '".Database::escape_string($course_code)."', class_id = '".Database::escape_string($class_id)."'";
-		Database::query($sql);
-		$sql = "SELECT user_id FROM $tbl_class_user WHERE class_id = '".Database::escape_string($class_id)."'";
-		$res = Database::query($sql);
-		while ($user = Database::fetch_object($res)) {
-			CourseManager :: subscribe_user($user->user_id, $course_code);
-		}
-	}
-	/**
-	 * Unsubscribe a class from a course.
-	 * Only students are unsubscribed. If a user is member of 2 classes which
-	 * are both subscribed to the course, the user stays in the course.
-	 * @param int $class_id The class id
-	 * @param string $course_code The course code
-	 */
-	function unsubscribe_from_course($class_id, $course_code)
-	{
-		$tbl_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-		$tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-		$sql = "SELECT cu.user_id,COUNT(cc.class_id) FROM $tbl_course_class cc, $tbl_class_user cu WHERE  cc.class_id = cu.class_id AND cc.course_code = '".Database::escape_string($course_code)."' GROUP BY cu.user_id HAVING COUNT(cc.class_id) = 1";
-		$single_class_users = Database::query($sql);
-		while ($single_class_user = Database::fetch_object($single_class_users))
-		{
-			$sql = "SELECT * FROM $tbl_class_user WHERE class_id = '".Database::escape_string($class_id)."' AND user_id = '".Database::escape_string($single_class_user->user_id)."'";
-			$res = Database::query($sql);
-			if (Database::num_rows($res) > 0)
-			{
-				if (CourseManager :: get_user_in_course_status($single_class_user->user_id, $course_code) == STUDENT)
-				{
-					CourseManager :: unsubscribe_user($single_class_user->user_id, $course_code);
-				}
-			}
-		}
-		$sql = "DELETE FROM $tbl_course_class WHERE course_code = '".Database::escape_string($course_code)."' AND class_id = '".Database::escape_string($class_id)."'";
-		Database::query($sql);
-	}
+        $table_class_course = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
+        $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $sql = "SELECT * FROM $table_class_course cc, $table_course c WHERE cc.class_id = '".$class_id."' AND cc.course_code = c.code";
+        $res = Database::query($sql);
+        $courses = array ();
+        while ($course = Database::fetch_array($res, 'ASSOC')) {
+            $courses[] = $course;
+        }
+        return $courses;
+    }
+    /**
+     * Subscribe all members of a class to a course
+     * @param  int $class_id The class id
+     * @param string $course_code The course code
+     */
+    public static function subscribe_to_course($class_id, $course_code) {
+        $tbl_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
+        $tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+        $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $sql = "INSERT IGNORE INTO $tbl_course_class SET course_code = '".Database::escape_string($course_code)."', class_id = '".Database::escape_string($class_id)."'";
+        Database::query($sql);
+        $sql = "SELECT user_id FROM $tbl_class_user WHERE class_id = '".Database::escape_string($class_id)."'";
+        $res = Database::query($sql);
+        while ($user = Database::fetch_object($res)) {
+            CourseManager :: subscribe_user($user->user_id, $course_code);
+        }
+    }
+    /**
+     * Unsubscribe a class from a course.
+     * Only students are unsubscribed. If a user is member of 2 classes which
+     * are both subscribed to the course, the user stays in the course.
+     * @param int $class_id The class id
+     * @param string $course_code The course code
+     */
+    public static function unsubscribe_from_course($class_id, $course_code)
+    {
+        $tbl_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
+        $tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+        $sql = "SELECT cu.user_id,COUNT(cc.class_id) FROM $tbl_course_class cc, $tbl_class_user cu WHERE  cc.class_id = cu.class_id AND cc.course_code = '".Database::escape_string($course_code)."' GROUP BY cu.user_id HAVING COUNT(cc.class_id) = 1";
+        $single_class_users = Database::query($sql);
+        while ($single_class_user = Database::fetch_object($single_class_users))
+        {
+            $sql = "SELECT * FROM $tbl_class_user WHERE class_id = '".Database::escape_string($class_id)."' AND user_id = '".Database::escape_string($single_class_user->user_id)."'";
+            $res = Database::query($sql);
+            if (Database::num_rows($res) > 0)
+            {
+                if (CourseManager :: get_user_in_course_status($single_class_user->user_id, $course_code) == STUDENT)
+                {
+                    CourseManager :: unsubscribe_user($single_class_user->user_id, $course_code);
+                }
+            }
+        }
+        $sql = "DELETE FROM $tbl_course_class WHERE course_code = '".Database::escape_string($course_code)."' AND class_id = '".Database::escape_string($class_id)."'";
+        Database::query($sql);
+    }
 
-	/**
-	 * Get the class-id
-	 * @param string $name The class name
-	 * @return int the ID of the class
-	 */
-	function get_class_id($name) {
+    /**
+     * Get the class-id
+     * @param string $name The class name
+     * @return int the ID of the class
+     */
+    public static function get_class_id($name) {
         $name = Database::escape_string($name);
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$sql = "SELECT * FROM $table_class WHERE name='".$name."'";
-		$res = Database::query($sql);
-		$obj = Database::fetch_object($res);
-		return $obj->id;
-	}
-	/**
-	 * Get all classes subscribed in a course
-	 * @param string $course_code
-	 * @return array An array with all classes (keys: 'id','code','name')
-	 */
-	function get_classes_in_course($course_code) {
-		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-		$table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-		$sql = "SELECT cl.* FROM $table_class cl, $table_course_class cc WHERE cc.course_code = '".Database::escape_string($course_code)."' AND cc.class_id = cl.id";
-		$res = Database::query($sql);
-		$classes = array ();
-		while ($class = Database::fetch_array($res, 'ASSOC')) {
-			$classes[] = $class;
-		}
-		return $classes;
-	}
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $sql = "SELECT * FROM $table_class WHERE name='".$name."'";
+        $res = Database::query($sql);
+        $obj = Database::fetch_object($res);
+        return $obj->id;
+    }
+    /**
+     * Get all classes subscribed in a course
+     * @param string $course_code
+     * @return array An array with all classes (keys: 'id','code','name')
+     */
+    public static function get_classes_in_course($course_code) {
+        $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+        $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
+        $sql = "SELECT cl.* FROM $table_class cl, $table_course_class cc WHERE cc.course_code = '".Database::escape_string($course_code)."' AND cc.class_id = cl.id";
+        $res = Database::query($sql);
+        $classes = array ();
+        while ($class = Database::fetch_array($res, 'ASSOC')) {
+            $classes[] = $class;
+        }
+        return $classes;
+    }
 }

+ 37 - 25
main/inc/lib/course.lib.php

@@ -1152,10 +1152,10 @@ class CourseManager
     /**
      * Return user info array of all users registered in the specified real or virtual course
      * This only returns the users that are registered in this actual course, not linked courses.
-     * @param null $course_code
+     * @param string $course_code
      * @param int $session_id
-     * @param null $limit
-     * @param null $order_by the field to order the users by.
+     * @param string $limit
+     * @param string $order_by the field to order the users by.
      * Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement
      * that starts with ORDER BY ...
      * @param null $filter_by_status if using the session_id: 0 or 2 (student, coach),
@@ -1163,9 +1163,10 @@ class CourseManager
      * @param null $return_count
      * @param bool $add_reports
      * @param bool $resumed_report
-     * @param null $extra_field
+     * @param array $extra_field
      * @param array $courseCodeList
-     * @param array $userList
+     * @param array $userIdList
+     * @param string $filterByActive
      * @return array|int
      */
     public static function get_user_list_from_course_code(
@@ -1177,9 +1178,10 @@ class CourseManager
         $return_count = null,
         $add_reports = false,
         $resumed_report = false,
-        $extra_field = null,
+        $extra_field = array(),
         $courseCodeList = array(),
-        $userIdList = array()
+        $userIdList = array(),
+        $filterByActive = null
     ) {
         // variable initialisation
         $session_id     = intval($session_id);
@@ -1252,8 +1254,11 @@ class CourseManager
         }
 
         if ($return_count && $resumed_report) {
-            $extra_field_info = UserManager::get_extra_field_information_by_name($extra_field);
-            $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES).' as ufv ON (user.user_id = ufv.user_id AND (field_id = '.$extra_field_info['id'].' OR field_id IS NULL ) )';
+            foreach ($extra_field as $extraField) {
+                $extraFieldInfo = UserManager::get_extra_field_information_by_name($extraField);
+                $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES).' as ufv
+                          ON (user.user_id = ufv.user_id AND (field_id = '.$extraFieldInfo['id'].' OR field_id IS NULL ) )';
+            }
         }
 
         $sql .= ' WHERE '.$filter_by_status_condition.' '.implode(' OR ', $where);
@@ -1279,16 +1284,18 @@ class CourseManager
             $sql .= ' AND user.user_id IN ("'.$userIdList.'")';
         }
 
-        //$userList = array()
+        if (isset($filterByActive)) {
+            $filterByActive = intval($filterByActive);
+            $sql .= ' AND user.active = '.$filterByActive;
+        }
 
         $sql .= ' '.$order_by.' '.$limit;
 
         $rs = Database::query($sql);
         $users = array();
 
-        if ($add_reports) {
-            $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
-        }
+        $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
+
         $counter = 1;
         $count_rows = Database::num_rows($rs);
 
@@ -1322,7 +1329,7 @@ class CourseManager
                     $course_code = $user['code'];
                     if ($resumed_report) {
                         foreach ($extra_fields as $extra) {
-                            if ($extra['1'] == $extra_field) {
+                            if (in_array($extra['1'], $extra_field)) {
                                 $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
                                 break;
                             }
@@ -1362,6 +1369,20 @@ class CourseManager
                         if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
                             $users[$row_key]['count_certificates']++;
                         }
+
+                        foreach ($extra_fields as $extra) {
+                            if ($extra['1'] == 'ruc') {
+                                continue;
+                            }
+
+                            if (!isset($users[$row_key][$extra['1']])) {
+                                $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
+                                if (!empty($user_data[$extra['1']])) {
+                                    $users[$row_key][$extra['1']] = $user_data[$extra['1']];
+                                }
+                            }
+                        }
+
                     } else {
                         $report_info['course'] = $user['title'];
                         $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']);
@@ -1373,8 +1394,6 @@ class CourseManager
                             $report_info['certificate'] = Display::label(get_lang('Yes'), 'success');
                         }
 
-                        //$report_info['score'] = Tracking::get_avg_student_score($user['user_id'], $course_code, array(), 0);
-
                         $progress = intval(Tracking::get_avg_student_progress($user['user_id'], $course_code, array(), 0));
                         $report_info['progress_100'] =  $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No'));
                         $report_info['progress'] = $progress."%";
@@ -1389,27 +1408,20 @@ class CourseManager
                     $users[$user['user_id']] = $user_info;
                 }
             }
-            $counter++;
-        }
-
-        if ($add_reports) {
-            if ($resumed_report) {
-                //var_dump($counter);
-            }
         }
         return $users;
     }
 
     /**
      * @param bool $resumed_report
-     * @param string $extra_field
+     * @param array $extra_field
      * @param array $courseCodeList
      * @param array $userIdList
      * @return array|int
      */
     static function get_count_user_list_from_course_code(
         $resumed_report = false,
-        $extra_field = null,
+        $extra_field = array(),
         $courseCodeList = array(),
         $userIdList = array()
     ) {

+ 177 - 102
main/inc/lib/database.mysqli.lib.php

@@ -4,7 +4,7 @@
  *	This is a special version of the main database library for Chamilo focused
  *  on using the MySQLi driver instead of the MySQL driver.
  * To use it, make a backup copy of your database.lib.php file and replace
- * database.lib.php by this file.
+ * database.lib.php by this file, then rename MySQLIDatabase into Database.
  *	Include/require it in your code to use its functionality.
  *   Because this library contains all the basic database calls, it could be
  *   replaced by another library for say, PostgreSQL, to actually use Chamilo
@@ -24,7 +24,7 @@ require_once 'database.constants.inc.php';
  *      The class and its methods
  *	@package chamilo.library
  */
-class Database {
+class MySQLIDatabase {
     
     /* Variable use only in the installation process to log errors. See the Database::query function */
     static $log_queries = false;
@@ -38,7 +38,8 @@ class Database {
     /**
      *	Returns the name of the main database.
      */
-    public static function get_main_database() {
+    public static function get_main_database()
+    {
         global $_configuration;
         return $_configuration['main_database'];
     }
@@ -46,7 +47,8 @@ class Database {
     /**
      *	Returns the name of the statistics database.
      */
-    public static function get_statistic_database() {
+    public static function get_statistic_database()
+    {
         global $_configuration;
         return $_configuration['statistics_database'];
     }
@@ -55,7 +57,8 @@ class Database {
      *	Returns the name of the SCORM database.
      *	@deprecated
      */
-    public static function get_scorm_database() {
+    public static function get_scorm_database()
+    {
         global $_configuration;
         return $_configuration['scorm_database'];
     }
@@ -63,7 +66,8 @@ class Database {
     /**
      *	Returns the name of the database where all the personal stuff of the user is stored
      */
-    public static function get_user_personal_database() {
+    public static function get_user_personal_database()
+    {
         global $_configuration;
         return $_configuration['user_personal_database'];
     }
@@ -72,7 +76,8 @@ class Database {
      *	Returns the name of the current course database.
      *  @return    mixed   Glued database name of false if undefined
      */
-    public static function get_current_course_database() {
+    public static function get_current_course_database()
+    {
         $course_info = api_get_course_info();
         if (empty($course_info['dbName'])) {
             return false;
@@ -84,7 +89,8 @@ class Database {
      *	Returns the glued name of the current course database.
      *  @return    mixed   Glued database name of false if undefined
      */
-    public static function get_current_course_glued_database() {
+    public static function get_current_course_glued_database()
+    {
         $course_info = api_get_course_info();
         if (empty($course_info['dbNameGlu'])) {
             return false;
@@ -99,7 +105,8 @@ class Database {
      *	there are multiple databases and the code can be written independent
      *	of the single / multiple database setting.
      */
-    public static function get_database_glue() {
+    public static function get_database_glue()
+    {
         global $_configuration;
         return $_configuration['db_glue'];
     }
@@ -111,7 +118,8 @@ class Database {
      *	TIP: This can be convenient e.g. if you have multiple system installations
      *	on the same physical server.
      */
-    public static function get_database_name_prefix() {
+    public static function get_database_name_prefix()
+    {
         global $_configuration;
         return $_configuration['db_prefix'];
     }
@@ -122,7 +130,8 @@ class Database {
      *	Do research.
      *	It's used in local.inc.php.
      */
-    public static function get_course_table_prefix() {
+    public static function get_course_table_prefix()
+    {
         global $_configuration;
         return $_configuration['table_prefix'];
     }
@@ -151,8 +160,10 @@ class Database {
      * instead of directly using magic words in your tool code.
      *
      * @param string $short_table_name, the name of the table
+     * @return string The full name of the requested table from the main DB
      */
-    public static function get_main_table($short_table_name) {
+    public static function get_main_table($short_table_name)
+    {
         return self::format_table_name(self::get_main_database(), $short_table_name);
     }
 
@@ -167,7 +178,8 @@ class Database {
      * @param string $database_name, optional, name of the course database
      * - if you don't specify this, you work on the current course.
      */
-    public static function get_course_table($short_table_name, $database_name = '') {
+    public static function get_course_table($short_table_name, $database_name = '')
+    {
         return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
     }
 
@@ -178,8 +190,10 @@ class Database {
      * instead of directly using magic words in your tool code.
      *
      * @param string $short_table_name, the name of the table
+     * @return string The full name of the requested stats table
      */
-    public static function get_statistic_table($short_table_name) {
+    public static function get_statistic_table($short_table_name)
+    {
         return self::format_table_name(self::get_statistic_database(), $short_table_name);
     }
 
@@ -191,11 +205,13 @@ class Database {
      *
      * @param string $short_table_name, the name of the table
      */
-    public static function get_user_personal_table($short_table_name) {
+    public static function get_user_personal_table($short_table_name)
+    {
         return self::format_table_name(self::get_user_personal_database(), $short_table_name);
     }
 
-    public static function get_course_chat_connected_table($database_name = '') {
+    public static function get_course_chat_connected_table($database_name = '')
+    {
         return self::format_glued_course_table_name(self::fix_database_parameter($database_name), TABLE_CHAT_CONNECTED);
     }
 
@@ -205,25 +221,30 @@ class Database {
     */
 
     /**
-     *	@return a list (array) of all courses.
-     * 	@todo shouldn't this be in the course.lib.php script?
+     * Returns a full list of the contents of the course table as a PHP table
+     * @return a list (array) of all courses.
+     * @todo shouldn't this be in the course.lib.php script?
      */
-    public static function get_course_list() {
+    public static function get_course_list()
+    {
         $table = self::get_main_table(TABLE_MAIN_COURSE);
         return self::store_result(self::query("SELECT * FROM $table"));
     }
 
     /**
-     *	Returns an array with all database fields for the specified course.
+     * Returns an array with all database fields for the specified course.
      *
-     *	@param the real (system) code of the course (ID from inside the main course table)
-     * 	@todo shouldn't this be in the course.lib.php script?
+     * @param string $course_code The real (system) code of the course (ID from inside the main course table)
+     * @return array Course info from the course table
+     * @todo shouldn't this be in the course.lib.php script?
      */
-    public static function get_course_info($course_code) {
+    public static function get_course_info($course_code)
+    {
         $course_code = self::escape_string($course_code);
         $table = self::get_main_table(TABLE_MAIN_COURSE);
         $result = self::generate_abstract_course_field_names(
-            self::fetch_array(self::query("SELECT * FROM $table WHERE `code` = '$course_code'")));
+            self::fetch_array(self::query("SELECT * FROM $table WHERE code = '$course_code'"))
+        );
         return $result === false ? array('db_name' => '') : $result;
     }
 
@@ -236,7 +257,8 @@ class Database {
      *	@desc find all the information about a specified user. Without parameter this is the current user.
      * 	@todo shouldn't this be in the user.lib.php script?
      */
-    public static function get_user_info_from_id($user_id = '') {
+    public static function get_user_info_from_id($user_id = '')
+    {
         if (empty($user_id)) {
             return $GLOBALS['_user'];
         }
@@ -252,7 +274,8 @@ class Database {
      * @return string  Course code
      * @todo move this function in a gradebook-related library
      */
-    public static function get_course_by_category($category_id) {
+    public static function get_course_by_category($category_id)
+    {
         $category_id = intval($category_id);
         $info = self::fetch_array(self::query('SELECT course_code FROM '.self::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id), 'ASSOC');
         return $info ? $info['course_code'] : false;
@@ -272,7 +295,8 @@ class Database {
      * 		  There should be consistency in the variable names and the use throughout the scripts
      * 		  for the database name we should consistently use or db_name or database (db_name probably being the better one)
      */
-    public static function generate_abstract_course_field_names($result_array) {
+    public static function generate_abstract_course_field_names($result_array)
+    {
         $visual_code = isset($result_array['visual_code']) ? $result_array['visual_code'] : null;
         $code        = isset($result_array['code']) ? $result_array['code'] : null;
         $title       = isset($result_array['title']) ? $result_array['title'] : null;
@@ -323,7 +347,8 @@ class Database {
      * 	@todo what's the use of this function. I think this is better removed.
      * 		There should be consistency in the variable names and the use throughout the scripts
      */
-    public static function generate_abstract_user_field_names($result_array) {
+    public static function generate_abstract_user_field_names($result_array)
+    {
         $result_array['firstName'] 		= $result_array['firstname'];
         $result_array['lastName'] 		= $result_array['lastname'];
         $result_array['mail'] 			= $result_array['email'];
@@ -337,7 +362,8 @@ class Database {
      * @param string $table The table of which the rows should be counted
      * @return int The number of rows in the given table.
      */
-    public static function count_rows($table) {
+    public static function count_rows($table)
+    {
         $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));
         return $obj->n;
     }
@@ -348,10 +374,11 @@ class Database {
 
     /**
      * Returns the number of affected rows in the last database operation.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int								Returns the number of affected rows on success, and -1 if the last query failed.
+     * @param resource $connection The database server connection, for detailed description see the method query().
+     * @return int Returns the number of affected rows on success, and -1 if the last query failed.
      */
-    public static function affected_rows($connection = null) {
+    public static function affected_rows($connection = null)
+    {
         global $database_connection;
         return $database_connection->affected_rows;
     }
@@ -361,7 +388,8 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return bool								Returns TRUE on success or FALSE on failure.
      */
-    public static function close($connection = null) {
+    public static function close($connection = null)
+    {
         return self::use_default_connection($connection) ? mysqli::close() : mysqli::close($connection);
     }
 
@@ -376,7 +404,8 @@ class Database {
      * @link http://php.net/manual/en/function.mysql-connect.php
      * @link http://php.net/manual/en/function.mysql-pconnect.php
      */
-    public static function connect($parameters = array()) {
+    public static function connect($parameters = array())
+    {
         global $database_connection;
         // A MySQL-specific implementation.
         if (!isset($parameters['server'])) {
@@ -407,7 +436,8 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return int								Returns the error number from the last database (operation, or 0 (zero) if no error occurred.
      */
-    public static function errno($connection = null) {
+    public static function errno($connection = null)
+    {
         return self::use_default_connection($connection) ? mysqli::mysqli_errno() : mysqli::mysqli_errno($connection);
     }
 
@@ -416,7 +446,8 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return string							Returns the error text from the last database operation, or '' (empty string) if no error occurred.
      */
-    public static function error($connection = null) {
+    public static function error($connection = null)
+    {
         return self::use_default_connection($connection) ? mysqli::mysqli_error() : mysqli::mysqli_error($connection);
     }
 
@@ -428,7 +459,8 @@ class Database {
      * @author Yannick Warnier <yannick.warnier@dokeos.com>
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
      */
-    public static function escape_string($string, $connection = null) {
+    public static function escape_string($string, $connection = null)
+    {
         global $database_connection;
         return get_magic_quotes_gpc()
             ? ( $database_connection->escape_string(stripslashes($string)))
@@ -442,7 +474,8 @@ class Database {
      * @return array		Array of results as returned by php
      * @author Yannick Warnier <yannick.warnier@beeznest.com>
      */
-    public static function fetch_array($result, $option = 'BOTH') {
+    public static function fetch_array($result, $option = 'BOTH')
+    {
         return ($option == 'ASSOC') ? $result->fetch_array(MYSQLI_ASSOC) : ($option == 'NUM' ? $result->fetch_array(MYSQLI_NUM) : $result->fetch_array());
     }
 
@@ -452,19 +485,21 @@ class Database {
      * @param resource $result	The result from a call to sql_query (e.g. Database::query).
      * @return array			Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
      */
-    public static function fetch_assoc($result) {
+    public static function fetch_assoc($result)
+    {
         return $result->fetch_assoc();
     }
 
     /**
      * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form
-     * @param	resource	The result from a call to sql_query (e.g. Database::query)
-     * @param	string		Optional class name to instanciate
-     * @param	array		Optional array of parameters
-     * @return	object		Object of class StdClass or the required class, containing the query result row
-     * @author	Yannick Warnier <yannick.warnier@dokeos.com>
+     * @param mysqli $result The result from a call to sql_query (e.g. Database::query)
+     * @param string $class Optional class name to instantiate
+     * @param array $params Optional array of parameters
+     * @return resource Object of class StdClass or the required class, containing the query result row
+     * @author Yannick Warnier <yannick.warnier@dokeos.com>
      */
-    public static function fetch_object($result, $class = null, $params = null) {
+    public static function fetch_object($result, $class = null, $params = null)
+    {
         return !empty($class) ? (is_array($params) ? $result->fetch_object($class, $params) : $result->fetch_object($class)) : $result->fetch_object();
     }
 
@@ -473,7 +508,8 @@ class Database {
      * @param resource		The result from a call to sql_query (see Database::query()).
      * @return array		Array of results as returned by php (mysql_fetch_row)
      */
-    public static function fetch_row($result) {
+    public static function fetch_row($result)
+    {
         return $result->fetch_row();
     }
 
@@ -483,28 +519,33 @@ class Database {
      * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
      * Anyway, all associated result memory is automatically freed at the end of the script's execution.
      */
-    public static function free_result($result) {
+    public static function free_result($result)
+    {
         return $result->free_result();
     }
 
     /**
      * Returns the database client library version.
-     * @return strung		Returns a string that represents the client library version.
+     * @return string String that represents the client library version.
      */
-    public function get_client_info() {
+    public function get_client_info()
+    {
         return mysqli_get_client_info();
     }
 
     /**
      * Returns a list of databases created on the server. The list may contain all of the
      * available database names or filtered database names by using a pattern.
-     * @param string $pattern (optional)		A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of database names.
+     * @param string $pattern A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
+     * @param resource $connection The database server connection, for detailed description see the method query().
+     * @return array Returns in an array the retrieved list of database names.
      */
-    public static function get_databases($pattern = '', $connection = null) {
+    public static function get_databases($pattern = '', $connection = null)
+    {
         $result = array();
-        $query_result = Database::query(!empty($pattern) ? "SHOW DATABASES LIKE '".self::escape_string($pattern, $connection)."'" : "SHOW DATABASES", $connection);
+        $query_result = Database::query(!empty($pattern) ?
+                "SHOW DATABASES LIKE '".self::escape_string($pattern, $connection)."'" :
+                "SHOW DATABASES", $connection);
         while ($row = Database::fetch_row($query_result)) {
             $result[] = $row[0];
         }
@@ -515,14 +556,15 @@ class Database {
      * Returns a list of the fields that a given table contains. The list may contain all of the available field names or filtered field names by using a pattern.
      * By using a special option, this method is able to return an indexed list of fields' properties, where field names are keys.
      * @param string $table						This is the examined table.
-     * @param string $pattern (optional)		A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'.
-     * @param string $database (optional)		The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param bool $including_properties (optional)	When this option is true, the returned result has the followong format:
-     * 												array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...)
+     * @param string $pattern (optional)		A pattern for filtering field names as if it was needed for the SQL LIKE clause, for example 'column_%'.
+     * @param string $database (optional)		The name of the targeted database. If it is omitted, the current database is assumed, see Database::select_db().
+     * @param bool $including_properties (optional)	When this option is true, the returned result has the following format:
+     * 												array(field_name_1 => array(0 => property_1, 1 => property_2, ...), field_name_2 => array(0 => property_1, ...), ...)
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return array							Returns in an array the retrieved list of field names.
      */
-    public static function get_fields($table, $pattern = '', $database = '', $including_properties = false, $connection = null) {
+    public static function get_fields($table, $pattern = '', $database = '', $including_properties = false, $connection = null)
+    {
         $result = array();
         $query = "SHOW COLUMNS FROM `".self::escape_string($table, $connection)."`";
         if (!empty($database)) {
@@ -551,7 +593,8 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return string/boolean					Returns string data on success or FALSE on failure.
      */
-    public function get_host_info($connection = null) {
+    public function get_host_info($connection = null)
+    {
         return self::use_default_connection($connection) ? mysqli::mysqli_get_host_info() : mysqli::mysqli_get_host_info($connection);
     }
 
@@ -560,7 +603,8 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return int/boolean						Returns the protocol version on success or FALSE on failure.
      */
-    public function get_proto_info($connection = null) {
+    public function get_proto_info($connection = null)
+    {
         return self::use_default_connection($connection) ? mysqli::mysqli_get_proto_info() : mysqli::mysqli_get_proto_info($connection);
     }
 
@@ -569,19 +613,21 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return string/boolean					Returns the MySQL server version on success or FALSE on failure.
      */
-    public function get_server_info($connection = null) {
+    public function get_server_info($connection = null)
+    {
         return self::use_default_connection($connection) ? mysqli::mysqli_get_server_info() : mysqli::mysqli_get_server_info($connection);
     }
 
     /**
      * Returns a list of tables within a database. The list may contain all of the
      * available table names or filtered table names by using a pattern.
-     * @param string $database (optional)		The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param string $pattern (optional)		A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
+     * @param string $database (optional)		The name of the examined database. If it is omitted, the current database is assumed, see Database::select_db().
+     * @param string $pattern (optional)		A pattern for filtering table names as if it was needed for the SQL LIKE clause, for example 'access_%'.
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return array							Returns in an array the retrieved list of table names.
      */
-    public static function get_tables($database = '', $pattern = '', $connection = null) {
+    public static function get_tables($database = '', $pattern = '', $connection = null)
+    {
         $result = array();
         $query = "SHOW TABLES";
         if (!empty($database)) {
@@ -603,7 +649,8 @@ class Database {
      * @return int								The last ID as returned by the DB function
      * @comment This should be updated to use ADODB at some point
      */
-    public static function insert_id($connection = null) {
+    public static function insert_id($connection = null)
+    {
         global $database_connection;
         return $database_connection->insert_id;
     }
@@ -612,9 +659,10 @@ class Database {
      * Gets the number of rows from the last query result - help achieving database independence
      * @param resource		The result
      * @return integer		The number of rows contained in this result
-     * @author Yannick Warnier <yannick.warnier@dokeos.com>
+     * @author Yannick Warnier <yannick.warnier@beeznest.com>
      **/
-    public static function num_rows($result) {
+    public static function num_rows($result)
+    {
         return is_a($result,'mysqli_result') ? $result->num_rows : false;
     }
 
@@ -626,7 +674,8 @@ class Database {
      * @param	string		Optional field name or number
      * @result	mixed		One cell of the result, or FALSE on error
      */
-    public static function result(&$resource, $row, $field = '') {
+    public static function result(&$resource, $row, $field = '')
+    {
         if (self::num_rows($resource) > 0) {
             if (!empty($field)) {
                 $r = mysqli_data_seek($resource, $row);
@@ -647,8 +696,8 @@ class Database {
      * 											If it is not specified, the connection opened by mysql_connect() is assumed.
      * 											If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
      * 											If no connection is found or established, an E_WARNING level error is generated.
-     * @param string $file (optional)			On error it shows the file in which the error has been trigerred (use the "magic" constant __FILE__ as input parameter)
-     * @param string $line (optional)			On error it shows the line in which the error has been trigerred (use the "magic" constant __LINE__ as input parameter)
+     * @param string $file (optional)			On error it shows the file in which the error has been triggered (use the "magic" constant __FILE__ as input parameter)
+     * @param string $line (optional)			On error it shows the line in which the error has been triggered (use the "magic" constant __LINE__ as input parameter)
      * @return resource							The returned result from the query
      * Note: The parameter $connection could be skipped. Here are examples of this method usage:
      * Database::query($query);
@@ -661,7 +710,8 @@ class Database {
      * Database::query($query, $connection, __FILE__, __LINE__);
      * $result = Database::query($query, $connection, __FILE__, __LINE__);
      */
-    public static function query($query, $connection = null, $file = null, $line = null) {
+    public static function query($query, $connection = null, $file = null, $line = null)
+    {
         global $database_connection;
         
         $result = @$database_connection->query($query);
@@ -749,7 +799,8 @@ class Database {
      * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
      * @return bool								Returns TRUE on success or FALSE on failure.
      */
-    public static function select_db($database_name, $connection = null) {
+    public static function select_db($database_name, $connection = null)
+    {
         global $database_connection;
         $database_connection->select_db($database_name);
         return !$database_connection->errno;
@@ -764,7 +815,8 @@ class Database {
      * @param  option BOTH, ASSOC, or NUM
      * @return array - the value returned by the query
      */
-    public static function store_result($result, $option = 'BOTH') {
+    public static function store_result($result, $option = 'BOTH')
+    {
         $array = array();
         if ($result !== false) { // For isolation from database engine's behaviour.
             while ($row = self::fetch_array($result, $option)) {
@@ -784,7 +836,8 @@ class Database {
      * @return bool				Returns a boolean value as a check-result.
      * @author Ivan Tcholakov
      */
-    public static function is_encoding_supported($encoding) {
+    public static function is_encoding_supported($encoding)
+    {
         static $supported = array();
         if (!isset($supported[$encoding])) {
             $supported[$encoding] = false;
@@ -806,7 +859,8 @@ class Database {
      * @return string						Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
      * @author Ivan Tcholakov
      */
-    public static function make_charset_clause($encoding = null, $language = null) {
+    public static function make_charset_clause($encoding = null, $language = null)
+    {
         if (empty($encoding)) {
             $encoding = api_get_system_encoding();
         }
@@ -826,13 +880,14 @@ class Database {
     }
 
     /**
-     * Converts an encoding identificator to MySQL-specific encoding identifictor,
+     * Converts an encoding identificator to MySQL-specific encoding identifier,
      * i.e. 'UTF-8' --> 'utf8'.
-     * @param string $encoding	The conventional encoding identificator.
-     * @return string			Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
+     * @param string $encoding	The conventional encoding identifier.
+     * @return string			Returns the corresponding MySQL-specific encoding identifier if any, otherwise returns NULL.
      * @author Ivan Tcholakov
      */
-    public static function to_db_encoding($encoding) {
+    public static function to_db_encoding($encoding)
+    {
         static $result = array();
         if (!isset($result[$encoding])) {
             $result[$encoding] = null;
@@ -848,13 +903,14 @@ class Database {
     }
 
     /**
-     * Converts a MySQL-specific encoding identifictor to conventional encoding identificator,
+     * Converts a MySQL-specific encoding identifier to conventional encoding identifier,
      * i.e. 'utf8' --> 'UTF-8'.
-     * @param string $encoding	The MySQL-specific encoding identificator.
-     * @return string			Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
+     * @param string $encoding	The MySQL-specific encoding identifier.
+     * @return string			Returns the corresponding conventional encoding identifier if any, otherwise returns NULL.
      * @author Ivan Tcholakov
      */
-    public static function from_db_encoding($db_encoding) {
+    public static function from_db_encoding($db_encoding)
+    {
         static $result = array();
         if (!isset($result[$db_encoding])) {
             $result[$db_encoding] = null;
@@ -876,7 +932,8 @@ class Database {
      * @return string						Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
      * @author Ivan Tcholakov
      */
-    public static function to_db_collation($encoding, $language = null) {
+    public static function to_db_collation($encoding, $language = null)
+    {
         static $result = array();
         if (!isset($result[$encoding][$language])) {
             $result[$encoding][$language] = null;
@@ -913,7 +970,8 @@ class Database {
      *	Glues a course database.
      *	glue format from local.inc.php.
      */
-    private static function glue_course_database_name($database_name) {
+    private static function glue_course_database_name($database_name)
+    {
         return self::get_course_table_prefix().$database_name.self::get_database_glue();
     }
 
@@ -923,7 +981,8 @@ class Database {
      *	@return the glued parameter if it is not empty,
      *	or the current course database (glued) if the parameter is empty.
      */
-    private static function fix_database_parameter($database_name) {
+    private static function fix_database_parameter($database_name)
+    {
         if (empty($database_name)) {
             $course_info = api_get_course_info();
             return $course_info['dbNameGlu'];
@@ -936,7 +995,8 @@ class Database {
      *	for querying. The course database parameter is considered glued:
      *	e.g. COURSE001`.`
      */
-    private static function format_glued_course_table_name($database_name_with_glue, $table) {
+    private static function format_glued_course_table_name($database_name_with_glue, $table)
+    {
         return '`'.$database_name_with_glue.$table.'`';
     }
 
@@ -945,7 +1005,8 @@ class Database {
      *	for querying. The database parameter is considered not glued,
      *	just plain e.g. COURSE001
      */
-    private static function format_table_name($database, $table) {
+    private static function format_table_name($database, $table)
+    {
         return '`'.$database.'`.`'.$table.'`';
     }
 
@@ -958,7 +1019,8 @@ class Database {
      * @return boolean						TRUE means that calling method should use the default connection.
      * 										FALSE means that (valid) parameter $connection has been provided and it should be used.
      */
-    private static function use_default_connection($connection) {
+    private static function use_default_connection($connection)
+    {
         return !is_resource($connection) && $connection !== false;
     }
 
@@ -968,7 +1030,8 @@ class Database {
      * @param string	The input variable to be filtered from XSS, in this class it is expected to be a string.
      * @return string	Returns the filtered string as a result.
      */
-    private static function remove_XSS(& $var) {
+    private static function remove_XSS(& $var)
+    {
         return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars($var, ENT_QUOTES, api_get_system_encoding());
     }
 
@@ -977,7 +1040,8 @@ class Database {
      * conventional and MuSQL-specific encoding identificators.
      * @author Ivan Tcholakov
      */
-    private static function & get_db_encoding_map() {
+    private static function & get_db_encoding_map()
+    {
         static $encoding_map = array(
             'ARMSCII-8'    => 'armscii8',
             'BIG5'         => 'big5',
@@ -1013,7 +1077,8 @@ class Database {
      * A helper language id translation table for choosing some collations.
      * @author Ivan Tcholakov
      */
-    private static function & get_db_collation_map() {
+    private static function & get_db_collation_map()
+    {
         static $db_collation_map = array(
             'german' => 'german2',
             'simpl_chinese' => 'chinese',
@@ -1030,7 +1095,8 @@ class Database {
      * @return string				Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
      * @author Ivan Tcholakov
      */
-    private static function check_db_collation($db_encoding, $language) {
+    private static function check_db_collation($db_encoding, $language)
+    {
         if (empty($db_encoding)) {
             return null;
         }
@@ -1056,7 +1122,8 @@ class Database {
      * Experimental useful database insert
      * @todo lot of stuff to do here
      */
-    public static function insert($table_name, $attributes) {
+    public static function insert($table_name, $attributes)
+    {
         if (empty($attributes) || empty($table_name)) {
             return false;
         }
@@ -1079,7 +1146,8 @@ class Database {
      * @todo lot of stuff to do here
     */
 
-    public static function select($columns, $table_name,  $conditions = array(), $type_result = 'all', $option = 'ASSOC') {
+    public static function select($columns, $table_name,  $conditions = array(), $type_result = 'all', $option = 'ASSOC')
+    {
         $conditions = self::parse_conditions($conditions);
 
         //@todo we could do a describe here to check the columns ...
@@ -1119,7 +1187,8 @@ class Database {
      * @param   array
      * @todo lot of stuff to do here
     */
-    static function parse_conditions($conditions) {
+    static function parse_conditions($conditions)
+    {
         if (empty($conditions)) {
             return '';
         }
@@ -1128,6 +1197,7 @@ class Database {
             $type_condition = strtolower($type_condition);
              switch($type_condition) {
                 case 'where':
+                    $where_return = '';
                     foreach ($condition_data as $condition => $value_array) {
                         if (is_array($value_array)) {
                             $clean_values = array();
@@ -1208,7 +1278,8 @@ class Database {
         return $return_value;
     }
 
-    public static function parse_where_conditions($coditions){
+    public static function parse_where_conditions($coditions)
+    {
         return self::parse_conditions(array('where'=>$coditions));
     }
 
@@ -1216,7 +1287,8 @@ class Database {
      * Experimental useful database update
      * @todo lot of stuff to do here
      */
-    public static function delete($table_name, $where_conditions) {
+    public static function delete($table_name, $where_conditions)
+    {
         $result = false;
         $where_return = self::parse_where_conditions($where_conditions);
         $sql    = "DELETE FROM $table_name $where_return ";        
@@ -1231,7 +1303,8 @@ class Database {
      * Experimental useful database update
      * @todo lot of stuff to do here
      */
-    public static function update($table_name, $attributes, $where_conditions = array()) {
+    public static function update($table_name, $attributes, $where_conditions = array())
+    {
 
         if (!empty($table_name) && !empty($attributes)) {
             $update_sql = '';
@@ -1265,14 +1338,16 @@ class Database {
     /**
      * @deprecated Use api_get_language_isocode($language) instead.
      */
-    public static function get_language_isocode($language) {
+    public static function get_language_isocode($language)
+    {
         return api_get_language_isocode($language);
     }
 
     /**
      * @deprecated Use Database::insert_id() instead.
      */
-    public static function get_last_insert_id() {
+    public static function get_last_insert_id()
+    {
         global $database_connection;
         return $database_connection->insert_id($database_connection);
     }

+ 132 - 56
main/inc/lib/document.lib.php

@@ -765,11 +765,25 @@ class DocumentManager
      * @param int    $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
      * @return boolean true/false
      * */
-    public static function check_readonly($_course, $user_id, $file, $document_id = '', $to_delete = false)
-    {
+    public static function check_readonly(
+        $_course,
+        $user_id,
+        $file,
+        $document_id = '',
+        $to_delete = false,
+        $sessionId = null
+    ) {
+
+        if (empty($sessionId)) {
+            $sessionId = api_get_session_id();
+        } else {
+            $sessionId = intval($sessionId);
+        }
+
         if (!(!empty($document_id) && is_numeric($document_id))) {
-            $document_id = self::get_document_id($_course, $file);
+            $document_id = self::get_document_id($_course, $file, $sessionId);
         }
+
         $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
         $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
         $course_id = $_course['real_id'];
@@ -778,12 +792,14 @@ class DocumentManager
             if (self::is_folder($_course, $document_id)) {
                 if (!empty($file)) {
                     $path = Database::escape_string($file);
-                    $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM " . $TABLE_DOCUMENT . " td , $TABLE_PROPERTY tp
+                    $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id
+                                          FROM $TABLE_DOCUMENT td , $TABLE_PROPERTY tp
                                           WHERE td.c_id = $course_id AND
                                           		tp.c_id = $course_id AND
+                                                td.session_id = $sessionId AND
                     							tp.ref= td.id AND
                     							(path='" . $path . "' OR path LIKE BINARY '" . $path . "/%' ) ";
-                    //get all id's of documents that are deleted
+                    // Get all id's of documents that are deleted
                     $what_to_check_result = Database::query($what_to_check_sql);
 
                     if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0) {
@@ -809,13 +825,14 @@ class DocumentManager
         }
 
         if (!empty($document_id)) {
-            $sql = "SELECT a.insert_user_id, b.readonly FROM $TABLE_PROPERTY a, $TABLE_DOCUMENT b
+            $sql = "SELECT a.insert_user_id, b.readonly
+                   FROM $TABLE_PROPERTY a, $TABLE_DOCUMENT b
                    WHERE
             			a.c_id = $course_id AND
                         b.c_id = $course_id AND
-            			a.ref = b.id and a.ref= $document_id LIMIT 1";
-            $resultans = Database::query($sql);
-            $doc_details = Database ::fetch_array($resultans, 'ASSOC');
+            			a.ref = b.id and a.ref = $document_id LIMIT 1";
+            $result = Database::query($sql);
+            $doc_details = Database ::fetch_array($result, 'ASSOC');
 
             if ($doc_details['readonly'] == 1) {
                 return !($doc_details['insert_user_id'] == $user_id || api_is_platform_admin());
@@ -846,32 +863,50 @@ class DocumentManager
      * @param int $session_id
      * @param bool $remove_content_from_db
      */
-    public static function delete_document_from_db($document_id, $course_info = array(), $session_id = 0, $remove_content_from_db = false)
-    {
+    public static function delete_document_from_db(
+        $document_id,
+        $course_info = array(),
+        $session_id = 0,
+        $remove_content_from_db = false
+    ) {
         $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
         $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
-        //Deleting from the DB
+        // Deleting from the DB
         $user_id = api_get_user_id();
+        $document_id = intval($document_id);
 
         if (empty($course_info)) {
             $course_info = api_get_course_info();
         }
+
         if (empty($session_id)) {
             $session_id = api_get_session_id();
         }
 
         // Soft DB delete
-        api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'delete', $user_id, null, null, null, null, $session_id);
+        api_item_property_update(
+            $course_info,
+            TOOL_DOCUMENT,
+            $document_id,
+            'delete',
+            $user_id,
+            null,
+            null,
+            null,
+            null,
+            $session_id
+        );
         self::delete_document_from_search_engine($course_info['code'], $document_id);
         self::unset_document_as_template($document_id, $course_info['code'], $user_id);
 
         //Hard DB delete
         if ($remove_content_from_db) {
-            $sql = "DELETE FROM $TABLE_ITEMPROPERTY WHERE c_id = {$course_info['real_id']} AND ref = " . $document_id . " AND tool='" . TOOL_DOCUMENT . "'";
+            $sql = "DELETE FROM $TABLE_ITEMPROPERTY
+                    WHERE c_id = {$course_info['real_id']} AND ref = ".$document_id." AND tool='".TOOL_DOCUMENT."'";
             Database::query($sql);
 
-            $sql = "DELETE FROM " . $TABLE_DOCUMENT . " WHERE c_id = {$course_info['real_id']} AND id = " . $document_id;
+            $sql = "DELETE FROM $TABLE_DOCUMENT WHERE c_id = {$course_info['real_id']} AND id = ".$document_id;
             Database::query($sql);
 
             self::delete_document_metadata($document_id);
@@ -900,11 +935,11 @@ class DocumentManager
      *
      * @param array $_course
      * @param string $path, path stored in the database
-     * @param string ,$base_work_dir, path to the documents folder
+     * @param string $base_work_dir, path to the documents folder
      * @return boolean true/false
      * @todo now only files/folders in a folder get visibility 2, we should rename them too.
      */
-    public static function delete_document($_course, $path, $base_work_dir)
+    public static function delete_document($_course, $path, $base_work_dir, $sessionId = null)
     {
         $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
 
@@ -914,63 +949,89 @@ class DocumentManager
 
         $course_id = $_course['real_id'];
 
-        //first, delete the actual document...
-        $document_id = self :: get_document_id($_course, $path);
+        if (empty($course_id)) {
+            return false;
+        }
+
+        if (empty($sessionId)) {
+            $sessionId = api_get_session_id();
+        } else {
+            $sessionId = intval($sessionId);
+        }
+
+        // First, delete the actual document.
+        $document_id = self::get_document_id($_course, $path, $sessionId);
+
+        if (empty($document_id)) {
+            return false;
+        }
+
         $document_exists_in_disk = file_exists($base_work_dir.$path);
 
-        $new_path = $path . '_DELETED_' . $document_id;
-        $current_session_id = api_get_session_id();
+        $new_path = $path.'_DELETED_'.$document_id;
 
         $file_deleted_from_db = false;
         $file_deleted_from_disk = false;
         $file_renamed_from_disk = false;
 
         if ($document_id) {
-            self::delete_document_from_db($document_id);
+            self::delete_document_from_db($document_id, $_course, $sessionId);
             // Checking
             // $file_exists_in_db = self::get_document_data_by_id($document_id, $_course['code']);
             $file_deleted_from_db = true;
         }
 
         if ($document_exists_in_disk) {
-
             if (api_get_setting('permanently_remove_deleted_files') == 'true') {
-                //Deleted files are *really* deleted
+
+                // Deleted files are *really* deleted.
                 $sql = "SELECT id FROM $TABLE_DOCUMENT
-                        WHERE c_id = $course_id AND path='".$path."' OR path LIKE BINARY '".$path."/%'";
-                // Get all id's of documents that are deleted
+                        WHERE
+                            c_id = $course_id AND
+                            session_id = $sessionId AND
+                            (path = '".$path."' OR path LIKE BINARY '".$path."/%') ";
+                // Get all id's of documents that are deleted.
                 $result = Database::query($sql);
 
                 if ($result && Database::num_rows($result) != 0) {
                     // Delete all item_property entries
                     while ($row = Database::fetch_array($result)) {
                         // Query to delete from item_property table (hard way)
-                        self::delete_document_from_db($row['id'], $_course, $current_session_id, true);
+                        self::delete_document_from_db($row['id'], $_course, $sessionId, true);
                     }
-                    // Delete documents, do it like this so metadata gets deleted too
-                    my_delete($base_work_dir . $path);
-                    $file_deleted_from_disk = true;
                 }
+
+                // Delete documents, do it like this so metadata gets deleted too
+                my_delete($base_work_dir.$path);
+                $file_deleted_from_disk = true;
+
             } else {
                 // Set visibility to 2 and rename file/folder to xxx_DELETED_#id (soft delete)
 
-                if (is_file($base_work_dir . $path) || is_dir($base_work_dir . $path)) {
-                    if (rename($base_work_dir . $path, $base_work_dir.$new_path)) {
+                if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
+                    if (rename($base_work_dir.$path, $base_work_dir.$new_path)) {
 
-                        $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE c_id = $course_id AND id='".$document_id."'";
+                        $sql = "UPDATE $TABLE_DOCUMENT SET path='".$new_path."'
+                                WHERE c_id = $course_id AND session_id = $sessionId AND id = '".$document_id."'";
                         Database::query($sql);
 
-                        $sql = "SELECT id, path FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path LIKE BINARY '".$path."/%'";
+                        $sql = "SELECT id, path FROM $TABLE_DOCUMENT
+                                WHERE
+                                    c_id = $course_id AND
+                                    session_id = $sessionId AND
+                                    (path = '".$path."' OR path LIKE BINARY '".$path."/%') ";
                         $result = Database::query($sql);
                         if ($result && Database::num_rows($result) > 0) {
                             while ($deleted_items = Database::fetch_array($result, 'ASSOC')) {
-                                self::delete_document_from_db($deleted_items['id']);
+                                self::delete_document_from_db($deleted_items['id'], $_course, $sessionId);
 
-                                // Change path of subfolders and documents in database.
+                                // Change path of sub folders and documents in database.
                                 $old_item_path = $deleted_items['path'];
-                                $new_item_path = $new_path . substr($old_item_path, strlen($path));
+                                $new_item_path = $new_path.substr($old_item_path, strlen($path));
 
-                                $sql = "UPDATE $TABLE_DOCUMENT set path = '" . $new_item_path . "' WHERE c_id = $course_id AND id = " . $deleted_items['id'];
+                                $sql = "UPDATE $TABLE_DOCUMENT
+                                        SET path = '".$new_item_path."'
+                                        WHERE c_id = $course_id AND session_id = $sessionId AND id = ".$deleted_items['id'];
                                 Database::query($sql);
                             }
                         }
@@ -1032,17 +1093,24 @@ class DocumentManager
     /**
      * Gets the id of a document with a given path
      *
-     * @param array $_course
+     * @param array $courseInfo
      * @param string $path
      * @return int id of document / false if no doc found
      */
-    public static function get_document_id($course_info, $path)
+    public static function get_document_id($courseInfo, $path, $sessionId = null)
     {
         $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
-        $course_id = $course_info['real_id'];
+        $course_id = $courseInfo['real_id'];
+        if (empty($sessionId)) {
+            $sessionId = api_get_session_id();
+        } else {
+            $sessionId = intval($sessionId);
+        }
         $path = Database::escape_string($path);
+
         if (!empty($course_id) && !empty($path)) {
-            $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path LIKE BINARY '$path' LIMIT 1";
+            $sql = "SELECT id FROM $TABLE_DOCUMENT
+                    WHERE c_id = $course_id AND path LIKE BINARY '$path' AND session_id = $sessionId LIMIT 1";
             $result = Database::query($sql);
             if ($result && Database::num_rows($result)) {
                 $row = Database::fetch_array($result);
@@ -1060,7 +1128,7 @@ class DocumentManager
      * @param bool load parents?
      * @return array document content
      */
-    public static function get_document_data_by_id($id, $course_code, $load_parents = false)
+    public static function get_document_data_by_id($id, $course_code, $load_parents = false, $session_id = null)
     {
         $course_info = api_get_course_info($course_code);
         $course_id = $course_info['real_id'];
@@ -1068,11 +1136,18 @@ class DocumentManager
         if (empty($course_info)) {
             return false;
         }
-        $www = api_get_path(WEB_COURSE_PATH) . $course_info['path'] . '/document';
+
+        if (empty($session_id)) {
+            $session_id = intval($session_id);
+        } else {
+            $session_id = api_get_session_id();
+        }
+
+        $www = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document';
 
         $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
         $id = intval($id);
-        $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND id = $id ";
+        $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND session_id = $session_id AND id = $id ";
         $result = Database::query($sql);
         if ($result && Database::num_rows($result) == 1) {
             $row = Database::fetch_array($result, 'ASSOC');
@@ -1093,15 +1168,13 @@ class DocumentManager
             if (dirname($row['path']) == '.') {
                 $row['parent_id'] = '0';
             } else {
-                $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']));
+                $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']), $session_id);
             }
             $parents = array();
 
             //Use to generate parents (needed for the breadcrumb)
             //@todo sorry but this for is here because there's not a parent_id in the document table so we parsed the path!!
 
-            $visibility = true;
-
             if ($load_parents) {
                 $dir_array = explode('/', $row['path']);
                 $dir_array = array_filter($dir_array);
@@ -1113,13 +1186,12 @@ class DocumentManager
                     $real_dir .= '/' . $dir_array[$i];
                     $parent_id = self::get_document_id($course_info, $real_dir);
                     if (!empty($parent_id)) {
-                        $sub_document_data = self::get_document_data_by_id($parent_id, $course_code, false);
+                        $sub_document_data = self::get_document_data_by_id($parent_id, $course_code, false, $session_id);
                         //@todo add visibility here
                         $parents[] = $sub_document_data;
                     }
                 }
             }
-            //$row['visibility_for_user'] = $visibility;
             $row['parents'] = $parents;
             return $row;
         }
@@ -1523,8 +1595,12 @@ class DocumentManager
      * @param int The document id of the default certificate
      * @return void()
      */
-    function remove_attach_certificate($course_id, $default_certificate_id)
+    public static function remove_attach_certificate($course_id, $default_certificate_id)
     {
+        if (empty($default_certificate_id)) {
+            return false;
+        }
+
         $default_certificate = self::get_default_certificate_id($course_id);
         if ((int) $default_certificate == (int) $default_certificate_id) {
             $tbl_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
@@ -1548,7 +1624,7 @@ class DocumentManager
      * @param string The course id
      * @return void()
      */
-    static function create_directory_certificate_in_course($course_id)
+    public static function create_directory_certificate_in_course($course_id)
     {
         $course_info = api_get_course_info($course_id);
         if (!empty($course_info)) {
@@ -1575,7 +1651,7 @@ class DocumentManager
      * @param string The course id
      * @return int The document id of the directory certificate
      */
-    static function get_document_id_of_directory_certificate()
+    public static function get_document_id_of_directory_certificate()
     {
         $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
         $course_id = api_get_course_int_id();
@@ -1590,7 +1666,7 @@ class DocumentManager
      * @param string path of directory
      * @return bool  true if is a certificate or false otherwise
      */
-    static function is_certificate_mode($dir)
+    public static function is_certificate_mode($dir)
     {
         // I'm in the certification module?
         $is_certificate_mode = false;
@@ -1615,7 +1691,7 @@ class DocumentManager
      * @return	array	List of file paths. An additional field containing 'local' or 'remote' helps determine
      * if the file should be copied into the zip or just linked
      */
-    static function get_resources_from_source_html($source_html, $is_file = false, $type = null, $recursivity = 1)
+    public static function get_resources_from_source_html($source_html, $is_file = false, $type = null, $recursivity = 1)
     {
         $max = 5;
         $attributes = array();
@@ -1900,7 +1976,7 @@ class DocumentManager
      * @return   array   An associative array of attributes
      * @author 	 Based on a function from the HTML_Common2 PEAR module     *
      */
-    static function parse_HTML_attributes($attrString, $wanted = array(), $explode_variables = array())
+    public static function parse_HTML_attributes($attrString, $wanted = array(), $explode_variables = array())
     {
         $attributes = array();
         $regs = array();

+ 47 - 40
main/inc/lib/fckeditor/editor/filemanager/connectors/php/config.php

@@ -22,7 +22,7 @@
  * Configuration file for the File Manager Connector for PHP.
  */
 
-// Modifications by Ivan Tcholakov, JUN-2009. 
+// Modifications by Ivan Tcholakov, JUN-2009.
 
 // Some language variables are needed.
 $language_file = array('create_course');
@@ -30,69 +30,79 @@ $language_file = array('create_course');
 // Loading the global initialization file, Chamilo LMS.
 require_once '../../../../../../global.inc.php';
 
+// Disabling access for anonymous users.
+api_block_anonymous_users();
+
 // Initialization of the repositories.
 require_once api_get_path(LIBRARY_PATH).'fckeditor/repository.php' ;
 
-global $Config ;
+global $Config;
 
 // SECURITY: You must explicitly enable this "connector". (Set it to "true").
 // WARNING: don't just set "$Config['Enabled'] = true ;", you must be sure that only
 //		authenticated users can access this file or use some kind of session checking.
 $Config['Enabled'] = true ;
 
-
 // Path to user files relative to the document root.
-//$Config['UserFilesPath']
+$Config['UserFilesPath'] = null;
+
+$userId = api_get_user_id();
+
+
 if (api_is_in_course()) {
-	if (!api_is_in_group()) {
-		// 1. We are inside a course and not in a group.
-		if (api_is_allowed_to_edit()) {
-			$Config['UserFilesPath'] = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/';
-		} else {
-			// 1.2. Student	
-			$current_session_id = api_get_session_id();
-			if($current_session_id==0)
-			{
-				$Config['UserFilesPath'] = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/shared_folder/sf_user_'.api_get_user_id().'/';
-			}
-			else
-			{
-				$Config['UserFilesPath'] = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().'/';		
-			}
-		}
-	} else {
-		// 2. Inside a course and inside a group.
-		global $group_properties;
-		$Config['UserFilesPath'] = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/';
-	}
+    $coursePath = api_get_path(REL_COURSE_PATH).api_get_course_path();
+    if (!api_is_in_group()) {
+        // 1. We are inside a course and not in a group.
+        if (api_is_allowed_to_edit()) {
+            $Config['UserFilesPath'] = $coursePath.'/document/';
+        } else {
+            // 1.2. Student
+            $current_session_id = api_get_session_id();
+            if ($current_session_id == 0) {
+                $Config['UserFilesPath'] = $coursePath.'/document/shared_folder/sf_user_'.$userId.'/';
+            } else {
+                $Config['UserFilesPath'] = $coursePath.'/document/shared_folder_session_'.$current_session_id.'/sf_user_'.$userId.'/';
+            }
+        }
+    } else {
+        $groupId = api_get_group_id();
+        $groupInfo = GroupManager::get_group_properties($groupId);
+        if (!empty($groupInfo)) {
+            // 2. Inside a course and inside a group.
+            $Config['UserFilesPath'] = $coursePath.'/document'.$groupInfo['directory'].'/';
+        }
+    }
 } else {
-	if (api_is_platform_admin() && $_SESSION['this_section'] == 'platform_admin') {
-		// 3. Platform administration activities.
-		$Config['UserFilesPath'] = api_get_path(REL_PATH).'home/default_platform_document/';
-	} else {
-		// 4. The user is outside courses.
-        $my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'rel');
-		$Config['UserFilesPath'] = $my_path['dir'].'my_files/';
-	}
+    if (api_is_platform_admin() && $_SESSION['this_section'] == 'platform_admin') {
+        // 3. Platform administration activities.
+        $Config['UserFilesPath'] = api_get_path(REL_PATH).'home/default_platform_document/';
+    } else {
+        // 4. The user is outside courses.
+        $my_path = UserManager::get_user_picture_path_by_id($userId, 'rel');
+        $Config['UserFilesPath'] = $my_path['dir'].'my_files/';
+    }
 }
 
+if (empty($Config['UserFilesPath'])) {
+    api_not_allowed(true);
+}
 
 // Fill the following value it you prefer to specify the absolute path for the
 // user files directory. Useful if you are using a virtual directory, symbolic
 // link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
 // Attention: The above 'UserFilesPath' must point to the same directory.
-$Config['UserFilesAbsolutePath'] = rtrim(api_get_path(SYS_SERVER_ROOT_PATH), '/') . $Config['UserFilesPath'] ;
+$Config['UserFilesAbsolutePath'] = rtrim(api_get_path(SYS_SERVER_ROOT_PATH), '/').$Config['UserFilesPath'];
 
 // Due to security issues with Apache modules, it is recommended to leave the
 // following setting enabled.
-$Config['ForceSingleExtension'] = true ;
+$Config['ForceSingleExtension'] = true;
 
 // Perform additional checks for image files.
 // If set to true, validate image size (using getimagesize).
 $Config['SecureImageUploads'] = true;
 
 // What the user can do with this connector.
-$Config['ConfigAllowedCommands'] = array('QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder') ;
+$Config['ConfigAllowedCommands'] = array('QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder');
 
 // Allowed Resource Types.
 $Config['ConfigAllowedTypes'] = array('File', 'Audio', 'Images', 'Flash', 'Media', 'MP3', 'Video', 'Video/flv') ;
@@ -160,8 +170,7 @@ $Config['ChmodOnFolderCreate'] = $permissions_for_new_directories ;
 			$Config['QuickUploadAbsolutePath']['Image']	= $Config['UserFilesAbsolutePath'] ;
 		into:
 			$Config['QuickUploadPath']['Image']			= $Config['FileTypesPath']['Image'] ;
-			$Config['QuickUploadAbsolutePath']['Image'] 	= $Config['FileTypesAbsolutePath']['Image'] ;
-
+			$Config['QuickUploadAbsolutePath']['Image'] 	= $Config['FileTypesAbsolutePath']['Image'];
 */
 
 // Files
@@ -220,5 +229,3 @@ $Config['FileTypesPath']['Video/flv']			= $Config['UserFilesPath'] . 'video/flv/
 $Config['FileTypesAbsolutePath']['Video/flv']	= $Config['UserFilesAbsolutePath'] . 'video/flv/' ;
 $Config['QuickUploadPath']['Video/flv']			= $Config['UserFilesPath'] . 'video/flv/' ;
 $Config['QuickUploadAbsolutePath']['Video/flv']	= $Config['UserFilesAbsolutePath'] . 'video/flv/' ;
-
-?>

+ 6 - 24
main/inc/lib/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php

@@ -576,24 +576,15 @@ class ImageManager
 				$chamiloFile = $file['name'];
 				$chamiloFileSize = $file['size'];
 				if(!empty($group_properties['directory'])) {
-					$chamiloFolder=$group_properties['directory'].$chamiloFolder;
+					$chamiloFolder = $group_properties['directory'].$chamiloFolder;
 				}
 
 				$doc_id = add_document($_course, $document_path,'file', $chamiloFileSize , $chamiloFile);
-				$current_session_id = api_get_session_id();
-				api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(),$to_group_id,null,null,null,$current_session_id);//get Dokeos
+				api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(),$to_group_id,null,null,null,api_get_session_id());
 			}
-
-			/*
-			if (!(api_is_platform_admin() || api_is_course_admin())) {
-				//setting invisible by default for the students
-				api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id());
-			}
-			*/
 		   $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0;
 		   // If maximum size is specified, constrain image to it.
-           if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0)
-           {
+           if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0) {
 			   $img = Image_Transform::factory(IMAGE_CLASS);
 			   $img->load($path . $result);
 
@@ -609,7 +600,7 @@ class ImageManager
            }
 	   }
 
-		//delete tmp files.
+		// Delete tmp files.
 		Files::delFile($file['tmp_name']);
 		return false;
 	}
@@ -782,13 +773,7 @@ class ImageManager
 			{
 				Return false;
 			}
-
-		}
-		/*
 		}
-		else
-			Return false;
-		*/
 	}
 
 	/**
@@ -820,9 +805,8 @@ class ImageManager
 					$base_dir = substr($path, 0, strpos($path,'/document/')+9); //
 					$new_dir  = substr($fullpath, strlen($base_dir),-1); //
 					$created_dir = create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), 0,0, $base_dir, $new_dir,$newDir);
-					$doc_id = DocumentManager::get_document_id($_course, $new_dir );
-					$current_session_id = api_get_session_id();
-					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(),null,null,null,null,$current_session_id);
+					$doc_id = DocumentManager::get_document_id($_course, $new_dir);
+					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(),null,null,null,null, api_get_session_id());
 				} else {
 				 	return Files::createFolder($fullpath);
 				}
@@ -891,5 +875,3 @@ class ImageManager
 		return $errors;
 	}
 }
-
-?>

+ 42 - 54
main/inc/lib/fckeditor/editor/plugins/ImageManager/config.inc.php

@@ -27,62 +27,53 @@
  in this directory and its subdirectories.
 */
 $language_file = array('document');
-include '../../../../../../inc/global.inc.php';
+
+require_once '../../../../../../inc/global.inc.php';
+
+// Disabling access for anonymous users.
+api_block_anonymous_users();
 
 // Initialization of the repositories.
 require_once api_get_path(LIBRARY_PATH).'fckeditor/repository.php';
 
+$userId = api_get_user_id();
+
 // Choosing the repository to be used.
-if (api_is_in_course())
-{
-	if (!api_is_in_group())
-	{
-		// 1. We are inside a course and not in a group.
-		if (api_is_allowed_to_edit())
-		{
-			// 1.1. Teacher
-			$IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document/';
-			$IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/';
-		}
-		else
-		{
-			// 1.2. Student			
-			$current_session_id = api_get_session_id();
-			if($current_session_id==0)
-			{
-				$IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document/shared_folder/sf_user_'.api_get_user_id().'/';
-				$IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/shared_folder/sf_user_'.api_get_user_id().'/';
-			}
-			else
-			{
-				$IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().'/';
-				$IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().'/';	
-			}	
-		}
-	}
-	else
-	{
-		// 2. Inside a course and inside a group.
-		$IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/';
-		$IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/';
-	}
-}
-else
-{
-	if (api_is_platform_admin() && $_SESSION['this_section'] == 'platform_admin')
-	{
-		// 3. Platform administration activities.
-		$IMConfig['base_dir'] = $_configuration['root_sys'].'home/default_platform_document/';
-		$IMConfig['base_url'] = $_configuration['root_web'].'home/default_platform_document/';
-	}
-	else
-	{
-		// 4. The user is outside courses.
-        $my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'system');
-		$IMConfig['base_dir'] = $my_path['dir'].'my_files/';
-        $my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'web');
-		$IMConfig['base_url'] = $my_path['dir'].'my_files/';
-	}
+if (api_is_in_course()) {
+    if (!api_is_in_group()) {
+        // 1. We are inside a course and not in a group.
+        if (api_is_allowed_to_edit()) {
+            // 1.1. Teacher
+            $IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document/';
+            $IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/';
+        } else {
+            // 1.2. Student
+            $sessionId = api_get_session_id();
+            if ($sessionId == 0) {
+                $IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document/shared_folder/sf_user_'.$userId.'/';
+                $IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/shared_folder/sf_user_'.$userId.'/';
+            } else {
+                $IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document/shared_folder_session_'.$sessionId.'/sf_user_'.$userId.'/';
+                $IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/shared_folder_session_'.$sessionId.'/sf_user_'.$userId.'/';
+            }
+        }
+	} else {
+        // 2. Inside a course and inside a group.
+        $IMConfig['base_dir'] = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/';
+        $IMConfig['base_url'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/';
+    }
+} else {
+    if (api_is_platform_admin() && $_SESSION['this_section'] == 'platform_admin') {
+        // 3. Platform administration activities.
+        $IMConfig['base_dir'] = $_configuration['root_sys'].'home/default_platform_document/';
+        $IMConfig['base_url'] = $_configuration['root_web'].'home/default_platform_document/';
+    } else {
+        // 4. The user is outside courses.
+        $my_path = UserManager::get_user_picture_path_by_id($userId, 'system');
+        $IMConfig['base_dir'] = $my_path['dir'].'my_files/';
+        $my_path = UserManager::get_user_picture_path_by_id($userId, 'web');
+        $IMConfig['base_url'] = $my_path['dir'].'my_files/';
+    }
 }
 
 $IMConfig['server_name'] = $_SERVER['SERVER_NAME'];
@@ -91,11 +82,8 @@ $IMConfig['server_name'] = $_SERVER['SERVER_NAME'];
  demo - when true, no saving is allowed
 */
 $IMConfig['demo'] = false;
-
 /*
-
   Possible values: true, false
-
   TRUE - If PHP on the web server is in safe mode, set this to true.
          SAFE MODE restrictions: directory creation will not be possible,
 		 only the GD library can be used, other libraries require

+ 0 - 2
main/inc/lib/fckeditor/editor/plugins/ImageManager/editor.php

@@ -20,7 +20,6 @@ if (isset($_GET['img'])) {
 
 ?>
 <!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="<?php echo $IMConfig['language']; ?>" lang="<?php echo $IMConfig['language']; ?>">
 <head>
 <title>Edit image</title>
@@ -92,7 +91,6 @@ if (isset($_GET['img'])) {
 <script type="text/javascript" src="assets/slider.js"></script>
 <script type="text/javascript" src="assets/popup.js"></script>
 <script type="text/javascript" src="assets/editor.js"></script>
-
 <style type="text/css" media="screen, projection">
 /*<![CDATA[*/
 body {

+ 23 - 25
main/inc/lib/fckeditor/editor/plugins/ImageManager/editorFrame.php

@@ -1,27 +1,27 @@
 <?php
-	/**
-	 * The frame that contains the image to be edited.
-	 * @author Wei Zhuo
-	 * @author Paul Moers <mail@saulmade.nl> - watermarking and replace code + several small enhancements <http://www.saulmade.nl/FCKeditor/FCKPlugins.php>
-	 * @version $Id: editorFrame.php,v 1.7 2006/12/20 18:19:28 thierrybo Exp $
-	 * @package ImageManager
-	 */
+/**
+ * The frame that contains the image to be edited.
+ * @author Wei Zhuo
+ * @author Paul Moers <mail@saulmade.nl> - watermarking and replace code + several small enhancements <http://www.saulmade.nl/FCKeditor/FCKPlugins.php>
+ * @version $Id: editorFrame.php,v 1.7 2006/12/20 18:19:28 thierrybo Exp $
+ * @package ImageManager
+ */
 
-	require_once('config.inc.php');
-	require_once('Classes/ImageManager.php');
-	require_once('Classes/ImageEditor.php');
+require_once('config.inc.php');
+require_once('Classes/ImageManager.php');
+require_once('Classes/ImageEditor.php');
 
-	//default path is /
-	$relative = '/';
+//default path is /
+$relative = '/';
 
-	$manager = new ImageManager($IMConfig);
-	$editor = new ImageEditor($manager);
+$manager = new ImageManager($IMConfig);
+$editor = new ImageEditor($manager);
 
-	// process any uploaded files
-	$imageRelative = $manager->processUploads();
+// process any uploaded files
+$imageRelative = $manager->processUploads();
 
-	// get image info and process any action
-	$imageInfo = $editor->processImage($imageRelative);
+// get image info and process any action
+$imageInfo = $editor->processImage($imageRelative);
 
 ?>
 <!--[if IE]>
@@ -35,14 +35,12 @@
 <script type="text/javascript" src="assets/wz_dragdrop.js"></script>
 <script type="text/javascript" src="assets/EditorContent.js"></script>
 <script type="text/javascript" src="assets/editorFrame.js"></script>
-
 <style>
-
-	/* for centering the image vertically in IE */
-	html, body
-	{
-		height: 100%;
-	}
+/* for centering the image vertically in IE */
+html, body
+{
+    height: 100%;
+}
 
 </style>
 

+ 6 - 14
main/inc/lib/fckeditor/editor/plugins/ImageManager/manager.php

@@ -6,21 +6,13 @@
  * @package ImageManager
  */
 
-	require_once('config.inc.php');
-	require_once('Classes/ImageManager.php');
+require_once('config.inc.php');
+require_once('Classes/ImageManager.php');
 
-	$manager = new ImageManager($IMConfig);
-	$dirs = $manager->getDirs();
-	$var = explode('/',$_GET['base_url_alt']);
-	/*
-	// if the base_url_alt parameter there is a default_course_document we change the allow upload parameter
-	if (($var[count($var)-2] == 'default_course_document') && !api_is_platform_admin())
-	{
-		$IMConfig['allow_upload']=false;
-	}
-	*/
-	//clean injection string (XSS)
-	$base_url_alt = str_replace('"','',$_GET['base_url_alt']);
+$manager = new ImageManager($IMConfig);
+$dirs = $manager->getDirs();
+$var = explode('/',$_GET['base_url_alt']);
+$base_url_alt = str_replace('"','',$_GET['base_url_alt']);
 
 ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

+ 157 - 126
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/_ajax_get_details_listing.php

@@ -1,137 +1,168 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+?>
+
 <div id="content">
-<table class="tableList" id="tableList" cellpadding="0" cellspacing="0" border="0">
-<thead>
-	<tr>
-		<th width="5"><a href="#" class="check_all" id="tickAll" title="<?php echo TIP_SELECT_ALL; ?>" onclick="checkAll(this);">&nbsp;</a></th>
-		<th width="10" class="fileColumns">&nbsp;</th>
-		<th class="docName"><?php echo LBL_NAME; ?></th>
-		<th  width="70" class="fileColumns"><?php echo LBL_SIZE; ?></th>
-		<!-- hide while implementing this Chamilo -->
-		<!--<th class="fileColumns"><?php // echo LBL_MODIFIED; ?></th> -->						
-	</tr>
-</thead>
-<tbody id="fileList">
-	<?php 
-		$count = 1;
-		$css = "";
-		//list all documents (files and folders) under this current folder, 
-		//echo appendQueryString(appendQueryString(CONFIG_URL_FILEnIMAGE_MANAGER, "path=" . $file['path']), makeQueryString(array('path'))); 
-		foreach($fileList as $file) {
-			$css = ($css == "" || $css == "even"?"odd":"even");
-			$strDisabled = ($file['is_writable']?"":" disabled");
-			$strClass = ($file['is_writable']?"left":" leftDisabled");
-			///First step for hidden some type of Chamilo files and folders
-			//Juan Carlos Raña
+    <table class="tableList" id="tableList" cellpadding="0" cellspacing="0" border="0">
+        <thead>
+        <tr>
+            <th width="5"><a href="#" class="check_all" id="tickAll" title="<?php echo TIP_SELECT_ALL; ?>"
+                             onclick="checkAll(this);">&nbsp;</a></th>
+            <th width="10" class="fileColumns">&nbsp;</th>
+            <th class="docName"><?php echo LBL_NAME; ?></th>
+            <th width="70" class="fileColumns"><?php echo LBL_SIZE; ?></th>
+            <!-- hide while implementing this Chamilo -->
+            <!--<th class="fileColumns"><?php // echo LBL_MODIFIED; ?></th> -->
+        </tr>
+        </thead>
+        <tbody id="fileList">
+        <?php
+        $count = 1;
+        $css = "";
+        //list all documents (files and folders) under this current folder,
+        //echo appendQueryString(appendQueryString(CONFIG_URL_FILEnIMAGE_MANAGER, "path=" . $file['path']), makeQueryString(array('path')));
+        foreach ($fileList as $file) {
+            $css         = ($css == "" || $css == "even" ? "odd" : "even");
+            $strDisabled = ($file['is_writable'] ? "" : " disabled");
+            $strClass    = ($file['is_writable'] ? "left" : " leftDisabled");
+            ///First step for hidden some type of Chamilo files and folders
+            //Juan Carlos Raña
+
+            //hidden files and folders deleted by Chamilo. Hidde folders css, hotpotatoes, chat_files, certificates
+            $deleted_by_chamilo_file    = ' DELETED '; // ' DELETED ' not '_DELETED_' because in $file['name'] _ is replaced with blank see class.manager.php
+            $deleted_by_chamilo_folder  = '_DELETED_';
+            $css_folder_chamilo         = 'css';
+            $hotpotatoes_folder_chamilo = 'HotPotatoes_files';
+            $chat_files_chamilo         = 'chat_files';
+            $certificates_chamilo       = 'certificates';
+            //show group's directory only if I'm member. Or if I'm a teacher. TODO: check groups not necessary because the student dont have access to main folder documents (only to document/group or document/shared_folder). Teachers can access to all groups ?
+            $group_folder = '_groupdocs';
+
+
+            $show_doc_group = true;
+            if (ereg($group_folder, $file['path'])) {
+                $show_doc_group = false;
+                if ($is_user_in_group || ($to_group_id != 0 && api_is_allowed_to_edit())) {
+                    $show_doc_group = true;
+                }
+            }
 
-			//hidden files and folders deleted by Chamilo. Hidde folders css, hotpotatoes, chat_files, certificates
-			$deleted_by_chamilo_file=' DELETED '; // ' DELETED ' not '_DELETED_' because in $file['name'] _ is replaced with blank see class.manager.php
-			$deleted_by_chamilo_folder='_DELETED_';
-			$css_folder_chamilo='css';
-			$hotpotatoes_folder_chamilo='HotPotatoes_files';
-			$chat_files_chamilo='chat_files';
-			$certificates_chamilo='certificates';
-			//show group's directory only if I'm member. Or if I'm a teacher. TODO: check groups not necessary because the student dont have access to main folder documents (only to document/group or document/shared_folder). Teachers can access to all groups ?
-			$group_folder='_groupdocs';
-						
+            ///Second step: hiding as the case
+            //Juan Carlos Raña
 
-			$show_doc_group=true;
-			if(ereg($group_folder, $file['path'])) {
-				$show_doc_group=false;
-				if($is_user_in_group ||( $to_group_id!=0 && api_is_allowed_to_edit())) {
-					$show_doc_group=true;
-				}
-			}
+            if ((!ereg($deleted_by_chamilo_file, $file['name']) &&
+                    !ereg($deleted_by_chamilo_folder, $file['path'])) &&
+                !ereg($css_folder_chamilo, $file['path']) &&
+                !ereg($hotpotatoes_folder_chamilo, $file['path']) &&
+                !ereg($chat_files_chamilo, $file['path']) &&
+                !ereg($certificates_chamilo, $file['path']) &&
+                $show_doc_group && $file['name'][0] != '.'
+            ) {
+                //hide Nanogong  tag
+                if (strpos($file['path'], '_chnano_')) {
+                    $file['path'] = substr_replace($file['path'], '.wav', -12); //into real file name
+                    $file['name'] = substr_replace($file['name'], '.wav', -12); //into web name
+                }
 
-			///Second step: hiding as the case
-			//Juan Carlos Raña
+                if ($file['type'] == 'file') {
+                    if (Security::remove_XSS($_GET['editor']) != 'stand_alone') {
+                        $path_chamilo_file = '../'.$file['path']; // fix for makes a good show when pressed next on window preview, don't only one image
+                    } else {
+                        $path_chamilo_file = $file['path'];
+                    }
 
-			if ((!ereg($deleted_by_chamilo_file, $file['name']) && 
-				 !ereg($deleted_by_chamilo_folder, $file['path'])) && 
-				 !ereg($css_folder_chamilo, $file['path']) && 
-				 !ereg($hotpotatoes_folder_chamilo, $file['path']) && 
-				 !ereg($chat_files_chamilo, $file['path']) && 
-				 !ereg($certificates_chamilo, $file['path']) && 
-				 $show_doc_group && $file['name'][0]!='.') {							
-				//hide Nanogong  tag
-				if (strpos($file['path'], '_chnano_')) {
-					$file['path']= substr_replace($file['path'], '.wav', -12);//into real file name
-					$file['name']= substr_replace($file['name'], '.wav', -12);//into web name
-				}
-				
-				if ($file['type'] == 'file') {
-					if(Security::remove_XSS($_GET['editor'])!='stand_alone') {
-						$path_chamilo_file='../'.$file['path'];// fix for makes a good show when pressed next on window preview, don't only one image
-					} else {
-						$path_chamilo_file=$file['path'];
-					}
+                    ?>
+                    <tr class="<?php echo $css; ?>" id="row<?php echo $count; ?>">
+                        <td align="center" id="tdz<?php echo $count; ?>">
+                            <span id="flag<?php echo $count; ?>" class="<?php echo $file['flag']; ?>">&nbsp;</span>
+                            <input type="checkbox" name="check[]" id="cb<?php echo $count; ?>"
+                                   value="<?php echo $file['path']; ?>" <?php echo $strDisabled; ?> />
+                        </td>
+                        <td align="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
+                            <a id="<?php echo $count; ?>" href="<?php echo $path_chamilo_file; // fix for Chamilo ?>"
+                               target="_blank">
+                                <span class="<?php echo $file['cssClass']; ?>">&nbsp;</span></a>
+                        </td>
+                        <td class="<?php echo $strClass; ?> docName" id="tdnd<?php echo $count; ?>">
+                            <a id="<?php echo $count; ?>" href="<?php echo $path_chamilo_file; //fix for Chamilo ?>"
+                               target="_blank">
+                                <?php echo $file['name']; ?></a>
+                        </td>
 
-				?>
-				<tr class="<?php echo $css; ?>" id="row<?php echo $count; ?>"  >
-					<td align="center" id="tdz<?php echo $count; ?>">
-						<span id="flag<?php echo $count; ?>" class="<?php echo $file['flag']; ?>">&nbsp;</span>
-						<input type="checkbox"  name="check[]" id="cb<?php echo $count; ?>" value="<?php echo $file['path']; ?>" <?php echo $strDisabled; ?> />
-					</td>
-					<td align="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
-						<a id="<?php echo $count; ?>" href="<?php echo $path_chamilo_file; // fix for Chamilo ?>" target="_blank">
-							<span class="<?php echo $file['cssClass']; ?>">&nbsp;</span></a>
-					</td>					
-					<td class="<?php echo $strClass; ?> docName"  id="tdnd<?php echo $count; ?>">
-						<a id="<?php echo $count; ?>" href="<?php echo $path_chamilo_file; //fix for Chamilo ?>" target="_blank">
-						<?php echo $file['name']; ?></a>
-					</td>
+                        <td class="docInfo" id="tdrd<?php echo $count; ?>"><?php echo transformFileSize(
+                                $file['size']
+                            ); ?></td>
+                        <!-- hide while implementing this Chamilo -->
+                        <!--<td class="docInfo" id="tdth<?php //echo $count; ?>"><?php //echo @date(DATE_TIME_FORMAT,$file['mtime']); ?></td> -->
+                    </tr>
+                <?php
 
-					<td class="docInfo" id="tdrd<?php echo $count; ?>"><?php echo transformFileSize($file['size']); ?></td>
-					<!-- hide while implementing this Chamilo -->
-					<!--<td class="docInfo" id="tdth<?php //echo $count; ?>"><?php //echo @date(DATE_TIME_FORMAT,$file['mtime']); ?></td> -->
-				</tr>
-				<?php
-				
-				} else {
-					?>
-					<tr class="<?php echo $css; ?>" id="row<?php echo $count; ?>" >
-						<td align="center" id="tdz<?php echo $count; ?>"><span id="flag<?php echo $count; ?>" class="<?php echo $file['flag']; ?>">&nbsp;</span><input type="checkbox" name="check[]" id="cb<?php echo $count; ?>" value="<?php echo $file['path']; ?>" <?php echo $strDisabled; ?>/>
-						</td>
-					  <?php
+                } else {
+                    ?>
+                    <tr class="<?php echo $css; ?>" id="row<?php echo $count; ?>">
+                        <td align="center" id="tdz<?php echo $count; ?>"><span id="flag<?php echo $count; ?>"
+                                                                               class="<?php echo $file['flag']; ?>">&nbsp;</span><input
+                                type="checkbox" name="check[]" id="cb<?php echo $count; ?>"
+                                value="<?php echo $file['path']; ?>" <?php echo $strDisabled; ?>/>
+                        </td>
+                        <?php
 
-						if (preg_match('/shared_folder/', basename($file['path']))) {
-						//add icon into ajaxfilemanager if sharedfolder is into Chamilo
-						?>
-							<td  lign="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
-								<a id="<?php echo $count; ?>" href="<?php echo $file['path']; ?>" <?php echo $file['cssClass'] == 'filePicture'?'rel="ajaxPhotos"':''; ?>  >
-									<span class="<?php echo ($file['type'] == 'folder '?$file['cssClass']:"folderShared"); ?>">&nbsp;</span></a>
-							</td>
-						<?php
-						} elseif(preg_match('/sf_user_/', basename($file['path']))) {
-						?>
-						<td  lign="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
-							<a id="<?php echo $count; ?>" href="<?php echo $file['path']; ?>" <?php echo $file['cssClass'] == 'filePicture'?'rel="ajaxPhotos"':''; ?>  >
-								<span class="<?php echo ($file['type'] == 'folder '?$file['cssClass']:"unknownUser"); ?>">&nbsp;</span></a>
-						</td>											
-						<?php
-						} else {
-						?>
-							<td  lign="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
-								<a id="<?php echo $count; ?>" href="<?php echo $file['path']; ?>" <?php echo $file['cssClass'] == 'filePicture'?'rel="ajaxPhotos"':''; ?>  >
-									<span class="<?php echo ($file['file']||$file['subdir']?$file['cssClass']:"folderEmpty"); ?>">&nbsp;</span></a>
-							</td>
-						<?php
-						}
-						?>                                            
-						<td class="<?php echo $strClass; ?> docName" id="tdnd<?php echo $count; ?>">
-							<a id="<?php echo $count; ?>" href="<?php echo "../".$file['path']; ?>" target="_blank"><?php echo $file['name']; ?></a>
-						</td>
-						<td class="docInfo" id="tdrd<?php echo $count; ?>">&nbsp;</td>
-						 <!-- hide while implementing this Chamilo -->
-						<!--<td class="docInfo" id="tdth<?php// echo $count; ?>"><?php //echo @date(DATE_TIME_FORMAT,$file['mtime']); ?></td> -->
-					</tr>
-					<?php
-				}
+                        if (preg_match('/shared_folder/', basename($file['path']))) {
+                            //add icon into ajaxfilemanager if sharedfolder is into Chamilo
+                            ?>
+                            <td lign="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
+                                <a id="<?php echo $count; ?>"
+                                   href="<?php echo $file['path']; ?>" <?php echo $file['cssClass'] == 'filePicture' ? 'rel="ajaxPhotos"' : ''; ?>  >
+                                    <span
+                                        class="<?php echo($file['type'] == 'folder ' ? $file['cssClass'] : "folderShared"); ?>">&nbsp;</span></a>
+                            </td>
+                        <?php
+                        } elseif (preg_match('/sf_user_/', basename($file['path']))) {
+                            ?>
+                            <td lign="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
+                                <a id="<?php echo $count; ?>"
+                                   href="<?php echo $file['path']; ?>" <?php echo $file['cssClass'] == 'filePicture' ? 'rel="ajaxPhotos"' : ''; ?>  >
+                                    <span
+                                        class="<?php echo($file['type'] == 'folder ' ? $file['cssClass'] : "unknownUser"); ?>">&nbsp;</span></a>
+                            </td>
+                        <?php
+                        } else {
+                            ?>
+                            <td lign="center" class="fileColumns" id="tdst<?php echo $count; ?>">&nbsp;
+                                <a id="<?php echo $count; ?>"
+                                   href="<?php echo $file['path']; ?>" <?php echo $file['cssClass'] == 'filePicture' ? 'rel="ajaxPhotos"' : ''; ?>  >
+                                    <span
+                                        class="<?php echo($file['file'] || $file['subdir'] ? $file['cssClass'] : "folderEmpty"); ?>">&nbsp;</span></a>
+                            </td>
+                        <?php
+                        }
+                        ?>
+                        <td class="<?php echo $strClass; ?> docName" id="tdnd<?php echo $count; ?>">
+                            <a id="<?php echo $count; ?>" href="<?php echo "../".$file['path']; ?>"
+                               target="_blank"><?php echo $file['name']; ?></a>
+                        </td>
+                        <td class="docInfo" id="tdrd<?php echo $count; ?>">&nbsp;</td>
+                        <!-- hide while implementing this Chamilo -->
+                        <!--<td class="docInfo" id="tdth<?php// echo $count; ?>"><?php //echo @date(DATE_TIME_FORMAT,$file['mtime']); ?></td> -->
+                    </tr>
+                <?php
+                }
 
-			}//end if hidden files and folders deleted by Chamilo
+            }
+            //end if hidden files and folders deleted by Chamilo
 
-			$count++;
-		}
-	?>
-</tbody>
-</table>
+            $count++;
+        }
+        ?>
+        </tbody>
+    </table>
 </div>

+ 143 - 83
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/_ajax_get_thumbnail_listing.php

@@ -1,64 +1,81 @@
-<div id="content">
-    <?php
-    $count = 1;
-    $thumbnailBaseUrl = CONFIG_URL_IMG_THUMBNAIL;
-
-    foreach ($fileList as $file) {
-
-        ///First step for hidden some type of Chamilo files and folders
-        //Juan Carlos Raña Trabado
-        //hidden files and folders deleted by Chamilo. Hidde folders css, hotpotatoes, chat, certificates
-        $deleted_by_chamilo_file = ' DELETED '; // ' DELETED ' not '_DELETED_' because in $file['name'] _ is replaced with blank see class.manager.php
-        $deleted_by_chamilo_folder = '_DELETED_';
-        $css_folder_chamilo = 'css';
-        $hotpotatoes_folder_chamilo = 'HotPotatoes_files';
-        $chat_files_chamilo = 'chat_files';
-        $certificates_chamilo = 'certificates';
-        //hidden directory of the group if the user is not a member of the group
-        $group_folder = '_groupdocs';
-
-
-        //show group's directory only if I'm member. Or I'm a teacher
-        $show_doc_group = true;
-
-        if (preg_match("/$group_folder/", $file['path'])) {
-            $show_doc_group = false;
-            if ($is_user_in_group || ( $to_group_id != 0 && api_is_allowed_to_edit())) {
-                $show_doc_group = true;
-            }
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+echo '<div id="content">';
+$count = 1;
+$thumbnailBaseUrl = CONFIG_URL_IMG_THUMBNAIL;
+
+foreach ($fileList as $file) {
+
+    ///First step for hidden some type of Chamilo files and folders
+    //Juan Carlos Raña Trabado
+    //hidden files and folders deleted by Chamilo. Hidde folders css, hotpotatoes, chat, certificates
+    $deleted_by_chamilo_file    = ' DELETED '; // ' DELETED ' not '_DELETED_' because in $file['name'] _ is replaced with blank see class.manager.php
+    $deleted_by_chamilo_folder  = '_DELETED_';
+    $css_folder_chamilo         = 'css';
+    $hotpotatoes_folder_chamilo = 'HotPotatoes_files';
+    $chat_files_chamilo         = 'chat_files';
+    $certificates_chamilo       = 'certificates';
+    //hidden directory of the group if the user is not a member of the group
+    $group_folder = '_groupdocs';
+
+
+    //show group's directory only if I'm member. Or I'm a teacher
+    $show_doc_group = true;
+
+    if (preg_match("/$group_folder/", $file['path'])) {
+        $show_doc_group = false;
+        if ($is_user_in_group || ($to_group_id != 0 && api_is_allowed_to_edit())) {
+            $show_doc_group = true;
         }
+    }
 
-        //show icon sharedfolder
-        $shared_folder = 'shared folder';  //'shared folder' not 'shared_folder' because  in $file['name'] _ is replaced with blank see class.manager.php
-        ///Second step: hiding as the case
-        //Juan Carlos Raña Trabado
-        if ((!preg_match("/$deleted_by_chamilo_file/", $file['name']) &&
+    //show icon sharedfolder
+    $shared_folder = 'shared folder'; //'shared folder' not 'shared_folder' because  in $file['name'] _ is replaced with blank see class.manager.php
+    ///Second step: hiding as the case
+    //Juan Carlos Raña Trabado
+    if ((!preg_match("/$deleted_by_chamilo_file/", $file['name']) &&
             !preg_match("/$deleted_by_chamilo_folder/", $file['path'])) &&
-            !preg_match("/$css_folder_chamilo/", $file['path']) &&
-            !preg_match("/$hotpotatoes_folder_chamilo/", $file['path']) &&
-            !preg_match("/$chat_files_chamilo/", $file['path']) &&
-            !preg_match("/$certificates_chamilo/", $file['path']) && $show_doc_group && $file['name'][0] != '.') {
-            //hide Nanogong  tag
-            if (strpos($file['path'], '_chnano_')) {
-                $file['path'] = substr_replace($file['path'], '.wav', -12); //into real file name
-                $file['name'] = substr_replace($file['name'], '.wav', -12); //into web name
-            }
-            ?>
-            <dl class="thumbnailListing" id="dl<?php echo $count; ?>">
+        !preg_match("/$css_folder_chamilo/", $file['path']) &&
+        !preg_match("/$hotpotatoes_folder_chamilo/", $file['path']) &&
+        !preg_match("/$chat_files_chamilo/", $file['path']) &&
+        !preg_match("/$certificates_chamilo/", $file['path']) && $show_doc_group && $file['name'][0] != '.'
+    ) {
+        //hide Nanogong  tag
+        if (strpos($file['path'], '_chnano_')) {
+            $file['path'] = substr_replace($file['path'], '.wav', -12); //into real file name
+            $file['name'] = substr_replace($file['name'], '.wav', -12); //into web name
+        }
+        ?>
+        <dl class="thumbnailListing" id="dl<?php echo $count; ?>">
             <?php
             if (preg_match('/shared_folder/', basename($file['path']))) {
-                //add icon into ajaxfilemanager if sharedfolder is in Chamilo
-                ?>
-                    <dt id="dt<?php echo $count; ?>" class="<?php echo ($file['type'] == 'folder' || empty($file['file']) || empty($file['subdir']) ? 'folderShared' : $file['cssClass']); ?>" class="<?php echo $file['cssClass']; ?>">
-                    <?php
+            //add icon into ajaxfilemanager if sharedfolder is in Chamilo
+            ?>
+            <dt id="dt<?php echo $count; ?>"
+                class="<?php echo($file['type'] == 'folder' || empty($file['file']) || empty($file['subdir']) ? 'folderShared' : $file['cssClass']); ?>"
+                class="<?php echo $file['cssClass']; ?>">
+                <?php
                 } elseif (preg_match('/sf_user_/', basename($file['path']))) {
-                    ?>
-                    <dt id="dt<?php echo $count; ?>" class="<?php echo ($file['type'] == 'folder' || empty($file['file']) || empty($file['subdir']) ? 'unknownUser' : $file['cssClass']); ?>" class="<?php echo $file['cssClass']; ?>">
-                    <?php
+                ?>
+            <dt id="dt<?php echo $count; ?>"
+                class="<?php echo($file['type'] == 'folder' || empty($file['file']) || empty($file['subdir']) ? 'unknownUser' : $file['cssClass']); ?>"
+                class="<?php echo $file['cssClass']; ?>">
+                <?php
                 } else {
-                    ?>
-                    <dt id="dt<?php echo $count; ?>" class="<?php echo ($file['type'] == 'folder' && empty($file['file']) && empty($file['subdir']) ? 'folderEmpty' : $file['cssClass']); ?>" class="<?php echo $file['cssClass']; ?>">
-                    <?php
+                ?>
+            <dt id="dt<?php echo $count; ?>"
+                class="<?php echo($file['type'] == 'folder' && empty($file['file']) && empty($file['subdir']) ? 'folderEmpty' : $file['cssClass']); ?>"
+                class="<?php echo $file['cssClass']; ?>">
+                <?php
                 }
                 switch ($file['cssClass']) {
                     case 'filePicture':
@@ -66,10 +83,10 @@
                         /* Chamilo create  thumbnail */
                         //setting
                         $allowed_thumbnail_types = array('jpg', 'jpeg', 'gif', 'png');
-                        $max_thumbnail_width = 100;
-                        $max_thumbnail_height = 100;
-                        $png_compression = 0; //0(none)-9
-                        $jpg_quality = 75; //from 0 to 100 (default is 75). More quality less compression
+                        $max_thumbnail_width     = 100;
+                        $max_thumbnail_height    = 100;
+                        $png_compression         = 0; //0(none)-9
+                        $jpg_quality             = 75; //from 0 to 100 (default is 75). More quality less compression
 
                         $directory_thumbnails = dirname($file['path']).'/.thumbs/';
 
@@ -79,18 +96,22 @@
 
                         //create thumbnails
 
-                        $image = $file['path'];
+                        $image           = $file['path'];
                         $image_thumbnail = $directory_thumbnails.'.'.basename($file['path']);
 
                         if (file_exists($image)) {
                             //check thumbnail
                             $imagetype = explode(".", $image);
-                            $imagetype = strtolower($imagetype[count($imagetype) - 1]); //or check $imagetype = image_type_to_extension(exif_imagetype($image), false);
+                            $imagetype = strtolower(
+                                $imagetype[count($imagetype) - 1]
+                            ); //or check $imagetype = image_type_to_extension(exif_imagetype($image), false);
 
                             if (in_array($imagetype, $allowed_thumbnail_types)) {
 
                                 if (!file_exists($image_thumbnail)) {
-                                    $original_image_size = api_getimagesize($image); //run each once we view thumbnails is too heavy, then need move into  !file_exists($image_thumbnail, and only run when haven't the thumbnail
+                                    $original_image_size = api_getimagesize(
+                                        $image
+                                    ); //run each once we view thumbnails is too heavy, then need move into  !file_exists($image_thumbnail, and only run when haven't the thumbnail
 
                                     switch ($imagetype) {
                                         case 'gif':
@@ -107,14 +128,22 @@
                                             break;
                                     }
 
-                                    $new_thumbnail_size = api_calculate_image_size($original_image_size['width'], $original_image_size['height'], $max_thumbnail_width, $max_thumbnail_height);
+                                    $new_thumbnail_size = api_calculate_image_size(
+                                        $original_image_size['width'],
+                                        $original_image_size['height'],
+                                        $max_thumbnail_width,
+                                        $max_thumbnail_height
+                                    );
 
                                     if ($max_thumbnail_width > $original_image_size['width'] && $max_thumbnail_height > $original_image_size['height']) {
-                                        $new_thumbnail_size['width'] = $original_image_size['width'];
+                                        $new_thumbnail_size['width']  = $original_image_size['width'];
                                         $new_thumbnail_size['height'] = $original_image_size['height'];
                                     }
 
-                                    $crop = imagecreatetruecolor($new_thumbnail_size['width'], $new_thumbnail_size['height']);
+                                    $crop = imagecreatetruecolor(
+                                        $new_thumbnail_size['width'],
+                                        $new_thumbnail_size['height']
+                                    );
 
                                     // preserve transparency
                                     if ($imagetype == "png") {
@@ -129,15 +158,32 @@
 
                                         //GIF89a for transparent and anim (first clip), either GIF87a
                                         if ($transindex >= 0 && $transindex < $palletsize) {
-                                            $transcol = imagecolorsforindex($source_img, $transindex);
-                                            $transindex = imagecolorallocatealpha($crop, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
+                                            $transcol   = imagecolorsforindex($source_img, $transindex);
+                                            $transindex = imagecolorallocatealpha(
+                                                $crop,
+                                                $transcol['red'],
+                                                $transcol['green'],
+                                                $transcol['blue'],
+                                                127
+                                            );
                                             imagefill($crop, 0, 0, $transindex);
                                             imagecolortransparent($crop, $transindex);
                                         }
                                     }
 
                                     //resampled image
-                                    imagecopyresampled($crop, $source_img, 0, 0, 0, 0, $new_thumbnail_size['width'], $new_thumbnail_size['height'], $original_image_size['width'], $original_image_size['height']);
+                                    imagecopyresampled(
+                                        $crop,
+                                        $source_img,
+                                        0,
+                                        0,
+                                        0,
+                                        0,
+                                        $new_thumbnail_size['width'],
+                                        $new_thumbnail_size['height'],
+                                        $original_image_size['width'],
+                                        $original_image_size['height']
+                                    );
 
                                     switch ($imagetype) {
                                         case 'gif':
@@ -156,14 +202,23 @@
 
                                     //clean memory
                                     imagedestroy($crop);
-                                }//end !exist thumbnail
+                                }
+                                //end !exist thumbnail
                                 //show thumbnail
-                                echo '<img src="'.appendQueryString($thumbnailBaseUrl, ' path='.base64_encode($image_thumbnail)).'" id="thumbImg'.$count.'"></a>'."\n";
+                                echo '<img src="'.appendQueryString(
+                                        $thumbnailBaseUrl,
+                                        ' path='.base64_encode($image_thumbnail)
+                                    ).'" id="thumbImg'.$count.'"></a>'."\n";
                             } else {
 
-                                echo '<img src="'.appendQueryString($thumbnailBaseUrl, ' path='.base64_encode($file['path'])).'" id="thumbImg'.$count.'"></a>'."\n";
-                            }//end allowed image types
-                        }//end if exist file image
+                                echo '<img src="'.appendQueryString(
+                                        $thumbnailBaseUrl,
+                                        ' path='.base64_encode($file['path'])
+                                    ).'" id="thumbImg'.$count.'"></a>'."\n";
+                            }
+                            //end allowed image types
+                        }
+                        //end if exist file image
                         ///////////////////////////////////////// End Chamilo create  thumbnail
 
                         break;
@@ -181,17 +236,22 @@
                     $path_chamilo_file = $file['path'];
                 }
                 ?>
-                </dt>
-                <dd id="dd<?php echo $count; ?>" class="thumbnailListing_info">
-                    <span id="flag<?php echo $count; ?>" class="<?php echo $file['flag']; ?>">&nbsp;</span>
-                    <input id="cb<?php echo $count; ?>" type="checkbox" name="check[]" <?php echo ($file['is_writable'] ? '' : 'disabled'); ?> class="radio" value="<?php echo $file['path']; ?>" />
-                    <a <?php echo ($file['cssClass'] == 'filePicture' ? 'rel="orgImg"' : ''); ?> href="<?php echo $path_chamilo_file; // fix for Chamilo ?>" title="<?php echo $file['name']; ?>" id="a<?php echo $count; ?>">
-                <?php echo shortenFileName($file['name']); ?>
-                    </a>
-                </dd>
-            </dl>
-        <?php
-    }//end if hidden files and folders deleted by Chamilo
+            </dt>
+            <dd id="dd<?php echo $count; ?>" class="thumbnailListing_info">
+                <span id="flag<?php echo $count; ?>" class="<?php echo $file['flag']; ?>">&nbsp;</span>
+                <input id="cb<?php echo $count; ?>" type="checkbox"
+                       name="check[]" <?php echo($file['is_writable'] ? '' : 'disabled'); ?> class="radio"
+                       value="<?php echo $file['path']; ?>"/>
+                <a <?php echo($file['cssClass'] == 'filePicture' ? 'rel="orgImg"' : ''); ?>
+                    href="<?php echo $path_chamilo_file; // fix for Chamilo ?>" title="<?php echo $file['name']; ?>"
+                    id="a<?php echo $count; ?>">
+                    <?php echo shortenFileName($file['name']); ?>
+                </a>
+            </dd>
+        </dl>
+    <?php
+    }
+    //end if hidden files and folders deleted by Chamilo
     $count++;
 }
 ?>

+ 17 - 11
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/_ajax_load_folders.php

@@ -1,15 +1,21 @@
 <?php
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
 ?>
 <select class="input inputSearch" name="search_folder" id="search_folder">
-	<?php 
-	
-					foreach(getFolderListing(CONFIG_SYS_ROOT_PATH) as $k=>$v)
-					{
-						?>
-      <option value="<?php echo $v; ?>" ><?php echo shortenFileName($k, 30); ?></option>
-      <?php 
-					}
-		
-				?>            	
+    <?php
+    foreach (getFolderListing(CONFIG_SYS_ROOT_PATH) as $k => $v) {
+        ?>
+        <option value="<?php echo $v; ?>"><?php echo shortenFileName($k, 30); ?></option>
+    <?php
+    }
+    ?>
 </select>

+ 82 - 56
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_create_folder.php

@@ -1,26 +1,25 @@
 <?php
-
+/* For licensing terms, see /license.txt */
 /**
- * create a folder
  * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
  * @link www.phpletter.com
- * @since 22/May/2007
+ * @since 22/April/2007
  *
- * Modify for Chamilo
- * @author Juan Carlos Ra�a
- * @since 18/January/2009
  */
-require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-//@ob_start(); //Disabled for integration with Chamilo
-//displayArray($_POST); //Disabled for integration with Chamilo
-//writeInfo(@ob_get_clean()); //Disabled for integration with Chamilo
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
 echo "{";
 $error = "";
-$info = "";
+$info  = "";
 /* 	$_POST['new_folder'] = substr(md5(time()), 1, 5);
   $_POST['currentFolderPath'] = "../../uploaded/"; */
-$_POST['new_folder'] = htmlentities($_POST['new_folder'], ENT_QUOTES); //Chamilo improve security
-$_POST['new_folder'] = str_replace(' ', '_', $_POST['new_folder']); //Interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
+$_POST['new_folder']        = htmlentities($_POST['new_folder'], ENT_QUOTES); //Chamilo improve security
+$_POST['new_folder']        = str_replace(
+    ' ',
+    '_',
+    $_POST['new_folder']
+); //Interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
 $_POST['currentFolderPath'] = htmlentities($_POST['currentFolderPath'], ENT_QUOTES); //Chamilo improve security
 
 if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_NEWFOLDER) {
@@ -29,55 +28,82 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_NEWFOLDER) {
     $error = ERR_FOLDER_NAME_EMPTY;
 } elseif (!preg_match("/^[a-zA-Z0-9_\- ]+$/", $_POST['new_folder'])) {
     $error = ERR_FOLDER_FORMAT;
-} else if (empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath'])) {
-    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
-} elseif (file_exists(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'])) {
-    $error = ERR_FOLDER_EXISTS;
 } else {
-    include_once CLASS_FILE;
-    $file = new file();
-    if ($file->mkdir(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'], 0775)) {
-        include_once CLASS_MANAGER;
-        $manager = new manager(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'], false);
-        $pathInfo = $manager->getFolderInfo(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder']);
+    if (empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath'])) {
+        $error = ERR_FOLDER_PATH_NOT_ALLOWED;
+    } elseif (file_exists(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder'])) {
+        $error = ERR_FOLDER_EXISTS;
+    } else {
+        include_once CLASS_FILE;
+        $file = new file();
+        if ($file->mkdir(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder'], 0775)) {
+            include_once CLASS_MANAGER;
+            $manager  = new manager(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder'], false);
+            $pathInfo = $manager->getFolderInfo(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder']);
 
-        //bridge to Chamilo
-        if (!empty($_course['path'])) {
-            //only inside courses
-            $mainPath = '../../../../../../../courses/' . $_course['path'] . '/document/'; //get Chamilo
-            $fullPath = $_POST['currentFolderPath'] . $_POST['new_folder']; //get Ajaxfilemanager
-            $chamiloPath = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1);
-            $_POST['new_folder'] = str_replace('_', ' ', $_POST['new_folder']); //Restore for interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
-            $chamiloFile = $_POST['new_folder']; //get Ajaxfilemanager
+            //bridge to Chamilo
+            if (!empty($_course['path'])) {
+                //only inside courses
+                $mainPath            = '../../../../../../../courses/'.$_course['path'].'/document/'; //get Chamilo
+                $fullPath            = $_POST['currentFolderPath'].$_POST['new_folder']; //get Ajaxfilemanager
+                $chamiloPath         = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1);
+                $_POST['new_folder'] = str_replace(
+                    '_',
+                    ' ',
+                    $_POST['new_folder']
+                ); //Restore for interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
+                $chamiloFile         = $_POST['new_folder']; //get Ajaxfilemanager
 
-            $doc_id = add_document($_course, $chamiloPath, 'folder', 0, $chamiloFile); //get Chamilo
-            $current_session_id = api_get_session_id(); //get Chamilo
-            api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
-            api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
-        }
-        // end bridge to Chamilo
+                $doc_id             = add_document($_course, $chamiloPath, 'folder', 0, $chamiloFile); //get Chamilo
+                $current_session_id = api_get_session_id(); //get Chamilo
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'FolderCreated',
+                    api_get_user_id(),
+                    $to_group_id,
+                    null,
+                    null,
+                    null,
+                    $current_session_id
+                ); //get Chamilo
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'invisible',
+                    api_get_user_id(),
+                    $to_group_id,
+                    null,
+                    null,
+                    null,
+                    $current_session_id
+                ); //get Chamilo
+            }
+            // end bridge to Chamilo
 
-        foreach ($pathInfo as $k => $v) {
-            switch ($k) {
-                case "ctime";
-                case "mtime":
-                case "atime":
-                    $v = date(DATE_TIME_FORMAT, $v);
-                    break;
-                case 'name':
-                    $info .= sprintf(", %s:'%s'", 'short_name', shortenFileName($v));
-                    break;
-                case 'cssClass':
-                    $v = 'folderEmpty';
-                    break;
+            foreach ($pathInfo as $k => $v) {
+                switch ($k) {
+                    case "ctime";
+                    case "mtime":
+                    case "atime":
+                        $v = date(DATE_TIME_FORMAT, $v);
+                        break;
+                    case 'name':
+                        $info .= sprintf(", %s:'%s'", 'short_name', shortenFileName($v));
+                        break;
+                    case 'cssClass':
+                        $v = 'folderEmpty';
+                        break;
+                }
+                $info .= sprintf(", %s:'%s'", $k, $v);
             }
-            $info .= sprintf(", %s:'%s'", $k, $v);
+        } else {
+            $error = ERR_FOLDER_CREATION_FAILED;
         }
-    } else {
-        $error = ERR_FOLDER_CREATION_FAILED;
     }
-    //$error = "For security reason, folder creation function has been disabled.";
 }
-echo "error:'" . $error . "'";
+echo "error:'".$error."'";
 echo $info;
-echo "}";
+echo "}";

+ 14 - 7
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_delete_file.php

@@ -1,15 +1,14 @@
 <?php
+/* For licensing terms, see /license.txt */
 /**
- * delete selected files
  * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
  * @link www.phpletter.com
  * @since 22/April/2007
  *
- * Modify for Chamilo
- * @author Juan Carlos Ra�a
- * @since 19/March/2009
  */
-require_once dirname(__FILE__).DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."config.php";
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
 $error = "";
 if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
     $error = SYS_DISABLED;
@@ -59,7 +58,11 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
                 }
             } else {
                 $file->delete(addTrailingSlash(backslashToSlash($_GET['delete']))); //deleted by ajaxfilemanager
-                event_system(LOG_USER_PERSONAL_DOC_DELETED, 'document_path', addTrailingSlash(backslashToSlash($_GET['delete'])));
+                event_system(
+                    LOG_USER_PERSONAL_DOC_DELETED,
+                    'document_path',
+                    addTrailingSlash(backslashToSlash($_GET['delete']))
+                );
             }
             //////end bridge to Chamilo
             $file->delete(addTrailingSlash(backslashToSlash($_GET['delete'])));
@@ -150,7 +153,11 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
                         }
                     } else {
                         $file->delete(addTrailingSlash(backslashToSlash($doc))); //deleted by ajaxfilemanager
-                        event_system(LOG_USER_PERSONAL_DOC_DELETED, 'document_path', addTrailingSlash(backslashToSlash($doc)));
+                        event_system(
+                            LOG_USER_PERSONAL_DOC_DELETED,
+                            'document_path',
+                            addTrailingSlash(backslashToSlash($doc))
+                        );
                     }
                     //////end bridge to Chamilo
                 } elseif (is_file($doc)

+ 28 - 30
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_download.php

@@ -1,32 +1,30 @@
 <?php
-	/**
-	 * delete selected files
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/April/2007
-	 *
-	 */
+/* For licensing terms, see /license.txt */
 
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	if(!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path']) && isUnderRoot($_GET['path']))
-	{
-			
-			$path = $_GET['path'];
-			//check if the file size
-			$fileSize = @filesize($path);
-			
-			if($fileSize > getMemoryLimit())
-			{//larger then the php memory limit, redirect to the file
-				
-				header('Location: ' . $path);
-				exit;				 
-			}else 
-			{//open it up and send out with php 
-				downloadFile($path);	
-				 			
-			}
-	}else 
-	{
-		die(ERR_DOWNLOAD_FILE_NOT_FOUND);
-	}
-?>
+/**
+ * delete selected files
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+if (!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path']) && isUnderRoot($_GET['path'])) {
+
+    $path = $_GET['path'];
+    //check if the file size
+    $fileSize = @filesize($path);
+
+    if ($fileSize > getMemoryLimit()) {
+        //larger then the php memory limit, redirect to the file
+        header('Location: '.$path);
+        exit;
+    } else { //open it up and send out with php
+        downloadFile($path);
+    }
+} else {
+    die(ERR_DOWNLOAD_FILE_NOT_FOUND);
+}

+ 107 - 115
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_editor_reset.php

@@ -1,116 +1,108 @@
 <?php
-	/**
-	 * reset the image
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");	
-	if(!isset($_POST['path']))
-	{
-		$_POST['path'] = "uploaded/Winter.jpg" .  "?" . makeQueryString(array('path'));
-		//for crop
-		$_POST['mode'] = "crop";
-		$_POST['x'] = 100;
-		$_POST['y'] = 100;
-		$imageInfo = @GetImageSize($_POST['path']);
-		$_POST['width'] = $imageInfo[0];
-		$_POST['height'] = $imageInfo[1];
-		
-	}
-	initSessionHistory($_POST['path']);
-	
-	echo "{";
-	$error = "";
-	$info = "";
-	
-	if(empty($_POST['path']))
-	{
-		$error  =  IMG_SAVE_EMPTY_PATH;
-	}elseif(!file_exists($_POST['path']))
-	{
-		$error  =  IMG_SAVE_NOT_EXISTS;
-	}else if(!isUnderRoot($_POST['path']))
-	{
-		$error = IMG_SAVE_PATH_DISALLOWED;
-	}
-	else
-	{
-		if(!empty($_POST['mode']))
-		{
-			
-			include_once(CLASS_IMAGE);
-			$image = new ImageAjaxFileManager();
-			$image->loadImage($_POST['path']);
-			
-			switch($_POST['mode'])
-			{
-				case "resize":					
-					if(!$image->resize($_POST['width'], $_POST['height'], (!empty($_POST['constraint'])?true:false)))
-					{
-						$error = IMG_SAVE_RESIZE_FAILED;
-					}					
-					break;
-				case "crop":
-					if(!$image->cropToDimensions($_POST['x'], $_POST['y'], intval($_POST['x']) + intval($_POST['width']), intval($_POST['y']) + intval($_POST['height'])))
-					{
-						$error = IMG_SAVE_CROP_FAILED;
-					}
-					
-					break;
-				case "flip":
-					if(!$image->flip($_POST['flip_angle']))
-					{
-						$error = IMG_SAVE_FLIP_FAILED;
-					}
-					break;
-				case "rotate":
-					if(!$image->rotate(intval($_POST['angle'])))
-					{
-						$error = IMG_SAVE_ROTATE_FAILED;
-					}
-					break;
-				default:
-					$error = IMG_SAVE_UNKNOWN_MODE;
-			}
-			if(empty($error))
-			{
-				
-				$sessionNewPath = $session->getSessionDir() . uniqid(md5(time())) . "." . getFileExt($_POST['path']);
-				if(!@copy($_POST['path'], $sessionNewPath))
-				{
-					$error = IMG_SAVE_BACKUP_FAILED;
-				}else 
-				{
-					addSessionHistory($_POST['path'], $sessionNewPath);
-					if($image->saveImage($_POST['path']))
-					{						
-						$imageInfo = $image->getFinalImageInfo();	
-						$info .= ",width:" . $imageInfo['width'] . "\n";
-						$info .= ",height:" . $imageInfo['height'] . "\n";
-						$info .= ",size:'" . transformFileSize($imageInfo['size']) . "'\n";
-					}else 
-					{
-						$error = IMG_SAVE_FAILED;
-					}			
-				}				
-			}else 
-			{
-				//$image->DestroyImages();
-			}
-		}else 
-		{
-			$error = IMG_SAVE_UNKNOWN_MODE;
-		}
-	}
-	
-	echo "error:'" . $error . "'\n";
-	if(isset($image) && is_object($image))
-	{
-		$image->DestroyImages();
-	}
-	echo $info;
-	echo ",history:" . sizeof($_SESSION[$_POST['path']]) . "\n";
-	echo "}";
-?>
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+if (!isset($_POST['path'])) {
+    $_POST['path'] = "uploaded/Winter.jpg"."?".makeQueryString(array('path'));
+    //for crop
+    $_POST['mode']   = "crop";
+    $_POST['x']      = 100;
+    $_POST['y']      = 100;
+    $imageInfo       = @GetImageSize($_POST['path']);
+    $_POST['width']  = $imageInfo[0];
+    $_POST['height'] = $imageInfo[1];
+
+}
+initSessionHistory($_POST['path']);
+
+echo "{";
+$error = "";
+$info  = "";
+
+if (empty($_POST['path'])) {
+    $error = IMG_SAVE_EMPTY_PATH;
+} elseif (!file_exists($_POST['path'])) {
+    $error = IMG_SAVE_NOT_EXISTS;
+} else {
+    if (!isUnderRoot($_POST['path'])) {
+        $error = IMG_SAVE_PATH_DISALLOWED;
+    } else {
+        if (!empty($_POST['mode'])) {
+
+            include_once(CLASS_IMAGE);
+            $image = new ImageAjaxFileManager();
+            $image->loadImage($_POST['path']);
+
+            switch ($_POST['mode']) {
+                case "resize":
+                    if (!$image->resize(
+                        $_POST['width'],
+                        $_POST['height'],
+                        (!empty($_POST['constraint']) ? true : false)
+                    )
+                    ) {
+                        $error = IMG_SAVE_RESIZE_FAILED;
+                    }
+                    break;
+                case "crop":
+                    if (!$image->cropToDimensions(
+                        $_POST['x'],
+                        $_POST['y'],
+                        intval($_POST['x']) + intval($_POST['width']),
+                        intval($_POST['y']) + intval($_POST['height'])
+                    )
+                    ) {
+                        $error = IMG_SAVE_CROP_FAILED;
+                    }
+
+                    break;
+                case "flip":
+                    if (!$image->flip($_POST['flip_angle'])) {
+                        $error = IMG_SAVE_FLIP_FAILED;
+                    }
+                    break;
+                case "rotate":
+                    if (!$image->rotate(intval($_POST['angle']))) {
+                        $error = IMG_SAVE_ROTATE_FAILED;
+                    }
+                    break;
+                default:
+                    $error = IMG_SAVE_UNKNOWN_MODE;
+            }
+            if (empty($error)) {
+
+                $sessionNewPath = $session->getSessionDir().uniqid(md5(time())).".".getFileExt($_POST['path']);
+                if (!@copy($_POST['path'], $sessionNewPath)) {
+                    $error = IMG_SAVE_BACKUP_FAILED;
+                } else {
+                    addSessionHistory($_POST['path'], $sessionNewPath);
+                    if ($image->saveImage($_POST['path'])) {
+                        $imageInfo = $image->getFinalImageInfo();
+                        $info .= ",width:".$imageInfo['width']."\n";
+                        $info .= ",height:".$imageInfo['height']."\n";
+                        $info .= ",size:'".transformFileSize($imageInfo['size'])."'\n";
+                    } else {
+                        $error = IMG_SAVE_FAILED;
+                    }
+                }
+            }
+        } else {
+            $error = IMG_SAVE_UNKNOWN_MODE;
+        }
+    }
+}
+
+echo "error:'".$error."'\n";
+if (isset($image) && is_object($image)) {
+    $image->DestroyImages();
+}
+echo $info;
+echo ",history:".sizeof($_SESSION[$_POST['path']])."\n";
+echo "}";

+ 26 - 32
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_copy.php

@@ -1,34 +1,28 @@
 <?php
-	/**
-	 * copy file
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
 
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	$error = "";
-	$info = '';
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_COPY)
-	{
-		$error = SYS_DISABLED;
-	}
-	elseif(!isset($_POST['selectedDoc']) || !is_array($_POST['selectedDoc']) || sizeof($_POST['selectedDoc']) < 1)
-	{
-		$error = ERR_NOT_DOC_SELECTED_FOR_COPY;
-	}
-	elseif(empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath']))
-	{
-		$error = ERR_FOLDER_PATH_NOT_ALLOWED;
-	}else 
-	{		
-		require_once(CLASS_SESSION_ACTION);
-		$sessionAction = new SessionAction();
-		$sessionAction->setAction($_POST['action_value']);
-		$sessionAction->setFolder($_POST['currentFolderPath']);
-		$sessionAction->set($_POST['selectedDoc']);
-		$info = ',num:' . sizeof($_POST['selectedDoc']);
-	}
-	echo "{error:'" . $error .  "'\n" . $info . "}";
-?>
+$error = "";
+$info  = '';
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_COPY) {
+    $error = SYS_DISABLED;
+} elseif (!isset($_POST['selectedDoc']) || !is_array($_POST['selectedDoc']) || sizeof($_POST['selectedDoc']) < 1) {
+    $error = ERR_NOT_DOC_SELECTED_FOR_COPY;
+} elseif (empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath'])) {
+    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
+} else {
+    require_once(CLASS_SESSION_ACTION);
+    $sessionAction = new SessionAction();
+    $sessionAction->setAction($_POST['action_value']);
+    $sessionAction->setFolder($_POST['currentFolderPath']);
+    $sessionAction->set($_POST['selectedDoc']);
+    $info = ',num:'.sizeof($_POST['selectedDoc']);
+}
+echo "{error:'".$error."'\n".$info."}";

+ 29 - 32
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_cut.php

@@ -1,33 +1,30 @@
 <?php
-	/**
-	 * cut file
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	$error = "";
-	$info = '';
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_CUT)
-	{
-		$error = SYS_DISABLED;
-	}
-	elseif(!isset($_POST['selectedDoc']) || !is_array($_POST['selectedDoc']) || sizeof($_POST['selectedDoc']) < 1)
-	{
-		$error = ERR_NOT_DOC_SELECTED_FOR_CUT;
-	}
-	elseif(empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath']))
-	{
-		$error = ERR_FOLDER_PATH_NOT_ALLOWED;
-	}else 
-	{		
-		require_once(CLASS_SESSION_ACTION);
-		$sessionAction = new SessionAction();
-		$sessionAction->setAction($_POST['action_value']);
-		$sessionAction->setFolder($_POST['currentFolderPath']);
-		$sessionAction->set($_POST['selectedDoc']);
-		$info = ',num:' . sizeof($_POST['selectedDoc']);
-	}
-	echo "{error:'" . $error .  "'\n" . $info . "}";
-?>
+/* For licensing terms, see /license.txt */
+/**
+ * cut file
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/May/2007
+ *
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+$error = "";
+$info  = '';
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_CUT) {
+    $error = SYS_DISABLED;
+} elseif (!isset($_POST['selectedDoc']) || !is_array($_POST['selectedDoc']) || sizeof($_POST['selectedDoc']) < 1) {
+    $error = ERR_NOT_DOC_SELECTED_FOR_CUT;
+} elseif (empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath'])) {
+    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
+} else {
+    require_once(CLASS_SESSION_ACTION);
+    $sessionAction = new SessionAction();
+    $sessionAction->setAction($_POST['action_value']);
+    $sessionAction->setFolder($_POST['currentFolderPath']);
+    $sessionAction->set($_POST['selectedDoc']);
+    $info = ',num:'.sizeof($_POST['selectedDoc']);
+}
+echo "{error:'".$error."'\n".$info."}";

+ 211 - 62
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_paste.php

@@ -1,8 +1,16 @@
 <?php
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
 
-include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."config.php");
-$error = '';
-$fileMoved = array();
+$error                   = '';
+$fileMoved               = array();
 $unmovedDocDueToSamePath = array();
 if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
     $error = SYS_DISABLED;
@@ -48,9 +56,9 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                     if ($file->copyTo($doc, $_GET['current_folder_path'])) {
 
                         $finalPath = $destFolderPath.basename($doc);
-                        $objFile = new file($finalPath);
-                        $tem = $objFile->getFileInfo();
-                        $obj = new manager($finalPath, false);
+                        $objFile   = new file($finalPath);
+                        $tem       = $objFile->getFileInfo();
+                        $obj       = new manager($finalPath, false);
 
                         $fileType = $obj->getFileType($finalPath, (is_dir($finalPath) ? true : false));
 
@@ -68,13 +76,13 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                           } */
 
                         $tem['final_path'] = $finalPath;
-                        $tem['path'] = backslashToSlash($finalPath);
-                        $tem['type'] = (is_dir($finalPath) ? 'folder' : 'file');
-                        $tem['size'] = @transformFileSize($tem['size']);
-                        $tem['ctime'] = date(DATE_TIME_FORMAT, $tem['ctime']);
-                        $tem['mtime'] = date(DATE_TIME_FORMAT, $tem['mtime']);
-                        $tem['flag'] = 'noFlag';
-                        $tem['url'] = getFileUrl($doc);
+                        $tem['path']       = backslashToSlash($finalPath);
+                        $tem['type']       = (is_dir($finalPath) ? 'folder' : 'file');
+                        $tem['size']       = @transformFileSize($tem['size']);
+                        $tem['ctime']      = date(DATE_TIME_FORMAT, $tem['ctime']);
+                        $tem['mtime']      = date(DATE_TIME_FORMAT, $tem['mtime']);
+                        $tem['flag']       = 'noFlag';
+                        $tem['url']        = getFileUrl($doc);
 
                         /**
                          * Bridge to Chamilo documents tool
@@ -82,10 +90,15 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                          */
                         if (!empty($_course['path'])) {
 
-                            $mainPath = getParentFolderPath($folderInfo['path']); // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/
-                            $fullPath = $tem['final_path']; // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/icons/book_highlight.jpg
-                            $chamiloFolder = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1); // sample /icons/book_highlight.jpg or /icons
-                            $chamiloFile = $tem['name']; //get ajaxmanager
+                            $mainPath        = getParentFolderPath(
+                                $folderInfo['path']
+                            ); // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/
+                            $fullPath        = $tem['final_path']; // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/icons/book_highlight.jpg
+                            $chamiloFolder   = substr(
+                                $fullPath,
+                                strlen($mainPath) - strlen($fullPath) - 1
+                            ); // sample /icons/book_highlight.jpg or /icons
+                            $chamiloFile     = $tem['name']; //get ajaxmanager
                             $chamiloFileSize = filesize($fullPath); //get ajaxmanager
                             if (!empty($group_properties['directory'])) {
                                 $chamiloFolder = $group_properties['directory'].$chamiloFolder; //get Chamilo
@@ -95,25 +108,43 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                 $full_old_path = $doc; // get from ajaxfilemanager sample ../../../../../../../courses/TEST/document/book_highlight.jpg or if you select a folder: ../../../../../../../courses/TEST/document/trainer/
                                 if (is_dir($full_old_path)) {
                                     //update first folder
-                                    $old_path = substr($full_old_path, strlen($mainPath) - strlen($full_old_path) - 1, -1);
+                                    $old_path = substr(
+                                        $full_old_path,
+                                        strlen($mainPath) - strlen($full_old_path) - 1,
+                                        -1
+                                    );
                                     if (!empty($group_properties['directory'])) {
                                         $old_path = $group_properties['directory'].$old_path; //get Chamilo
                                     }
                                     $new_path = $chamiloFolder; //sample /images
-                                    $dbTable = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
+                                    $dbTable  = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
                                     update_db_info('update', $old_path, $new_path); //Chamilo
-                                    $curdirpath = $new_path;
-                                    $doc_id = DocumentManager::get_document_id($_course, $curdirpath); //Chamilo
+                                    $curdirpath         = $new_path;
+                                    $doc_id             = DocumentManager::get_document_id(
+                                        $_course,
+                                        $curdirpath
+                                    ); //Chamilo
                                     $current_session_id = api_get_session_id();
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'FolderMoved',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
                                     // update database: inside subdirectories and files
-                                    $course_dir = $_course['path']."/document"; //get Chamilo
+                                    $course_dir      = $_course['path']."/document"; //get Chamilo
                                     $sys_course_path = api_get_path(SYS_COURSE_PATH); //get Chamilo
-                                    $base_work_dir = $sys_course_path.$course_dir; // sample c:/xampp/htdocs/chamilo/courses/TEST/document
-                                    $source_dir = $base_work_dir.$chamiloFolder;
+                                    $base_work_dir   = $sys_course_path.$course_dir; // sample c:/xampp/htdocs/chamilo/courses/TEST/document
+                                    $source_dir      = $base_work_dir.$chamiloFolder;
 
                                     //thanks to donovan
-                                    $path = '';
+                                    $path    = '';
                                     $stack[] = $source_dir;
                                     while ($stack) {
                                         $thisdir = array_pop($stack);
@@ -125,7 +156,7 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                                     if (is_file($current_file)) {
                                                         $path[] = "{$thisdir}/{$dircont[$i]}";
                                                     } elseif (is_dir($current_file)) {
-                                                        $path[] = "{$thisdir}/{$dircont[$i]}";
+                                                        $path[]  = "{$thisdir}/{$dircont[$i]}";
                                                         $stack[] = $current_file;
                                                     }
                                                 }
@@ -140,36 +171,74 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                         //Sample $item is C:/xampp/htdocs/chamilo/courses/TEST/document/books/book_highlight.jpg
                                         $file_orig = basename($item);
                                         if ($file_orig[0] != '.' && !in_array($invisibleFileNames)) {
-                                            $source_item = substr($item, (strlen($base_work_dir) - strlen($item))); // sample /books/book_highlight.jpg or /books
-                                            $target_item = $source_item;
+                                            $source_item   = substr(
+                                                $item,
+                                                (strlen($base_work_dir) - strlen($item))
+                                            ); // sample /books/book_highlight.jpg or /books
+                                            $target_item   = $source_item;
                                             $chamiloFolder = $target_item;
-                                            $chamiloFile = basename($target_item);
+                                            $chamiloFile   = basename($target_item);
                                             //
                                             if (is_dir($item)) {
-                                                $old_path = substr($full_old_path, strlen($mainPath) - strlen($full_old_path) - 1, -1);
+                                                $old_path = substr(
+                                                    $full_old_path,
+                                                    strlen($mainPath) - strlen($full_old_path) - 1,
+                                                    -1
+                                                );
                                                 if (!empty($group_properties['directory'])) {
                                                     $old_path = $group_properties['directory'].$old_path; //get Chamilo
                                                 }
                                                 $new_path = $chamiloFolder; //sample /images
-                                                $dbTable = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
+                                                $dbTable  = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
                                                 update_db_info('update', $old_path, $new_path); //Chamilo
-                                                $curdirpath = $new_path;
-                                                $doc_id = DocumentManager::get_document_id($_course, $curdirpath); //Chamilo
+                                                $curdirpath         = $new_path;
+                                                $doc_id             = DocumentManager::get_document_id(
+                                                    $_course,
+                                                    $curdirpath
+                                                ); //Chamilo
                                                 $current_session_id = api_get_session_id();
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'FolderMoved',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                );
                                             } elseif (is_file($item)) {
-                                                $old_path = substr($full_old_path, strlen($mainPath) - strlen($full_old_path) - 1);
+                                                $old_path = substr(
+                                                    $full_old_path,
+                                                    strlen($mainPath) - strlen($full_old_path) - 1
+                                                );
                                                 if (!empty($group_properties['directory'])) {
                                                     $old_path = $group_properties['directory'].$old_path; //get Chamilo
                                                 }
                                                 $new_path = $chamiloFolder; //sample /images/book_highlight.jpg
-                                                $dbTable = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
+                                                $dbTable  = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
                                                 update_db_info('update', $old_path, $new_path); //Chamilo
                                                 //update items
-                                                $curdirpath = $new_path;
-                                                $doc_id = DocumentManager::get_document_id($_course, $curdirpath); //Chamilo
+                                                $curdirpath         = $new_path;
+                                                $doc_id             = DocumentManager::get_document_id(
+                                                    $_course,
+                                                    $curdirpath
+                                                ); //Chamilo
                                                 $current_session_id = api_get_session_id();
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'DocumentMoved',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                );
                                             }
                                         }
                                     }
@@ -183,26 +252,54 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                     $dbTable = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
                                     update_db_info('update', $old_path, $new_path); //Chamilo
                                     //update items
-                                    $curdirpath = $new_path;
-                                    $doc_id = DocumentManager::get_document_id($_course, $curdirpath);
+                                    $curdirpath         = $new_path;
+                                    $doc_id             = DocumentManager::get_document_id($_course, $curdirpath);
                                     $current_session_id = api_get_session_id();
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'DocumentMoved',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
                                 }
                             } else {
                                 $current_session_id = api_get_session_id();
                                 if ($tem['type'] == "folder") {
                                     //add to database the first folder to target
-                                    $doc_id = add_document($_course, $chamiloFolder, 'folder', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                    $doc_id = add_document(
+                                        $_course,
+                                        $chamiloFolder,
+                                        'folder',
+                                        $chamiloFileSize,
+                                        $chamiloFile
+                                    ); //get Chamilo
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'FolderCreated',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    ); //get Chamilo
                                     // add to database inside subdirectories and files
 
-                                    $course_dir = $_course['path']."/document"; //get Chamilo
+                                    $course_dir      = $_course['path']."/document"; //get Chamilo
                                     $sys_course_path = api_get_path(SYS_COURSE_PATH); //get Chamilo
-                                    $base_work_dir = $sys_course_path.$course_dir; // sample c:/xampp/htdocs/chamilo/courses/TEST/document
-                                    $source_dir = $base_work_dir.$chamiloFolder;
+                                    $base_work_dir   = $sys_course_path.$course_dir; // sample c:/xampp/htdocs/chamilo/courses/TEST/document
+                                    $source_dir      = $base_work_dir.$chamiloFolder;
 
                                     //thanks to donovan
-                                    $path = '';
+                                    $path    = '';
                                     $stack[] = $source_dir;
                                     while ($stack) {
                                         $thisdir = array_pop($stack);
@@ -214,7 +311,7 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                                     if (is_file($current_file)) {
                                                         $path[] = "{$thisdir}/{$dircont[$i]}";
                                                     } elseif (is_dir($current_file)) {
-                                                        $path[] = "{$thisdir}/{$dircont[$i]}";
+                                                        $path[]  = "{$thisdir}/{$dircont[$i]}";
                                                         $stack[] = $current_file;
                                                     }
                                                 }
@@ -229,24 +326,78 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                         //Sample $item is C:/xampp/htdocs/chamilo/courses/TEST/document/books/book_highlight.jpg
                                         $file_orig = basename($item);
                                         if ($file_orig[0] != '.' && !in_array($invisibleFileNames)) {
-                                            $source_item = substr($item, (strlen($base_work_dir) - strlen($item))); // sample /books/book_highlight.jpg or /books
-                                            $target_item = $source_item;
+                                            $source_item   = substr(
+                                                $item,
+                                                (strlen($base_work_dir) - strlen($item))
+                                            ); // sample /books/book_highlight.jpg or /books
+                                            $target_item   = $source_item;
                                             $chamiloFolder = $target_item;
-                                            $chamiloFile = basename($target_item);
+                                            $chamiloFile   = basename($target_item);
                                             //
                                             if (is_dir($item)) {
-                                                $doc_id = add_document($_course, $chamiloFolder, 'folder', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                                $doc_id = add_document(
+                                                    $_course,
+                                                    $chamiloFolder,
+                                                    'folder',
+                                                    $chamiloFileSize,
+                                                    $chamiloFile
+                                                ); //get Chamilo
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'FolderCreated',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                ); //get Chamilo
                                             } elseif (is_file($item)) {
                                                 $chamiloFileSize = filesize($item);
-                                                $doc_id = add_document($_course, $chamiloFolder, 'file', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                                $doc_id          = add_document(
+                                                    $_course,
+                                                    $chamiloFolder,
+                                                    'file',
+                                                    $chamiloFileSize,
+                                                    $chamiloFile
+                                                ); //get Chamilo
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'DocumentAdded',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                ); //get Chamilo
                                             }
                                         }
                                     }
                                 } elseif ($tem['type'] == "file") {
-                                    $doc_id = add_document($_course, $chamiloFolder, 'file', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                    $doc_id = add_document(
+                                        $_course,
+                                        $chamiloFolder,
+                                        'file',
+                                        $chamiloFileSize,
+                                        $chamiloFile
+                                    ); //get Chamilo
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'DocumentAdded',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    ); //get Chamilo
                                 }
                             }
                         }
@@ -258,9 +409,8 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                         }
 
 
-
                         $fileMoved[sizeof($fileMoved)] = $tem;
-                        $tem = null;
+                        $tem                           = null;
                     }
                 } else {
                     $unmovedDocDueToSamePath[] = $doc;
@@ -290,4 +440,3 @@ foreach ($fileMoved as $i => $file) {
     echo "} ";
 }
 echo "} }";
-?>

+ 105 - 75
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_upload.php

@@ -1,101 +1,131 @@
 <?php
+/* For licensing terms, see /license.txt */
 /**
- * processing the uploaded files
  * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
  * @link www.phpletter.com
- * @since 22/May/2007
+ * @since 22/April/2007
  *
  */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+// @todo sleep??
+
 sleep(3);
-require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php";
 echo "{";
 $error = "";
-$info = "";
+$info  = "";
 
-include_once CLASS_UPLOAD ;
+include_once CLASS_UPLOAD;
 $upload = new Upload();
 
 $folder = base64_decode($_GET['folder']);
 //$folder = ($_GET['folder']);
 $upload->setInvalidFileExt(explode(",", CONFIG_UPLOAD_INVALID_EXTS));
-if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_UPLOAD) {
-	$error = SYS_DISABLED;
-} elseif(empty($folder) || !isUnderRoot($folder)) {
-	$error = ERR_FOLDER_PATH_NOT_ALLOWED;
-} else	if(!$upload->isFileUploaded('file')) {
-	$error = ERR_FILE_NOT_UPLOADED;
-}else if(!$upload->moveUploadedFile($folder)) {
-	$error = ERR_FILE_MOVE_FAILED;
-} elseif(!$upload->isPermittedFileExt(explode(",", CONFIG_UPLOAD_VALID_EXTS))) {
-	$error = ERR_FILE_TYPE_NOT_ALLOWED;
-} elseif(defined('CONFIG_UPLOAD_MAXSIZE') && CONFIG_UPLOAD_MAXSIZE && $upload->isSizeTooBig(CONFIG_UPLOAD_MAXSIZE)) {
-	 $error = sprintf(ERROR_FILE_TOO_BID, transformFileSize(CONFIG_UPLOAD_MAXSIZE));
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_UPLOAD) {
+    $error = SYS_DISABLED;
+} elseif (empty($folder) || !isUnderRoot($folder)) {
+    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
+} else if (!$upload->isFileUploaded('file')) {
+    $error = ERR_FILE_NOT_UPLOADED;
 } else {
-	include_once(CLASS_FILE);
-	$path = $upload->getFilePath();
-	$obj = new file($path);
-	$tem = $obj->getFileInfo();
+    if (!$upload->moveUploadedFile($folder)) {
+        $error = ERR_FILE_MOVE_FAILED;
+    } elseif (!$upload->isPermittedFileExt(explode(",", CONFIG_UPLOAD_VALID_EXTS))) {
+        $error = ERR_FILE_TYPE_NOT_ALLOWED;
+    } elseif (defined('CONFIG_UPLOAD_MAXSIZE') && CONFIG_UPLOAD_MAXSIZE && $upload->isSizeTooBig(
+            CONFIG_UPLOAD_MAXSIZE
+        )
+    ) {
+        $error = sprintf(ERROR_FILE_TOO_BID, transformFileSize(CONFIG_UPLOAD_MAXSIZE));
+    } else {
+        include_once(CLASS_FILE);
+        $path = $upload->getFilePath();
+        $obj  = new file($path);
+        $tem  = $obj->getFileInfo();
 
-	if (sizeof($tem)) {
-		include_once(CLASS_MANAGER);
-		$manager = new manager($upload->getFilePath(), false);
-		$fileType = $manager->getFileType($upload->getFileName());
-		foreach($fileType as $k=>$v) {
-			$tem[$k] = $v;
-		}
+        if (sizeof($tem)) {
+            include_once(CLASS_MANAGER);
+            $manager  = new manager($upload->getFilePath(), false);
+            $fileType = $manager->getFileType($upload->getFileName());
+            foreach ($fileType as $k => $v) {
+                $tem[$k] = $v;
+            }
 
-		$tem['path'] = backslashToSlash($path);
-		$tem['type'] = "file";
-		$tem['size'] = transformFileSize($tem['size']);
-		$tem['ctime'] = date(DATE_TIME_FORMAT, $tem['ctime']);
-		$tem['mtime'] = date(DATE_TIME_FORMAT, $tem['mtime']);
-		$tem['short_name'] = shortenFileName($tem['name']);
-		$tem['flag'] = 'noFlag';
+            $tem['path']       = backslashToSlash($path);
+            $tem['type']       = "file";
+            $tem['size']       = transformFileSize($tem['size']);
+            $tem['ctime']      = date(DATE_TIME_FORMAT, $tem['ctime']);
+            $tem['mtime']      = date(DATE_TIME_FORMAT, $tem['mtime']);
+            $tem['short_name'] = shortenFileName($tem['name']);
+            $tem['flag']       = 'noFlag';
 
-		/**
-		* Bridge to Chamilo documents tool
-		* @author Juan Carlos Raña Trabado
-		*/
+            /**
+             * Bridge to Chamilo documents tool
+             * @author Juan Carlos Raña Trabado
+             */
 
-		if(!empty($_course['path'])) {
-			//only inside courses
-			$fullPath= $upload->getFilePath();		//get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/image.jpg
-			$folderInfo = $manager->getFolderInfo(); //get	ajaxmanager
-			$mainPath= getParentFolderPath($folderInfo['path']);//get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/
-			$chamiloFolder = substr($fullPath, strlen($mainPath)-strlen($fullPath)-1);
-			$chamiloFile = $tem['name'];	//get	ajaxmanager
-			$chamiloFileSize = filesize($fullPath); //get ajaxmanager
-			//get Chamilo
-			if(!empty($group_properties['directory'])) {
-				$chamiloFolder=$group_properties['directory'].$chamiloFolder;//get Chamilo
-			} else {
-				if(!api_is_allowed_to_edit()) {
-					$current_session_id = api_get_session_id();
-					if($current_session_id==0) {
-						$chamiloFolder='/shared_folder/sf_user_'.api_get_user_id().$chamiloFolder;
-					} else {
-						$chamiloFolder='/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().$chamiloFolder;
-					}
-				}
-			}
+            if (!empty($_course['path'])) {
+                //only inside courses
+                $fullPath        = $upload->getFilePath(
+                ); //get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/image.jpg
+                $folderInfo      = $manager->getFolderInfo(); //get	ajaxmanager
+                $mainPath        = getParentFolderPath(
+                    $folderInfo['path']
+                ); //get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/
+                $chamiloFolder   = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1);
+                $chamiloFile     = $tem['name']; //get	ajaxmanager
+                $chamiloFileSize = filesize($fullPath); //get ajaxmanager
+                //get Chamilo
+                if (!empty($group_properties['directory'])) {
+                    $chamiloFolder = $group_properties['directory'].$chamiloFolder; //get Chamilo
+                } else {
+                    if (!api_is_allowed_to_edit()) {
+                        $current_session_id = api_get_session_id();
+                        if ($current_session_id == 0) {
+                            $chamiloFolder = '/shared_folder/sf_user_'.api_get_user_id().$chamiloFolder;
+                        } else {
+                            $chamiloFolder = '/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id(
+                                ).$chamiloFolder;
+                        }
+                    }
+                }
 
-			$doc_id = add_document($_course, $chamiloFolder,'file', $chamiloFileSize , $chamiloFile); //get Chamilo
-			$current_session_id = api_get_session_id();
-			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(),$to_group_id,null,null,null,$current_session_id);//get Chamilo
+                $doc_id             = add_document(
+                    $_course,
+                    $chamiloFolder,
+                    'file',
+                    $chamiloFileSize,
+                    $chamiloFile
+                ); //get Chamilo
+                $current_session_id = api_get_session_id();
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'DocumentAdded',
+                    api_get_user_id(),
+                    $to_group_id,
+                    null,
+                    null,
+                    null,
+                    $current_session_id
+                ); //get Chamilo
 
-		}
-		// end bridge
-		$obj->close();
-		foreach($tem as $k=>$v) {
-			$info .= sprintf(", %s:'%s'", $k, $v);
-		}
-		$info .= sprintf(", url:'%s'",  getFileUrl($path));
-		$info .= sprintf(", tipedit:'%s'",  TIP_DOC_RENAME);
-	} else {
-		$error = ERR_FILE_NOT_AVAILABLE;
-	}
+            }
+            // end bridge
+            $obj->close();
+            foreach ($tem as $k => $v) {
+                $info .= sprintf(", %s:'%s'", $k, $v);
+            }
+            $info .= sprintf(", url:'%s'", getFileUrl($path));
+            $info .= sprintf(", tipedit:'%s'", TIP_DOC_RENAME);
+        } else {
+            $error = ERR_FILE_NOT_AVAILABLE;
+        }
+    }
 }
 
-echo "error:'" . $error . "'";
+echo "error:'".$error."'";
 echo $info;
 echo "}";

+ 26 - 23
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_get_file_listing.php

@@ -1,25 +1,21 @@
 <?php
-
+/* For licensing terms, see /license.txt */
 /**
- * the php script used to get the list of file or folders under a specific folder
  * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
  * @link www.phpletter.com
- * @since 22/May/2007
+ * @since 22/April/2007
  *
- * Modify for Chamilo
- * @author Juan Carlos Ra�a Trabado
- * @since 31/December/2008
  */
-require_once '../../../../../../inc/global.inc.php'; // Integrating with Chamilo
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
 
 if (!isset($manager)) {
     /**
      *  this is part of  script for processing file paste
      */
-    //$_GET = $_POST;
-    include_once dirname(__FILE__).DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."config.php";
     include_once CLASS_PAGINATION;
-    $pagination = new pagination(false);
+    $pagination    = new pagination(false);
     $search_folder = null;
     if (isset($_GET['search_folder'])) {
         $search_folder = str_replace("'", "", $_GET['search_folder']); //security fix for Chamilo by cfasanando
@@ -37,7 +33,7 @@ if (!isset($manager)) {
         $search->addSearchKeyword('recursive', @$_GET['search_recursively']);
         $search->addSearchKeyword('name', @$_GET['search_name']);
         $search->doSearch();
-        $fileList = $search->getFoundFiles();
+        $fileList   = $search->getFoundFiles();
         $folderInfo = $search->getRootFolderInfo();
     } else {
         include_once(CLASS_MANAGER);
@@ -48,7 +44,7 @@ if (!isset($manager)) {
         $manager = new manager();
         $manager->setSessionAction($sessionAction);
 
-        $fileList = $manager->getFileList();
+        $fileList   = $manager->getFileList();
         $folderInfo = $manager->getFolderInfo();
     }
     $pagination->setUrl(CONFIG_URL_FILEnIMAGE_MANAGER);
@@ -68,18 +64,20 @@ echo $pagination->getPaginationHTML();
 // Chamilo fix for count hidden folders
 $count_hideItem = 0;
 
-$deleted_by_Chamilo_file = ' DELETED '; // ' DELETED ' not '_DELETED_' because in $file['name'] _ is replaced with blank see class.manager.php
-$deleted_by_Chamilo_folder = '_DELETED_';
-$css_folder_Chamilo = 'css';
+$deleted_by_Chamilo_file    = ' DELETED '; // ' DELETED ' not '_DELETED_' because in $file['name'] _ is replaced with blank see class.manager.php
+$deleted_by_Chamilo_folder  = '_DELETED_';
+$css_folder_Chamilo         = 'css';
 $hotpotatoes_folder_Chamilo = 'HotPotatoes_files';
-$chat_files_Chamilo = 'chat_files';
-$certificates_Chamilo = 'certificates';
+$chat_files_Chamilo         = 'chat_files';
+$certificates_Chamilo       = 'certificates';
 
 //end previous fix for count hidden folders
 
 echo "<script>";
 
-echo "parentFolder = {path_base64:'".base64_encode(getParentFolderPath($folderInfo['path']))."', path:'".getParentFolderPath($folderInfo['path'])."'};";
+echo "parentFolder = {path_base64:'".base64_encode(
+        getParentFolderPath($folderInfo['path'])
+    )."', path:'".getParentFolderPath($folderInfo['path'])."'};";
 echo 'currentFolder ={';
 $count = 1;
 foreach ($folderInfo as $k => $v) {
@@ -94,23 +92,24 @@ $count = 1;
 
 foreach ($fileList as $file) {
     //show group's directory only if I'm member. Or if I'm a teacher. TODO: check groups not necessary because the student dont have access to main folder documents (only to document/group or document/shared_folder). Teachers can access to all groups ?
-    $group_folder = '_groupdocs';
+    $group_folder   = '_groupdocs';
     $hide_doc_group = false;
     if (preg_match("/$group_folder/", $file['path'])) {
         $hide_doc_group = true;
-        if ($is_user_in_group || ( $to_group_id != 0 && api_is_allowed_to_edit())) {
+        if ($is_user_in_group || ($to_group_id != 0 && api_is_allowed_to_edit())) {
             $hide_doc_group = false;
         }
     }
 
     if ((!preg_match("/$deleted_by_Chamilo_file/", $file['name']) ||
-        !preg_match("/$deleted_by_Chamilo_folder/", $file['path'])) ||
+            !preg_match("/$deleted_by_Chamilo_folder/", $file['path'])) ||
         preg_match("/$css_folder_Chamilo/", $file['path']) ||
         preg_match("/$hotpotatoes_folder_Chamilo/", $file['path']) ||
         preg_match("/$chat_files_Chamilo/", $file['path']) ||
         preg_match("/$certificates_Chamilo/", $file['path']) ||
         $hide_doc_group ||
-        $file['name'][0] == '.') { //Chamilo fix for hidden items.
+        $file['name'][0] == '.'
+    ) { //Chamilo fix for hidden items.
         $count_hideItem = $count_hideItem + 1;
     }
 
@@ -128,7 +127,11 @@ foreach ($fileList as $file) {
     echo (($j++ > 1) ? "," : '')."'url':'".getFileUrl($file['path'])."'";
     echo "}\n";
 }
-$fileList = array_slice($fileList, $pagination->getPageOffset(), $pagination->getLimit()); //Chamilo fix for hidden files added +$count_hideItem
+$fileList = array_slice(
+    $fileList,
+    $pagination->getPageOffset(),
+    $pagination->getLimit()
+); //Chamilo fix for hidden files added +$count_hideItem
 
 echo "};</script>";
 if (!empty($_GET['view'])) {

+ 18 - 11
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_get_folder_listing.php

@@ -1,13 +1,20 @@
 <?php
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	echo '{';
-	$count = 1;
-	foreach(getFolderListing(CONFIG_SYS_ROOT_PATH) as $k=>$v)
-	{
-		
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
 
-		echo (($count > 1)?', ':''). "'" . $v . "':'" . $k . "'"; 
-		$count++;
-	}
-	echo "}";
-?>
+echo '{';
+$count = 1;
+foreach (getFolderListing(CONFIG_SYS_ROOT_PATH) as $k => $v) {
+
+
+    echo (($count > 1) ? ', ' : '')."'".$v."':'".$k."'";
+    $count++;
+}
+echo "}";

+ 244 - 205
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_editor.php

@@ -1,223 +1,262 @@
 <?php
-		/**
-	 * Ajax image editor platform
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE)
-	{
-		die(SYS_DISABLED);
-	}
-		//$session->gc();// Disabled for integration with Chamilo
-		$_GET['path'] = empty($_GET['path'])?CONFIG_SYS_ROOT_PATH . "ajax_image_editor_demo.jpg":$_GET['path'];
-		if(!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path']) && isUnderRoot($_GET['path']))
-		{
-				$path = $_GET['path'];
-		}else 
-		{
-			die(IMG_GEN_IMG_NOT_EXISTS);
-		}
-		require_once(CLASS_HISTORY);
-		$history = new History($path, $session);
-		if(CONFIG_SYS_DEMO_ENABLE)
-		{
-			$sessionImageInfo = $history->getLastestRestorable();
-			$originalSessionImageInfo = $history->getOriginalImage();
-			if(sizeof($originalSessionImageInfo))
-			{
-				$path = backslashToSlash($session->getSessionDir() . $originalSessionImageInfo['info']['name']);
-			}
-		}
-		require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "class.image.php");
-		$image = new ImageAjaxFileManager();
-		
-		$imageInfo = $image->getImageInfo($path);
-
-	?>
+/* For licensing terms, see /license.txt */
+/**
+ * Ajax image editor platform
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/May/2007
+ *
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE) {
+    die(SYS_DISABLED);
+}
+
+$_GET['path'] = empty($_GET['path']) ? CONFIG_SYS_ROOT_PATH."ajax_image_editor_demo.jpg" : $_GET['path'];
+if (!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path']) && isUnderRoot($_GET['path'])) {
+    $path = $_GET['path'];
+} else {
+    die(IMG_GEN_IMG_NOT_EXISTS);
+}
+require_once(CLASS_HISTORY);
+$history = new History($path, $session);
+if (CONFIG_SYS_DEMO_ENABLE) {
+    $sessionImageInfo         = $history->getLastestRestorable();
+    $originalSessionImageInfo = $history->getOriginalImage();
+    if (sizeof($originalSessionImageInfo)) {
+        $path = backslashToSlash($session->getSessionDir().$originalSessionImageInfo['info']['name']);
+    }
+}
+require_once(dirname(__FILE__).DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."class.image.php");
+$image = new ImageAjaxFileManager();
+
+$imageInfo = $image->getImageInfo($path);
+
+?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="author" content="Logan Cai" />
-<meta name="website" content="http://www.phpletter.com" />
-<script type="text/javascript" src="jscripts/ajaximageeditor_c.js"></script>
-
-<!--<script type="text/javascript" src="jscripts/jquery.js"></script>
-<script type="text/javascript" src="jscripts/form.js"></script>
-<script type="text/javascript" src="jscripts/select.js"></script>
-<script type="text/javascript" src="jscripts/jqModal.js"></script>
-<script type="text/javascript" src="jscripts/rotate.js"></script>
-<script type="text/javascript" src="jscripts/interface.js"></script>-->
-
-
-<script type="text/javascript" src="jscripts/ajaximageeditor.js"></script>
-
-
-
-
-
-
-<script type="text/javascript">
-	var imageHistory = false;
-	var currentFolder =  '<?php echo removeTrailingSlash(backslashToSlash(dirname($path))); ?>';
-	var warningLostChanges = '<?php echo IMG_WARNING_LOST_CHANAGES; ?>';
-	var warningReset = '<?php echo IMG_WARNING_REST; ?>';
-	var warningResetEmpty = '<?php echo IMG_WARNING_EMPTY_RESET; ?>';
-	var warningEditorClose = '<?php echo IMG_WARING_WIN_CLOSE; ?>';
-	var warningUndoImage = '<?php echo IMG_WARNING_UNDO; ?>';
-	var warningFlipHorizotal = '<?php echo IMG_WARING_FLIP_H; ?>';
-	var warningFlipVertical = '<?php echo IMG_WARING_FLIP_V; ?>';
-	var numSessionHistory = <?php echo $history->getNumRestorable(); ?>;
-	var noChangeMadeBeforeSave = '<?php echo IMG_WARNING_NO_CHANGE_BEFORE_SAVE; ?>';
-	var warningInvalidNewName = '<?php echo IMG_SAVE_AS_ERR_NAME_INVALID; ?>';
-	var wordCloseWindow = '<?php echo LBL_ACTION_CLOSE; ?>';
-	var warningNoFolderSelected = '<?php echo IMG_SAVE_AS_NOT_FOLDER_SELECTED; ?>';
-	var urlGetFolderList = '<?php echo appendQueryString(CONFIG_URL_GET_FOLDER_LIST, makeQueryString(array('path'))); ?>';
-	$(document).ready(
-		function()
-		{
-			$('#windowSaveAs').jqm();
-			$('#image_mode').val('');
-			$('#angle').val(0);
-			$(getImageElement()).clone().appendTo("#hiddenImage");
-			changeMode();
-			initDisabledButtons(true);
-			$("#formImageInfo").bind("keypress", function(e) {
-			if (e.keyCode == 13) {
-			
-			return false;
-			
-			}
-			});			
-		}
-	);
-	
-</script>
-<link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/ajaximageeditor.css" type="text/css" rel="stylesheet" />
-<link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/jqModal.css" type="text/css" rel="stylesheet" />
-<title>Ajax Image Editor</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+    <meta name="author" content="Logan Cai"/>
+    <meta name="website" content="http://www.phpletter.com"/>
+    <script type="text/javascript" src="jscripts/ajaximageeditor_c.js"></script>
+
+    <!--<script type="text/javascript" src="jscripts/jquery.js"></script>
+    <script type="text/javascript" src="jscripts/form.js"></script>
+    <script type="text/javascript" src="jscripts/select.js"></script>
+    <script type="text/javascript" src="jscripts/jqModal.js"></script>
+    <script type="text/javascript" src="jscripts/rotate.js"></script>
+    <script type="text/javascript" src="jscripts/interface.js"></script>-->
+
+
+    <script type="text/javascript" src="jscripts/ajaximageeditor.js"></script>
+
+
+    <script type="text/javascript">
+        var imageHistory = false;
+        var currentFolder = '<?php echo removeTrailingSlash(backslashToSlash(dirname($path))); ?>';
+        var warningLostChanges = '<?php echo IMG_WARNING_LOST_CHANAGES; ?>';
+        var warningReset = '<?php echo IMG_WARNING_REST; ?>';
+        var warningResetEmpty = '<?php echo IMG_WARNING_EMPTY_RESET; ?>';
+        var warningEditorClose = '<?php echo IMG_WARING_WIN_CLOSE; ?>';
+        var warningUndoImage = '<?php echo IMG_WARNING_UNDO; ?>';
+        var warningFlipHorizotal = '<?php echo IMG_WARING_FLIP_H; ?>';
+        var warningFlipVertical = '<?php echo IMG_WARING_FLIP_V; ?>';
+        var numSessionHistory = <?php echo $history->getNumRestorable(); ?>;
+        var noChangeMadeBeforeSave = '<?php echo IMG_WARNING_NO_CHANGE_BEFORE_SAVE; ?>';
+        var warningInvalidNewName = '<?php echo IMG_SAVE_AS_ERR_NAME_INVALID; ?>';
+        var wordCloseWindow = '<?php echo LBL_ACTION_CLOSE; ?>';
+        var warningNoFolderSelected = '<?php echo IMG_SAVE_AS_NOT_FOLDER_SELECTED; ?>';
+        var urlGetFolderList = '<?php echo appendQueryString(CONFIG_URL_GET_FOLDER_LIST, makeQueryString(array('path'))); ?>';
+        $(document).ready(
+            function () {
+                $('#windowSaveAs').jqm();
+                $('#image_mode').val('');
+                $('#angle').val(0);
+                $(getImageElement()).clone().appendTo("#hiddenImage");
+                changeMode();
+                initDisabledButtons(true);
+                $("#formImageInfo").bind("keypress", function (e) {
+                    if (e.keyCode == 13) {
+
+                        return false;
+
+                    }
+                });
+            }
+        );
+
+    </script>
+    <link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/ajaximageeditor.css" type="text/css" rel="stylesheet"/>
+    <link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/jqModal.css" type="text/css" rel="stylesheet"/>
+    <title>Ajax Image Editor</title>
 </head>
 <body>
 <?php
-	//displayArray($_SESSION);
-	 
+//displayArray($_SESSION);
+
 ?>
 <div id="controls">
-	<fieldset id="modes">
-		<legend>Modes</legend>
-		<form name="formAction" id="formAction" method="post" action="<?php echo appendQueryString(CONFIG_URL_IMAGE_UNDO, makeQueryString(array('path'))); ?>">
-			<input type="hidden" name="file_path" id="file_path" value="<?php echo $_GET['path']; ?>" />
-			
-			<p><label  id="label_resize" class="labelMode"><?php echo IMG_MODE_RESIZE; ?></label> <input type="radio" name="mode" value="resize" class="input" checked="checked"  onclick="return changeMode();"/>
-			<label id="label_crop"  class="labelMode"><?php echo IMG_MODE_CROP; ?></label> <input type="radio" name="mode" value="crop" class="input" onclick="return changeMode();" />
-			<label  id="label_rotate"  class="labelMode"><?php echo IMG_MODE_ROTATE; ?></label> <input type="radio" name="mode" value="rotate" class="input" onclick="return changeMode();" />
-			<label  id="label_flip"  class="labelMode"><?php echo IMG_MODE_FLIP; ?></label> <input type="radio" name="mode" value="flip" class="input" onclick="return changeMode();" />
-			 || <label  id="label_constraint"><?php echo IMG_CHECKBOX_CONSTRAINT; ?></label> <input type="checkbox" name="constraint" id="constraint" value="1" class="input" onclick="return toggleConstraint();" />
-			<!--			<label>Watermark:</label> <input type="radio" name="mode" value="watermark" class="input" onclick="return false;" />-->
-			
-			<button id="actionRotateLeft" class="disabledButton" onclick="return leftRotate();" disabled><?php echo IMG_BTN_ROTATE_LEFT; ?></button>
-			<button id="actionRotateRight" class="disabledButton" onclick="return rightRotate();" disabled><?php echo IMG_BTN_ROTATE_RIGHT; ?></button>
-			<button id="actionFlipH" class="disabledButton" onclick="return flipHorizontal();" disabled><?php echo IMG_BTN_FLIP_H; ?></button>
-			<button id="actionFlipV" class="disabledButton" onclick="return flipVertical();" disabled><?php echo IMG_BTN_FLIP_V; ?></button>			
-			<button id="actionReset" class="button" onclick="return resetEditor();"><?php echo IMG_BTN_RESET; ?></button>
-			<button id="actionUndo" class="button" onclick="return undoImage();"><?php echo IMG_BTN_UNDO; ?></button>
-			<button id="actionSave" class="button" onclick="return saveImage();"><?php echo IMG_BTN_SAVE; ?></button>
-      <button id="actionSaveAs" class="button" onclick="return saveAsImagePre();"><?php echo IMG_BTN_SAVE_AS; ?></button>
-			<button id="actionClose" class="button" onclick="return editorClose();"><?php echo IMG_BTN_CLOSE; ?></button></p>
-		</form>
-	</fieldset>
-	<fieldset id="imageInfo">
-		<legend id="imageInfoLegend"><?php echo IMG_INFO; ?></legend>
-		<form name="formImageInfo" action="<?php echo appendQueryString(CONFIG_URL_IMAGE_SAVE, makeQueryString(array('path'))); ?>" method="post" id="formImageInfo">
-			<p><input type="hidden" name="mode" id="image_mode" value="" />
-      <input type="hidden" name="new_name" id="hidden_new_name" value="" />
-      <input type="hidden" name="save_to" id="hidden_save_to" value="" />
-			<input type="hidden" name="path" id="path" value="<?php echo $_GET['path']; ?>"  />
-			<input type="hidden" name="flip_angle" id="flip_angle" value="" />
-			<label><?php echo IMG_LBL_WIDTH; ?></label> <input type="text" name="width" id="width" value="" class="input imageInput"  />
-			<label><?php echo IMG_LBL_HEIGHT; ?></label> <input type="text" name="height" id="height" value="" class="input imageInput" />
-			<label><?php echo IMG_LBL_X; ?></label> <input type="text" name="x" id="x" value="" class="input imageInput"/>
-			<label><?php echo IMG_LBL_Y; ?></label> <input type="text" name="y" id="y" value="" class="input imageInput"/>
-<!--			<b>Percentage:</b> <input type="text" name="percentage" id="percentage" value="" class="input imageInput"/>-->
-			<label><?php echo IMG_LBL_RATIO; ?></label> <input type="text" name="ratio" id="ratio" value="" class="input imageInput"/>
-			<label><?php echo IMG_LBL_ANGLE; ?></label> <input type="text" name="angle" id="angle" value="" class="input imageInput" />
-			
-			</p>
-		</form>
-	</fieldset>
+    <fieldset id="modes">
+        <legend>Modes</legend>
+        <form name="formAction" id="formAction" method="post"
+              action="<?php echo appendQueryString(CONFIG_URL_IMAGE_UNDO, makeQueryString(array('path'))); ?>">
+            <input type="hidden" name="file_path" id="file_path" value="<?php echo $_GET['path']; ?>"/>
+
+            <p><label id="label_resize" class="labelMode"><?php echo IMG_MODE_RESIZE; ?></label> <input type="radio"
+                                                                                                        name="mode"
+                                                                                                        value="resize"
+                                                                                                        class="input"
+                                                                                                        checked="checked"
+                                                                                                        onclick="return changeMode();"/>
+                <label id="label_crop" class="labelMode"><?php echo IMG_MODE_CROP; ?></label> <input type="radio"
+                                                                                                     name="mode"
+                                                                                                     value="crop"
+                                                                                                     class="input"
+                                                                                                     onclick="return changeMode();"/>
+                <label id="label_rotate" class="labelMode"><?php echo IMG_MODE_ROTATE; ?></label> <input type="radio"
+                                                                                                         name="mode"
+                                                                                                         value="rotate"
+                                                                                                         class="input"
+                                                                                                         onclick="return changeMode();"/>
+                <label id="label_flip" class="labelMode"><?php echo IMG_MODE_FLIP; ?></label> <input type="radio"
+                                                                                                     name="mode"
+                                                                                                     value="flip"
+                                                                                                     class="input"
+                                                                                                     onclick="return changeMode();"/>
+                || <label id="label_constraint"><?php echo IMG_CHECKBOX_CONSTRAINT; ?></label> <input type="checkbox"
+                                                                                                      name="constraint"
+                                                                                                      id="constraint"
+                                                                                                      value="1"
+                                                                                                      class="input"
+                                                                                                      onclick="return toggleConstraint();"/>
+                <!--			<label>Watermark:</label> <input type="radio" name="mode" value="watermark" class="input" onclick="return false;" />-->
+
+                <button id="actionRotateLeft" class="disabledButton" onclick="return leftRotate();"
+                        disabled><?php echo IMG_BTN_ROTATE_LEFT; ?></button>
+                <button id="actionRotateRight" class="disabledButton" onclick="return rightRotate();"
+                        disabled><?php echo IMG_BTN_ROTATE_RIGHT; ?></button>
+                <button id="actionFlipH" class="disabledButton" onclick="return flipHorizontal();"
+                        disabled><?php echo IMG_BTN_FLIP_H; ?></button>
+                <button id="actionFlipV" class="disabledButton" onclick="return flipVertical();"
+                        disabled><?php echo IMG_BTN_FLIP_V; ?></button>
+                <button id="actionReset" class="button"
+                        onclick="return resetEditor();"><?php echo IMG_BTN_RESET; ?></button>
+                <button id="actionUndo" class="button"
+                        onclick="return undoImage();"><?php echo IMG_BTN_UNDO; ?></button>
+                <button id="actionSave" class="button"
+                        onclick="return saveImage();"><?php echo IMG_BTN_SAVE; ?></button>
+                <button id="actionSaveAs" class="button"
+                        onclick="return saveAsImagePre();"><?php echo IMG_BTN_SAVE_AS; ?></button>
+                <button id="actionClose" class="button"
+                        onclick="return editorClose();"><?php echo IMG_BTN_CLOSE; ?></button>
+            </p>
+        </form>
+    </fieldset>
+    <fieldset id="imageInfo">
+        <legend id="imageInfoLegend"><?php echo IMG_INFO; ?></legend>
+        <form name="formImageInfo"
+              action="<?php echo appendQueryString(CONFIG_URL_IMAGE_SAVE, makeQueryString(array('path'))); ?>"
+              method="post" id="formImageInfo">
+            <p><input type="hidden" name="mode" id="image_mode" value=""/>
+                <input type="hidden" name="new_name" id="hidden_new_name" value=""/>
+                <input type="hidden" name="save_to" id="hidden_save_to" value=""/>
+                <input type="hidden" name="path" id="path" value="<?php echo $_GET['path']; ?>"/>
+                <input type="hidden" name="flip_angle" id="flip_angle" value=""/>
+                <label><?php echo IMG_LBL_WIDTH; ?></label> <input type="text" name="width" id="width" value=""
+                                                                   class="input imageInput"/>
+                <label><?php echo IMG_LBL_HEIGHT; ?></label> <input type="text" name="height" id="height" value=""
+                                                                    class="input imageInput"/>
+                <label><?php echo IMG_LBL_X; ?></label> <input type="text" name="x" id="x" value=""
+                                                               class="input imageInput"/>
+                <label><?php echo IMG_LBL_Y; ?></label> <input type="text" name="y" id="y" value=""
+                                                               class="input imageInput"/>
+                <!--			<b>Percentage:</b> <input type="text" name="percentage" id="percentage" value="" class="input imageInput"/>-->
+                <label><?php echo IMG_LBL_RATIO; ?></label> <input type="text" name="ratio" id="ratio" value=""
+                                                                   class="input imageInput"/>
+                <label><?php echo IMG_LBL_ANGLE; ?></label> <input type="text" name="angle" id="angle" value=""
+                                                                   class="input imageInput"/>
+
+            </p>
+        </form>
+    </fieldset>
 </div>
 <div id="imageArea">
     <div id="imageContainer">
-    
-	<?php
-	if(Security::remove_XSS($_GET['editor'])!='stand_alone'){
-	
-		$path='../'.$path;//<!-- For Chamilo integrating, enter a back directory "../" to avoid introducing main and can not read the image -->
-	}
-	?>
-        <img src="<?php echo $path; ?>" name="<?php echo basename($path); ?>" width="<?php echo $imageInfo['width']; ?>" height="<?php echo $imageInfo['height']; ?>" />
-        
+
+        <?php
+        if (Security::remove_XSS($_GET['editor']) != 'stand_alone') {
+
+            $path = '../'.$path; //<!-- For Chamilo integrating, enter a back directory "../" to avoid introducing main and can not read the image -->
+        }
+        ?>
+        <img src="<?php echo $path; ?>" name="<?php echo basename($path); ?>" width="<?php echo $imageInfo['width']; ?>"
+             height="<?php echo $imageInfo['height']; ?>"/>
+
     </div>
     <div id="resizeMe">
-    	<div id="resizeSE"></div>
-    	<div id="resizeE"></div>
-    	<div id="resizeNE"></div>
-    	<div id="resizeN"></div>
-    	<div id="resizeNW"></div>
-    	<div id="resizeW"></div>
-    	<div id="resizeSW"></div>
-    	<div id="resizeS"></div>
-		<img id="loading" style="display:none;" src="theme/<?php echo CONFIG_THEME_NAME; ?>/images/ajaxLoading.gif" />
+        <div id="resizeSE"></div>
+        <div id="resizeE"></div>
+        <div id="resizeNE"></div>
+        <div id="resizeN"></div>
+        <div id="resizeNW"></div>
+        <div id="resizeW"></div>
+        <div id="resizeSW"></div>
+        <div id="resizeS"></div>
+        <img id="loading" style="display:none;" src="theme/<?php echo CONFIG_THEME_NAME; ?>/images/ajaxLoading.gif"/>
     </div>
 </div>
-    <div id="hiddenImage">
-    </div>
-		<div id="windowSaveAs" class="jqmWindow" style="display:none">
-    	<a href="#" class="jqmClose" id="windowSaveClose"><?php echo LBL_ACTION_CLOSE; ?></a>
-      <form id="formSaveAs" name="formSaveAs" action="" method="post">
-    	<table class="tableForm" cellpadding="0" cellspacing="0">
-      	<thead>
-        	<tr>
-          	<th colspan="2"><?php echo IMG_LBL_SAVE_AS; ?></th>
-          </tr>
-        </thead>
-        <tbody>
-        	<tr>
-          	<th>
-            	<label><?php echo IMG_LBL_NEW_NAME; ?></label>
-            </th>
-            <td>
-            	<input type="text" id="new_name" class="input" name="new_name" value="" />&nbsp;.<?php echo getFileExt($path); ?>
-            </td>
-          </tr>
-          <tr>
-          	<th>
-            	<label><?php echo IMG_LBL_SAVE_TO; ?></label>
-            </th>
-            <td>
-            	<select class="input" name="save_to" id="save_to"></select>
-            </td>
-          </tr>
-          <tr>
-          	<th>&nbsp;
-            </th>
-            <td>
-            <span class="comments">*</span>
-            <?php echo IMG_NEW_NAME_COMMENTS; ?>
-            </td>
-          </tr>
-        </tbody>
-        <tfoot>
-        	<tr>
-        	<th>&nbsp;</th>
-          <td><input type="button" class="button" value="<?php echo IMG_BTN_SAVE_AS; ?>" onclick="return saveAsImage();" /></td>
-          </tr>
-        </tfoot>
-      </table>
-      </form>
-    </div>
+<div id="hiddenImage">
+</div>
+<div id="windowSaveAs" class="jqmWindow" style="display:none">
+    <a href="#" class="jqmClose" id="windowSaveClose"><?php echo LBL_ACTION_CLOSE; ?></a>
+
+    <form id="formSaveAs" name="formSaveAs" action="" method="post">
+        <table class="tableForm" cellpadding="0" cellspacing="0">
+            <thead>
+            <tr>
+                <th colspan="2"><?php echo IMG_LBL_SAVE_AS; ?></th>
+            </tr>
+            </thead>
+            <tbody>
+            <tr>
+                <th>
+                    <label><?php echo IMG_LBL_NEW_NAME; ?></label>
+                </th>
+                <td>
+                    <input type="text" id="new_name" class="input" name="new_name"
+                           value=""/>&nbsp;.<?php echo getFileExt($path); ?>
+                </td>
+            </tr>
+            <tr>
+                <th>
+                    <label><?php echo IMG_LBL_SAVE_TO; ?></label>
+                </th>
+                <td>
+                    <select class="input" name="save_to" id="save_to"></select>
+                </td>
+            </tr>
+            <tr>
+                <th>&nbsp;
+                </th>
+                <td>
+                    <span class="comments">*</span>
+                    <?php echo IMG_NEW_NAME_COMMENTS; ?>
+                </td>
+            </tr>
+            </tbody>
+            <tfoot>
+            <tr>
+                <th>&nbsp;</th>
+                <td><input type="button" class="button" value="<?php echo IMG_BTN_SAVE_AS; ?>"
+                           onclick="return saveAsImage();"/></td>
+            </tr>
+            </tfoot>
+        </table>
+    </form>
+</div>
 </body>
 </html>

+ 165 - 194
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_save.php

@@ -1,195 +1,166 @@
 <?php
-	/**
-	 * image save function
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");	
-	
-
-	$error = "";
-	$info = "";
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE)
-	{
-		$error = SYS_DISABLED;
-	}
-	elseif(empty($_POST['path']))
-	{
-		$error  =  IMG_SAVE_EMPTY_PATH;
-	}elseif(!file_exists($_POST['path']))
-	{		
-		$error  =  IMG_SAVE_NOT_EXISTS;
-	}elseif(!isUnderRoot($_POST['path']))
-	{
-		$error = IMG_SAVE_PATH_DISALLOWED;
-	}elseif(($sessionDir = $session->getSessionDir()) == '')
-	{
-		$error = SESSION_PERSONAL_DIR_NOT_FOUND;
-	}
-	else
-	{	
-		require_once(CLASS_HISTORY);
-		$history = new History($_POST['path'], $session);
-		if(!empty($_POST['mode']))
-		{
-			//get the original image which is the lastest session image if any when the system is in demo
-			$lastestSessionImageInfo = $history->getLastestRestorable();
-			if(sizeof($lastestSessionImageInfo) && CONFIG_SYS_DEMO_ENABLE)
-			{				
-				$originalSessionImageInfo = $history->getOriginalImage();
-				if(sizeof($originalSessionImageInfo))
-				{					
-					$originalImage = $sessionDir . $originalSessionImageInfo['info']['name'];
-				}				
-			}
-			if(empty($originalImage))
-			{
-				$originalImage = $_POST['path'];
-			}
-			
-			include_once(CLASS_IMAGE);
-			$image = new ImageAjaxFileManager();
-			if($image->loadImage($originalImage))
-			{				
-				
-				switch($_POST['mode'])
-				{
-					case "resize":					
-						if(!$image->resize($_POST['width'], $_POST['height'], (!empty($_POST['constraint'])?true:false)))
-						{
-							$error = IMG_SAVE_RESIZE_FAILED;
-						}					
-						break;
-					case "crop":	
-						if(!$image->crop($_POST['x'], $_POST['y'], $_POST['width'], $_POST['height']))
-						{
-							$error = IMG_SAVE_CROP_FAILED;
-						}
-						break;
-					case "flip":
-						if(!$image->flip($_POST['flip_angle']))
-						{
-							$error = IMG_SAVE_FLIP_FAILED;
-						}
-						break;
-					case "rotate":
-						
-						if(!$image->rotate(intval($_POST['angle'])))
-						{
-							$error = IMG_SAVE_ROTATE_FAILED;
-						}
-						
-						break;
-					default:
-						$error = IMG_SAVE_UNKNOWN_MODE;
-				}
-				
-				
-				if(empty($error))
-				{					
-					$sessionNewPath = $sessionDir  . uniqid(md5(time())) . "." . getFileExt($_POST['path']);					
-					if(!@copy($originalImage, $sessionNewPath))
-					{//keep a copy under the session folder
-						$error = IMG_SAVE_BACKUP_FAILED;						
-					}else 
-					{
-						
-						$isSaveAsRequest = (!empty($_POST['new_name']) && !empty($_POST['save_to'])?true:false);
-						//save the modified image
-						$sessionImageInfo = array('name'=>basename($sessionNewPath), 'restorable'=>1);
-						$history->add($sessionImageInfo);
-						if(CONFIG_SYS_DEMO_ENABLE)
-						{//demo only
-							if(isset($originalSessionImageInfo) && sizeof($originalSessionImageInfo))
-							{
-								$imagePath = $sessionDir . $originalSessionImageInfo['info']['name'];
-							}else 
-							{	
-								$imagePath = $sessionDir  . uniqid(md5(time())) . "." . getFileExt($_POST['path']);
-							}
-						}else 
-						{	
-							if($isSaveAsRequest)
-							{//save as request
-								//check save to folder if exists
-								$imagePath = addTrailingSlash(backslashToSlash($_POST['save_to'])) . $_POST['new_name'] . "." . getFileExt($_POST['path']); 
-								
-								if(!file_exists($_POST['save_to']) || !is_dir($_POST['save_to']))
-								{
-									$error = IMG_SAVE_AS_FOLDER_NOT_FOUND;
-								}elseif(file_exists($imagePath)) 
-								{
-									$error = IMG_SAVE_AS_NEW_IMAGE_EXISTS;
-								}elseif(!preg_match("/^[a-zA-Z0-9_\- ]+$/", $_POST['new_name']))
-								{
-									$error = IMG_SAVE_AS_ERR_NAME_INVALID;
-								}
-								
-							}else 
-							{//save request
-								$imagePath = $originalImage;	
-							}
-												
-						}
-
-						if($image->saveImage($imagePath))
-						{		
-									
-							if(CONFIG_SYS_DEMO_ENABLE)
-							{
-								if(!isset($originalSessionImageInfo) || !sizeof($originalSessionImageInfo))
-								{//keep this original image information on session for future reference if demo only	
-									$originalSessionImageInfo = array('name'=>basename($imagePath), 'restorable'=>0, 'is_original'=>1);
-									$history->add($originalSessionImageInfo);
-								}
-							}
-							$imageInfo = $image->getFinalImageInfo();								
-						}else 
-						{
-							$error = IMG_SAVE_FAILED;
-							
-						}							
-						if(isset($imageInfo))
-						{
-								$info .= ",width:" . $imageInfo['width'] . "";
-								$info .= ",height:" . $imageInfo['height'] . "";
-								$info .= ",size:'" . transformFileSize($imageInfo['size']) . "'";
-								if($isSaveAsRequest)
-								{
-									$info .= ",save_as:'1'";
-								}else 
-								{
-									$info .= ",save_as:'0'";
-								}
-								$info .= ",folder_path:'" . dirname($imagePath) . "'";
-								$info .= ",path:'" . backslashToSlash($imagePath) . "'";	
-													
-						}				
-			
-					}				
-								
-				}			
-			}else 
-			{
-				$error = IMG_SAVE_IMG_OPEN_FAILED . $originalImage;
-			}		
-
-		}else 
-		{
-			$error = IMG_SAVE_UNKNOWN_MODE;
-		}
-	}
-	echo "{";	
-	echo "error:'" . $error . "'";
-	if(isset($image) && is_object($image))
-	{
-		$image->DestroyImages();
-	}
-	echo $info;
-	echo ",history:" . (isset($history) && is_object($history)?($history->getNumRestorable()):0)  . "";
-	echo "}";
-	
-	
-?>
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+$error = "";
+$info  = "";
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE) {
+    $error = SYS_DISABLED;
+} elseif (empty($_POST['path'])) {
+    $error = IMG_SAVE_EMPTY_PATH;
+} elseif (!file_exists($_POST['path'])) {
+    $error = IMG_SAVE_NOT_EXISTS;
+} elseif (!isUnderRoot($_POST['path'])) {
+    $error = IMG_SAVE_PATH_DISALLOWED;
+} elseif (($sessionDir = $session->getSessionDir()) == '') {
+    $error = SESSION_PERSONAL_DIR_NOT_FOUND;
+} else {
+    require_once(CLASS_HISTORY);
+    $history = new History($_POST['path'], $session);
+    if (!empty($_POST['mode'])) {
+        //get the original image which is the lastest session image if any when the system is in demo
+        $lastestSessionImageInfo = $history->getLastestRestorable();
+        if (sizeof($lastestSessionImageInfo) && CONFIG_SYS_DEMO_ENABLE) {
+            $originalSessionImageInfo = $history->getOriginalImage();
+            if (sizeof($originalSessionImageInfo)) {
+                $originalImage = $sessionDir.$originalSessionImageInfo['info']['name'];
+            }
+        }
+        if (empty($originalImage)) {
+            $originalImage = $_POST['path'];
+        }
+
+        include_once(CLASS_IMAGE);
+        $image = new ImageAjaxFileManager();
+        if ($image->loadImage($originalImage)) {
+
+            switch ($_POST['mode']) {
+                case "resize":
+                    if (!$image->resize(
+                        $_POST['width'],
+                        $_POST['height'],
+                        (!empty($_POST['constraint']) ? true : false)
+                    )
+                    ) {
+                        $error = IMG_SAVE_RESIZE_FAILED;
+                    }
+                    break;
+                case "crop":
+                    if (!$image->crop($_POST['x'], $_POST['y'], $_POST['width'], $_POST['height'])) {
+                        $error = IMG_SAVE_CROP_FAILED;
+                    }
+                    break;
+                case "flip":
+                    if (!$image->flip($_POST['flip_angle'])) {
+                        $error = IMG_SAVE_FLIP_FAILED;
+                    }
+                    break;
+                case "rotate":
+
+                    if (!$image->rotate(intval($_POST['angle']))) {
+                        $error = IMG_SAVE_ROTATE_FAILED;
+                    }
+
+                    break;
+                default:
+                    $error = IMG_SAVE_UNKNOWN_MODE;
+            }
+
+
+            if (empty($error)) {
+                $sessionNewPath = $sessionDir.uniqid(md5(time())).".".getFileExt($_POST['path']);
+                if (!@copy($originalImage, $sessionNewPath)) { //keep a copy under the session folder
+                    $error = IMG_SAVE_BACKUP_FAILED;
+                } else {
+
+                    $isSaveAsRequest = (!empty($_POST['new_name']) && !empty($_POST['save_to']) ? true : false);
+                    //save the modified image
+                    $sessionImageInfo = array('name' => basename($sessionNewPath), 'restorable' => 1);
+                    $history->add($sessionImageInfo);
+                    if (CONFIG_SYS_DEMO_ENABLE) { //demo only
+                        if (isset($originalSessionImageInfo) && sizeof($originalSessionImageInfo)) {
+                            $imagePath = $sessionDir.$originalSessionImageInfo['info']['name'];
+                        } else {
+                            $imagePath = $sessionDir.uniqid(md5(time())).".".getFileExt($_POST['path']);
+                        }
+                    } else {
+                        if ($isSaveAsRequest) { //save as request
+                            //check save to folder if exists
+                            $imagePath = addTrailingSlash(
+                                    backslashToSlash($_POST['save_to'])
+                                ).$_POST['new_name'].".".getFileExt($_POST['path']);
+
+                            if (!file_exists($_POST['save_to']) || !is_dir($_POST['save_to'])) {
+                                $error = IMG_SAVE_AS_FOLDER_NOT_FOUND;
+                            } elseif (file_exists($imagePath)) {
+                                $error = IMG_SAVE_AS_NEW_IMAGE_EXISTS;
+                            } elseif (!preg_match("/^[a-zA-Z0-9_\- ]+$/", $_POST['new_name'])) {
+                                $error = IMG_SAVE_AS_ERR_NAME_INVALID;
+                            }
+
+                        } else { //save request
+                            $imagePath = $originalImage;
+                        }
+
+                    }
+
+                    if ($image->saveImage($imagePath)) {
+
+                        if (CONFIG_SYS_DEMO_ENABLE) {
+                            if (!isset($originalSessionImageInfo) || !sizeof(
+                                    $originalSessionImageInfo
+                                )
+                            ) { //keep this original image information on session for future reference if demo only
+                                $originalSessionImageInfo = array(
+                                    'name'        => basename($imagePath),
+                                    'restorable'  => 0,
+                                    'is_original' => 1
+                                );
+                                $history->add($originalSessionImageInfo);
+                            }
+                        }
+                        $imageInfo = $image->getFinalImageInfo();
+                    } else {
+                        $error = IMG_SAVE_FAILED;
+
+                    }
+                    if (isset($imageInfo)) {
+                        $info .= ",width:".$imageInfo['width']."";
+                        $info .= ",height:".$imageInfo['height']."";
+                        $info .= ",size:'".transformFileSize($imageInfo['size'])."'";
+                        if ($isSaveAsRequest) {
+                            $info .= ",save_as:'1'";
+                        } else {
+                            $info .= ",save_as:'0'";
+                        }
+                        $info .= ",folder_path:'".dirname($imagePath)."'";
+                        $info .= ",path:'".backslashToSlash($imagePath)."'";
+
+                    }
+
+                }
+
+            }
+        } else {
+            $error = IMG_SAVE_IMG_OPEN_FAILED.$originalImage;
+        }
+
+    } else {
+        $error = IMG_SAVE_UNKNOWN_MODE;
+    }
+}
+echo "{";
+echo "error:'".$error."'";
+if (isset($image) && is_object($image)) {
+    $image->DestroyImages();
+}
+echo $info;
+echo ",history:".(isset($history) && is_object($history) ? ($history->getNumRestorable()) : 0)."";
+echo "}";

+ 18 - 14
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_thumbnail.php

@@ -1,4 +1,6 @@
 <?php
+/* For licensing terms, see /license.txt */
+
 /**
  * ajax preview
  * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
@@ -7,20 +9,22 @@
  *
  */
 
-include_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");	
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
 $path = base64_decode($_GET['path']);
-if(!empty($path) && file_exists($path) && is_file($path)) {
-	require_once CLASS_IMAGE;	
-	$image = new ImageAjaxFileManager(true);
-	if($image->loadImage($path)) {
-		if($image->resize(CONFIG_IMG_THUMBNAIL_MAX_X, CONFIG_IMG_THUMBNAIL_MAX_Y, true, true)) {
-			$image->showImage();
-		} else {
-			echo PREVIEW_NOT_PREVIEW . ".";	
-		}
-	} else {
-		echo PREVIEW_NOT_PREVIEW . "..";			
-	}		
+if (!empty($path) && file_exists($path) && is_file($path)) {
+    require_once CLASS_IMAGE;
+    $image = new ImageAjaxFileManager(true);
+    if ($image->loadImage($path)) {
+        if ($image->resize(CONFIG_IMG_THUMBNAIL_MAX_X, CONFIG_IMG_THUMBNAIL_MAX_Y, true, true)) {
+            $image->showImage();
+        } else {
+            echo PREVIEW_NOT_PREVIEW.".";
+        }
+    } else {
+        echo PREVIEW_NOT_PREVIEW."..";
+    }
 } else {
-	echo PREVIEW_NOT_PREVIEW . "...";
+    echo PREVIEW_NOT_PREVIEW."...";
 }

+ 79 - 91
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_image_undo.php

@@ -1,94 +1,82 @@
 <?php
-	/**
-	 * ajax image undo function
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");	
-	require_once(CLASS_HISTORY);
-	$history = new History($_POST['file_path'], $session);
-	$lastestSessionImageInfo = $history->getLastestRestorable();
-	echo "{";
-	$error = "";
-	$info = "";
-	if(CONFIG_SYS_VIEW_ONLY)
-	{
-		$error = SYS_DISABLED;
-	}
-	elseif(empty($_POST['file_path']))
-	{
-		$error  =  IMG_SAVE_EMPTY_PATH;
-	}elseif(!file_exists($_POST['file_path']))
-	{
-		$error  =  IMG_SAVE_NOT_EXISTS;
-	}elseif(!isUnderRoot($_POST['file_path']))
-	{
-		$error = IMG_SAVE_PATH_DISALLOWED;
-	}else if(!sizeof($lastestSessionImageInfo))
-	{
-		$error = IMG_UNDO_NO_HISTORY_AVAIALBE;
-	}
-	else
-	{		
-			//get the original image which is the lastest session image if any when the system is in demo
-			$sessionImage = $session->getSessionDir() . $lastestSessionImageInfo['name'];
-			$originalSessionImageInfo = $history->getOriginalImage();
-			if(CONFIG_SYS_DEMO_ENABLE && sizeof($originalSessionImageInfo))
-			{
-				$originalImage = $session->getSessionDir() . $originalSessionImageInfo['info']['name'];				
-			}else 
-			{
-				$originalImage = $_POST['file_path'];
-			}		
-			 
-				include_once(CLASS_IMAGE);
-				$image = new ImageAjaxFileManager();
-				if($image->loadImage($sessionImage))
-				{
-					$imageInfo = $image->getOriginalImageInfo();
-					if(!@copy($sessionImage, $originalImage))
-					{
-						$error = IMG_UNDO_COPY_FAILED;
-					}else 
-					{
-						
-						//remove the session image
-						if(@unlink($sessionImage))
-						{
-							$history->restore();
-						}
-						//only one left, remove the session original if demo
-						
-						if($history->getNumRestorable() == 0 && CONFIG_SYS_DEMO_ENABLE && sizeof($originalSessionImageInfo))
-						{
-							@unlink($session->getSessionDir() . $originalSessionImageInfo['info']['name']);	
-							$originalImage = $_POST['file_path'];
-						}
-					}
-					$imagePath = $originalImage;
-					
-				}else 
-				{
-					$error = IMG_SAVE_IMG_OPEN_FAILED;
-				}
-					if(isset($imageInfo))
-					{
-							$info .= ",width:" . $imageInfo['width'] . "\n";
-							$info .= ",height:" . $imageInfo['height'] . "\n";
-							$info .= ",size:'" . transformFileSize($imageInfo['size']) . "'\n";
-							$info .= ",path:'" . backslashToSlash($imagePath) . "'\n";						
-					}	
+/* For licensing terms, see /license.txt */
 
-	}
-	
-	echo "error:'" . $error . "'\n";
-	if(isset($image) && is_object($image))
-	{
-		$image->DestroyImages();
-	}
-	echo $info;
-	echo ",history:" . ($history->getNumRestorable()) . "\n";
-	echo "}";
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+require_once(CLASS_HISTORY);
+$history                 = new History($_POST['file_path'], $session);
+$lastestSessionImageInfo = $history->getLastestRestorable();
+echo "{";
+$error = "";
+$info  = "";
+if (CONFIG_SYS_VIEW_ONLY) {
+    $error = SYS_DISABLED;
+} elseif (empty($_POST['file_path'])) {
+    $error = IMG_SAVE_EMPTY_PATH;
+} elseif (!file_exists($_POST['file_path'])) {
+    $error = IMG_SAVE_NOT_EXISTS;
+} elseif (!isUnderRoot($_POST['file_path'])) {
+    $error = IMG_SAVE_PATH_DISALLOWED;
+} else {
+    if (!sizeof($lastestSessionImageInfo)) {
+        $error = IMG_UNDO_NO_HISTORY_AVAIALBE;
+    } else {
+        //get the original image which is the lastest session image if any when the system is in demo
+        $sessionImage             = $session->getSessionDir().$lastestSessionImageInfo['name'];
+        $originalSessionImageInfo = $history->getOriginalImage();
+        if (CONFIG_SYS_DEMO_ENABLE && sizeof($originalSessionImageInfo)) {
+            $originalImage = $session->getSessionDir().$originalSessionImageInfo['info']['name'];
+        } else {
+            $originalImage = $_POST['file_path'];
+        }
+
+        include_once(CLASS_IMAGE);
+        $image = new ImageAjaxFileManager();
+        if ($image->loadImage($sessionImage)) {
+            $imageInfo = $image->getOriginalImageInfo();
+            if (!@copy($sessionImage, $originalImage)) {
+                $error = IMG_UNDO_COPY_FAILED;
+            } else {
+
+                //remove the session image
+                if (@unlink($sessionImage)) {
+                    $history->restore();
+                }
+                //only one left, remove the session original if demo
+
+                if ($history->getNumRestorable() == 0 && CONFIG_SYS_DEMO_ENABLE && sizeof($originalSessionImageInfo)) {
+                    @unlink($session->getSessionDir().$originalSessionImageInfo['info']['name']);
+                    $originalImage = $_POST['file_path'];
+                }
+            }
+            $imagePath = $originalImage;
+
+        } else {
+            $error = IMG_SAVE_IMG_OPEN_FAILED;
+        }
+        if (isset($imageInfo)) {
+            $info .= ",width:".$imageInfo['width']."\n";
+            $info .= ",height:".$imageInfo['height']."\n";
+            $info .= ",size:'".transformFileSize($imageInfo['size'])."'\n";
+            $info .= ",path:'".backslashToSlash($imagePath)."'\n";
+        }
+
+    }
+}
+
+echo "error:'".$error."'\n";
+if (isset($image) && is_object($image)) {
+    $image->DestroyImages();
+}
+echo $info;
+echo ",history:".($history->getNumRestorable())."\n";
+echo "}";
 ?>

+ 46 - 44
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_login.php

@@ -1,56 +1,58 @@
 <?php
-	/**
-	 * access control login form
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/April/2007
-	 *
-	 */
-require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-if(isset($_POST['username']))
-{
-	if($auth->login())
-	{
-		header('Location: ' . appendQueryString(CONFIG_URL_HOME, makeQueryString()));
-		exit;		
-	}
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+if (isset($_POST['username'])) {
+    if ($auth->login()) {
+        header('Location: '.appendQueryString(CONFIG_URL_HOME, makeQueryString()));
+        exit;
+    }
 }
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<!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">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<link type="text/css" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/login.css" rel="stylesheet" />
-<title><?php echo LOGIN_PAGE_TITLE; ?></title>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+    <link type="text/css" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/login.css" rel="stylesheet"/>
+    <title><?php echo LOGIN_PAGE_TITLE; ?></title>
 </head>
 <body>
 <div id="container">
     <div id="content">
-			<form name="frmLogin" method="post" action="">
-			    <table class="adminLoginTable" cellpadding="0" cellspacing="0">
-			        <thead>
-			            <tr>
-			                <th colspan="2"><?php echo LOGIN_FORM_TITLE; ?></th>
-			            </tr>
-			        </thead>
-			        <tbody>
-			            <tr>
-			                <th class="padTop"><label><?php echo LOGIN_USERNAME; ?> </label></th>
-			                <td class="padTop"><input type="text" value="" class="input" name="username" id="username" /></td>
-			            </tr>
-			            <tr>
-			                <th><label><?php echo LOGIN_PASSWORD; ?> </label></th>
-			                <td><input type="password" value="" class="input" name="password" id="password" /></td>
-			            </tr>
-			        </tbody>
-			        <tfoot>
-			            <tr>
-			            	<td>&nbsp;</td>
-			              <td><input type="submit" class="button" value="Login" /></td>
-			            </tr>			        
-			        </tfoot>
-			    </table>
-			</form>
+        <form name="frmLogin" method="post" action="">
+            <table class="adminLoginTable" cellpadding="0" cellspacing="0">
+                <thead>
+                <tr>
+                    <th colspan="2"><?php echo LOGIN_FORM_TITLE; ?></th>
+                </tr>
+                </thead>
+                <tbody>
+                <tr>
+                    <th class="padTop"><label><?php echo LOGIN_USERNAME; ?> </label></th>
+                    <td class="padTop"><input type="text" value="" class="input" name="username" id="username"/></td>
+                </tr>
+                <tr>
+                    <th><label><?php echo LOGIN_PASSWORD; ?> </label></th>
+                    <td><input type="password" value="" class="input" name="password" id="password"/></td>
+                </tr>
+                </tbody>
+                <tfoot>
+                <tr>
+                    <td>&nbsp;</td>
+                    <td><input type="submit" class="button" value="Login"/></td>
+                </tr>
+                </tfoot>
+            </table>
+        </form>
     </div>
 </div>
 </body>

+ 39 - 34
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_preview.php

@@ -1,43 +1,48 @@
 <?php
+/* For licensing terms, see /license.txt */
 /**
- * AJAX preview
  * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
- * @author Julio Montoya - adding support for chamilo
  * @link www.phpletter.com
  * @since 22/April/2007
  *
  */
-include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php";	
-api_block_anonymous_users();	
-if (!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path'])) {		
-	include_once(CLASS_MANAGER);
-	$manager = new manager($_GET['path'], false);
-	$fileTypes = $manager->getFileType(basename($_GET['path']));
-	if ($fileTypes['preview']) {
-		switch($fileTypes['fileType']) {
-			case "image":
-				$imageInfo = @getimagesize($_GET['path']);
-				if(!empty($imageInfo[0]) && !empty($imageInfo[1])) {
-					$thumInfo = getThumbWidthHeight($imageInfo[0], $imageInfo[1], 400, 135);
-					printf("<img src=\"%s\" width=\"%s\" height=\"%s\" />", getFileUrl($_GET['path']), $thumInfo['width'], $thumInfo['height']);													
-				} else {
-					echo PREVIEW_IMAGE_LOAD_FAILED;
-				}
-				break;
-			case "txt":
-				if(($fp = @fopen($_GET['path'], 'r'))) {
-					echo @fread($fp, @filesize($_GET['path']));
-					@fclose($fp);
-				} else {
-					echo PREVIEW_OPEN_FAILED . ".";
-				}
-				break;					
-			case "video":
-				break;
-		}
-	} else {
-		echo PREVIEW_NOT_PREVIEW . "..";
-	}				
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+if (!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path'])) {
+    include_once(CLASS_MANAGER);
+    $manager   = new manager($_GET['path'], false);
+    $fileTypes = $manager->getFileType(basename($_GET['path']));
+    if ($fileTypes['preview']) {
+        switch ($fileTypes['fileType']) {
+            case "image":
+                $imageInfo = @getimagesize($_GET['path']);
+                if (!empty($imageInfo[0]) && !empty($imageInfo[1])) {
+                    $thumInfo = getThumbWidthHeight($imageInfo[0], $imageInfo[1], 400, 135);
+                    printf(
+                        "<img src=\"%s\" width=\"%s\" height=\"%s\" />",
+                        getFileUrl($_GET['path']),
+                        $thumInfo['width'],
+                        $thumInfo['height']
+                    );
+                } else {
+                    echo PREVIEW_IMAGE_LOAD_FAILED;
+                }
+                break;
+            case "txt":
+                if (($fp = @fopen($_GET['path'], 'r'))) {
+                    echo @fread($fp, @filesize($_GET['path']));
+                    @fclose($fp);
+                } else {
+                    echo PREVIEW_OPEN_FAILED.".";
+                }
+                break;
+            case "video":
+                break;
+        }
+    } else {
+        echo PREVIEW_NOT_PREVIEW."..";
+    }
 } else {
-	echo PREVIEW_NOT_PREVIEW . "...";
+    echo PREVIEW_NOT_PREVIEW."...";
 }

+ 46 - 35
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_as_form.php

@@ -1,57 +1,68 @@
-<?php 
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<!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">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<title>Untitled Document</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+    <title>Untitled Document</title>
 </head>
 
 <body>
-    	<a href="#" class="jqmClose" id="windowSaveClose"><?php echo IMG_BTN_CANCEL; ?></a>
-      <form id="formSaveAs" name="formSaveAs" action="" method="post">
-    	<table class="tableForm" cellpadding="0" cellspacing="0">
-      	<thead>
-        	<tr>
-          	<th colspan="2"><?php echo IMG_LBL_SAVE_AS; ?></th>
-          </tr>
+<a href="#" class="jqmClose" id="windowSaveClose"><?php echo IMG_BTN_CANCEL; ?></a>
+
+<form id="formSaveAs" name="formSaveAs" action="" method="post">
+    <table class="tableForm" cellpadding="0" cellspacing="0">
+        <thead>
+        <tr>
+            <th colspan="2"><?php echo IMG_LBL_SAVE_AS; ?></th>
+        </tr>
         </thead>
         <tbody>
-        	<tr>
-          	<th>
-            	<label><?php echo IMG_LBL_NEW_NAME; ?></label>
+        <tr>
+            <th>
+                <label><?php echo IMG_LBL_NEW_NAME; ?></label>
             </th>
             <td>
-            	<input type="text" id="new_name" class="input" name="new_name" value="" />
+                <input type="text" id="new_name" class="input" name="new_name" value=""/>
             </td>
-          </tr>
-          <tr>
-          	<th>
-            	<label><?php echo IMG_LBL_SAVE_TO; ?></label>
+        </tr>
+        <tr>
+            <th>
+                <label><?php echo IMG_LBL_SAVE_TO; ?></label>
             </th>
             <td>
-            	<select class="input" name="save_to">
-              	
-              </select>
+                <select class="input" name="save_to">
+
+                </select>
             </td>
-          </tr>
-          <tr>
-          	<th>&nbsp;
+        </tr>
+        <tr>
+            <th>&nbsp;
             </th>
             <td>
-            <span class="comments">*</span>
-            <?php echo IMG_NEW_NAME_COMMENTS; ?>
+                <span class="comments">*</span>
+                <?php echo IMG_NEW_NAME_COMMENTS; ?>
             </td>
-          </tr>
+        </tr>
         </tbody>
         <tfoot>
-        	<tr>
-        	<th>&nbsp;</th>
-          <td><input type="button" class="button" value="<?php echo IMG_BTN_SAVE_AS; ?>" onclick="return saveAsImage();" /></td>
-          </tr>
+        <tr>
+            <th>&nbsp;</th>
+            <td><input type="button" class="button" value="<?php echo IMG_BTN_SAVE_AS; ?>"
+                       onclick="return saveAsImage();"/></td>
+        </tr>
         </tfoot>
-      </table>
+    </table>
 </body>
 </html>

+ 81 - 79
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_name.php

@@ -1,81 +1,83 @@
 <?php
-	/**
-	 * ajax save name
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	$error = '';
-	$fileInfo = array();
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_RENAME)
-	{
-		$error = SYS_DISABLED;
-	}
-	elseif(empty($_POST['name']))
-	{
-		$error = ERR_RENAME_EMPTY;
-	}elseif(!preg_match("/^[a-zA-Z0-9 _\-.]+$/", $_POST['name']))
-	{
-		$error = ERR_RENAME_FORMAT;
-	}elseif(empty($_POST['original_path']) || !file_exists($_POST['original_path']))
-	{
-		$error = ERR_RENAME_FILE_NOT_EXISTS;
-	}elseif(substr(slashToBackslash(removeTrailingSlash($_POST['original_path'])), strrpos(slashToBackslash(removeTrailingSlash($_POST['original_path'])), "/") + 1) == $_POST['name'])
-	{
-		$error = ERR_NO_CHANGES_MADE;
-	}elseif(file_exists(addTrailingSlash(getParentPath($_POST['original_path'])) . $_POST['name']))
-	{
-		$error = ERR_RENAME_EXISTS;
-	}elseif(is_file($_POST['original_path']) && !isValidExt($_POST['name'], explode(",", CONFIG_UPLOAD_VALID_EXTS), explode(",", CONFIG_UPLOAD_INVALID_EXTS)))
-	{
-		$error = ERR_RENAME_FILE_TYPE_NOT_PERMITED;
-	}elseif(!rename(removeTrailingSlash($_POST['original_path']), addTrailingSlash(getParentPath($_POST['original_path'])) . $_POST['name']))
-	{
-		$error = ERR_RENAME_FAILED;
-	}else 
-	{
-		//update record of session if image exists in session for cut or copy
-		include_once(CLASS_SESSION_ACTION);
-		$sessionAction = new SessionAction();		
-		$selectedDocuments = $sessionAction->get();
-		if(removeTrailingSlash($sessionAction->getFolder()) == getParentPath($_POST['original_path']) && sizeof($selectedDocuments))
-		{
-			if(($key = array_search(basename($_POST['original_path']), $selectedDocuments)) !== false)
-			{
-				$selectedDocuments[$key] = $_POST['name'];
-				$sessionAction->set($selectedDocuments);
-				
-			}
-			
-		}elseif(removeTrailingSlash($sessionAction->getFolder()) == removeTrailingSlash($_POST['original_path']))
-		{
-			$sessionAction->setFolder($_POST['original_path']);
-		}	
-		$path = addTrailingSlash(getParentPath($_POST['original_path'])) . $_POST['name'];
-		if(is_file($path))
-		{
-			include_once(CLASS_FILE);
-			$file = new file($path);
-			$fileInfo = $file->getFileInfo();
-			$fileInfo['mtime'] = date(DATE_TIME_FORMAT,$fileInfo['mtime']);
-		}else
-		{
-			include_once(CLASS_MANAGER);
-			$manager = new manager($path, false);
-			$fileInfo = $manager->getFolderInfo();
-			$fileInfo['mtime'] = date(DATE_TIME_FORMAT,$fileInfo['mtime']);
-		}
-	}
-	
-	echo "{";
-	echo "error:'" . $error . "' ";
-	foreach ($fileInfo as $k=>$v)
-	{
-		echo "," . $k . ":'" . $v . "' ";
-	}
-	echo "}";
-	
-	
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+$error    = '';
+$fileInfo = array();
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_RENAME) {
+    $error = SYS_DISABLED;
+} elseif (empty($_POST['name'])) {
+    $error = ERR_RENAME_EMPTY;
+} elseif (!preg_match("/^[a-zA-Z0-9 _\-.]+$/", $_POST['name'])) {
+    $error = ERR_RENAME_FORMAT;
+} elseif (empty($_POST['original_path']) || !file_exists($_POST['original_path'])) {
+    $error = ERR_RENAME_FILE_NOT_EXISTS;
+} elseif (substr(
+        slashToBackslash(removeTrailingSlash($_POST['original_path'])),
+        strrpos(slashToBackslash(removeTrailingSlash($_POST['original_path'])), "/") + 1
+    ) == $_POST['name']
+) {
+    $error = ERR_NO_CHANGES_MADE;
+} elseif (file_exists(addTrailingSlash(getParentPath($_POST['original_path'])).$_POST['name'])) {
+    $error = ERR_RENAME_EXISTS;
+} elseif (is_file($_POST['original_path']) && !isValidExt(
+        $_POST['name'],
+        explode(",", CONFIG_UPLOAD_VALID_EXTS),
+        explode(",", CONFIG_UPLOAD_INVALID_EXTS)
+    )
+) {
+    $error = ERR_RENAME_FILE_TYPE_NOT_PERMITED;
+} elseif (!rename(
+    removeTrailingSlash($_POST['original_path']),
+    addTrailingSlash(getParentPath($_POST['original_path'])).$_POST['name']
+)
+) {
+    $error = ERR_RENAME_FAILED;
+} else {
+    //update record of session if image exists in session for cut or copy
+    include_once(CLASS_SESSION_ACTION);
+    $sessionAction     = new SessionAction();
+    $selectedDocuments = $sessionAction->get();
+    if (removeTrailingSlash($sessionAction->getFolder()) == getParentPath($_POST['original_path']) && sizeof(
+            $selectedDocuments
+        )
+    ) {
+        if (($key = array_search(basename($_POST['original_path']), $selectedDocuments)) !== false) {
+            $selectedDocuments[$key] = $_POST['name'];
+            $sessionAction->set($selectedDocuments);
+
+        }
+
+    } elseif (removeTrailingSlash($sessionAction->getFolder()) == removeTrailingSlash($_POST['original_path'])) {
+        $sessionAction->setFolder($_POST['original_path']);
+    }
+    $path = addTrailingSlash(getParentPath($_POST['original_path'])).$_POST['name'];
+    if (is_file($path)) {
+        include_once(CLASS_FILE);
+        $file              = new file($path);
+        $fileInfo          = $file->getFileInfo();
+        $fileInfo['mtime'] = date(DATE_TIME_FORMAT, $fileInfo['mtime']);
+    } else {
+        include_once(CLASS_MANAGER);
+        $manager           = new manager($path, false);
+        $fileInfo          = $manager->getFolderInfo();
+        $fileInfo['mtime'] = date(DATE_TIME_FORMAT, $fileInfo['mtime']);
+    }
+}
+
+echo "{";
+echo "error:'".$error."' ";
+foreach ($fileInfo as $k => $v) {
+    echo ",".$k.":'".$v."' ";
+}
+echo "}";
+
+
 ?>

+ 64 - 84
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_text.php

@@ -1,88 +1,68 @@
 <?php
-	/**
-	 * ajax save name
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	$error = '';
-	$path = addTrailingSlash(backslashToSlash($_POST['folder'])) . $_POST['name'];
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE)
-	{
-		$error = SYS_DISABLED;
-	}
-	elseif(isset($_POST['save_as_request']))
-	{		
-		if(!preg_match('/^[a-zA-Z0-9_\-.]+$/', $_POST['name']))
-		{
-			$error = TXT_SAVE_AS_ERR_NAME_INVALID;
-		}elseif(array_search(strtolower(getFileExt($_POST['name'])), getValidTextEditorExts()) === false)
-		{
-			$error = TXT_DISALLOWED_EXT;
-		}elseif(!isUnderRoot($_POST['folder']))
-		{
-			$error = ERR_FOLDER_PATH_NOT_ALLOWED;
-		}
-		else
-		{
-			
-			if(!empty($_POST['save_as_request']))
-			{//save as request
-				if(file_exists($path))
-				{
-					$error = TXT_FILE_EXIST;
-				}else 
-				{
-					if(($fp = @fopen($path, 'w+')) !== false)
-					{
-						if(@fwrite($fp, $_POST['text']))
-						{
-							@fclose($fp);
-						}else 
-						{
-							$error = TXT_CONTENT_WRITE_FAILED;
-						}
-					}else 
-					{
-						$error = TXT_CREATE_FAILED;
-					}					
-				}
+/* For licensing terms, see /license.txt */
+/**
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/April/2007
+ *
+ */
 
-				
-			}else 
-			{
-				if(!file_exists($path))
-				{
-					$error = TXT_FILE_NOT_EXIST;
-				}else 
-				{
-					if(($fp = @fopen($path, 'w')) !== false)
-					{
-						if(@fwrite($fp, $_POST['text']))
-						{
-							@fclose($fp);
-						}else 
-						{
-							$error = TXT_CONTENT_UPDATE_FAILED;
-						}
-					}else 
-					{
-						$error = TXT_FILE_OPEN_FAILED;
-					}						
-				}
-			}
-			
-		}
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+$error = '';
+$path  = addTrailingSlash(backslashToSlash($_POST['folder'])).$_POST['name'];
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE) {
+    $error = SYS_DISABLED;
+} elseif (isset($_POST['save_as_request'])) {
+    if (!preg_match('/^[a-zA-Z0-9_\-.]+$/', $_POST['name'])) {
+        $error = TXT_SAVE_AS_ERR_NAME_INVALID;
+    } elseif (array_search(strtolower(getFileExt($_POST['name'])), getValidTextEditorExts()) === false) {
+        $error = TXT_DISALLOWED_EXT;
+    } elseif (!isUnderRoot($_POST['folder'])) {
+        $error = ERR_FOLDER_PATH_NOT_ALLOWED;
+    } else {
+
+        if (!empty($_POST['save_as_request'])) { //save as request
+            if (file_exists($path)) {
+                $error = TXT_FILE_EXIST;
+            } else {
+                if (($fp = @fopen($path, 'w+')) !== false) {
+                    if (@fwrite($fp, $_POST['text'])) {
+                        @fclose($fp);
+                    } else {
+                        $error = TXT_CONTENT_WRITE_FAILED;
+                    }
+                } else {
+                    $error = TXT_CREATE_FAILED;
+                }
+            }
+
+
+        } else {
+            if (!file_exists($path)) {
+                $error = TXT_FILE_NOT_EXIST;
+            } else {
+                if (($fp = @fopen($path, 'w')) !== false) {
+                    if (@fwrite($fp, $_POST['text'])) {
+                        @fclose($fp);
+                    } else {
+                        $error = TXT_CONTENT_UPDATE_FAILED;
+                    }
+                } else {
+                    $error = TXT_FILE_OPEN_FAILED;
+                }
+            }
+        }
+
+    }
+
+} else {
+    $error = TXT_UNKNOWN_REQUEST;
+}
+echo "{";
+echo "error:'".$error."',\n";
+echo "path:'".$path."'";
+echo "}";
 
-	}else 
-	{
-		$error = TXT_UNKNOWN_REQUEST;
-	}
-		echo "{";
-		echo "error:'" . $error . "',\n";
-		echo  "path:'" . $path . "'";
-		echo "}";
-	
 ?>

+ 144 - 148
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_text_editor.php

@@ -1,166 +1,162 @@
 <?php
-		/**
-	 * Ajax image editor platform
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 22/May/2007
-	 *
-	 */
-	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
-	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE)
-	{
-		die(SYS_DISABLED);
-	}	
-		//$session->gc(); //disabled for Chamilo
-		$_GET['path'] = empty($_GET['path'])?CONFIG_SYS_ROOT_PATH . "ajax_image_editor_demo.jpg":$_GET['path'];
-		if(!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path']) && isUnderRoot($_GET['path']))
-		{
-				$path = $_GET['path'];
-		}else 
-		{
-			die(TXT_FILE_NOT_FOUND);
-		}
-		if(file_exists(DIR_AJAX_EDIT_AREA . "reg_syntax" . DIRECTORY_SEPARATOR . getFileExt($path) . ".js"))
-		{
-			$syntax = getFileExt($path);			
-		}else 
-		{
-			switch (getFileExt($path))
-			{
-				case 'htm':
-					$syntax = 'html';
-					break;
-				default:
-					$syntax = 'basic';
-			}
-		}
-		if(array_search(getFileExt($path), getValidTextEditorExts())=== false)
-		{
-			die(TXT_DISALLOWED_EXT);	
-		}
-	?>
+/* For licensing terms, see /license.txt */
+/**
+ * Ajax image editor platform
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/May/2007
+ *
+ */
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
+
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_EDITABLE) {
+    die(SYS_DISABLED);
+}
+
+//$session->gc(); //disabled for Chamilo
+$_GET['path'] = empty($_GET['path']) ? CONFIG_SYS_ROOT_PATH."ajax_image_editor_demo.jpg" : $_GET['path'];
+if (!empty($_GET['path']) && file_exists($_GET['path']) && is_file($_GET['path']) && isUnderRoot($_GET['path'])) {
+    $path = $_GET['path'];
+} else {
+    die(TXT_FILE_NOT_FOUND);
+}
+if (file_exists(DIR_AJAX_EDIT_AREA."reg_syntax".DIRECTORY_SEPARATOR.getFileExt($path).".js")) {
+    $syntax = getFileExt($path);
+} else {
+    switch (getFileExt($path)) {
+        case 'htm':
+            $syntax = 'html';
+            break;
+        default:
+            $syntax = 'basic';
+    }
+}
+if (array_search(getFileExt($path), getValidTextEditorExts()) === false) {
+    die(TXT_DISALLOWED_EXT);
+}
+?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="author" content="Logan Cai" />
-<meta name="website" content="http://www.phpletter.com" />
-<script type="text/javascript" src="jscripts/ajaxtexteditor_c.js"></script>
-<!--<script type="text/javascript" src="jscripts/jquery.js"></script>
-<script type="text/javascript" src="jscripts/form.js"></script>
-<script type="text/javascript" src="jscripts/select.js"></script>
-<script type="text/javascript" src="jscripts/jqModal.js"></script>
-<script type="text/javascript" src="jscripts/ajaxtexteditor.js"></script>
--->
-<script type="text/javascript" src="jscripts/edit_area/edit_area_full.js"></script>
-<script type="text/javascript">
-				var warningExtNotSelected = '<?php echo TXT_EXT_NOT_SELECTED; ?>';
-				var urlGetFolderList = '<?php echo appendQueryString(CONFIG_URL_GET_FOLDER_LIST, makeQueryString(array('path'))); ?>';
-				var warningInvalidName = '<?php echo TXT_SAVE_AS_ERR_NAME_INVALID; ?>';
-				var waringFolderNotSelected = '<?php echo TXT_DEST_FOLDER_NOT_SELECTED; ?>';
-				var currentFolder = '<?php echo dirname($path); ?>';
-				var currentName = '<?php echo basename($path); ?>';
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+    <meta name="author" content="Logan Cai"/>
+    <meta name="website" content="http://www.phpletter.com"/>
+    <script type="text/javascript" src="jscripts/ajaxtexteditor_c.js"></script>
+    <!--<script type="text/javascript" src="jscripts/jquery.js"></script>
+    <script type="text/javascript" src="jscripts/form.js"></script>
+    <script type="text/javascript" src="jscripts/select.js"></script>
+    <script type="text/javascript" src="jscripts/jqModal.js"></script>
+    <script type="text/javascript" src="jscripts/ajaxtexteditor.js"></script>
+    -->
+    <script type="text/javascript" src="jscripts/edit_area/edit_area_full.js"></script>
+    <script type="text/javascript">
+        var warningExtNotSelected = '<?php echo TXT_EXT_NOT_SELECTED; ?>';
+        var urlGetFolderList = '<?php echo appendQueryString(CONFIG_URL_GET_FOLDER_LIST, makeQueryString(array('path'))); ?>';
+        var warningInvalidName = '<?php echo TXT_SAVE_AS_ERR_NAME_INVALID; ?>';
+        var waringFolderNotSelected = '<?php echo TXT_DEST_FOLDER_NOT_SELECTED; ?>';
+        var currentFolder = '<?php echo dirname($path); ?>';
+        var currentName = '<?php echo basename($path); ?>';
 
-		jQuery(document).ready(
-		function()
-		{
-				editAreaLoader.init({				
-				id: "content"	// id of the textarea to transform		
-				,start_highlight: false	// if start with highlight
-				,allow_resize: "both"
-				,gecko_spellcheck:true
-				,allow_toggle: true
-				,toolbar:"search, go_to_line, fullscreen, |, undo, redo, |, select_font,|, highlight, reset_highlight, |, save, save_as"
-				,save_callback:"save"
-				,save_as_callback:"save_as"
-				,language: "<?php echo (file_exists(DIR_AJAX_EDIT_AREA . 'langs' . DIRECTORY_SEPARATOR .CONFIG_LANG_INDEX . ".js")?CONFIG_LANG_INDEX:'en'); ?>"
-				,syntax: "<?php echo $syntax; ?>"	
-			});				
-				jQuery('#windowSaveAs').jqm();		
-				jQuery('#windowProcessing').jqm({modal:true});				
-		}
-	);		
+        jQuery(document).ready(
+            function () {
+                editAreaLoader.init({
+                    id: "content"	// id of the textarea to transform
+                    , start_highlight: false	// if start with highlight
+                    , allow_resize: "both", gecko_spellcheck: true, allow_toggle: true, toolbar: "search, go_to_line, fullscreen, |, undo, redo, |, select_font,|, highlight, reset_highlight, |, save, save_as", save_callback: "save", save_as_callback: "save_as", language: "<?php echo (file_exists(DIR_AJAX_EDIT_AREA . 'langs' . DIRECTORY_SEPARATOR .CONFIG_LANG_INDEX . ".js")?CONFIG_LANG_INDEX:'en'); ?>", syntax: "<?php echo $syntax; ?>"
+                });
+                jQuery('#windowSaveAs').jqm();
+                jQuery('#windowProcessing').jqm({modal: true});
+            }
+        );
 
-		
 
-			
-</script>
+    </script>
 
-<link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/ajaxtexteditor.css" type="text/css" rel="stylesheet" />
-<link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/jqModal.css" type="text/css" rel="stylesheet" />
-<title>Ajax Text Editor</title>
+    <link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/ajaxtexteditor.css" type="text/css" rel="stylesheet"/>
+    <link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/jqModal.css" type="text/css" rel="stylesheet"/>
+    <title>Ajax Text Editor</title>
 </head>
 <body>
 
 <div id="pageBody">
-	<textarea name="content" id="content" style="height:500px; width: 97%;"><?php echo getFileContent($path); ?></textarea>
+    <textarea name="content" id="content" style="height:500px; width: 97%;"><?php echo getFileContent(
+            $path
+        ); ?></textarea>
 </div>
 <div id="windowProcessing" class="jqmWindow" style="display:none">
-	<form name="frmProcessing" id="frmProcessing" method="post" action="<?php echo appendQueryString(CONFIG_URL_SAVE_TEXT, makeQueryString(array('path')));?>">
-		<input type="hidden" name="folder" id="folder" value="<?php echo dirname($path); ?>" />
-		<input type="hidden" name="name" id="name" value="<?php echo basename($path); ?>" />	
-		<input type="hidden" name="save_as_request" id="save_as_request" value="0" />
-		<div style="display:none"><textarea name="text" id="text"></textarea></div> 
-	</form> 
-	<a href="#" class="jqmClose" id="windowSaveClose"><?php echo IMG_BTN_CANCEL; ?></a>
-	<p><img src="theme/<?php echo CONFIG_THEME_NAME; ?>/images/loading.gif" /></p>
+    <form name="frmProcessing" id="frmProcessing" method="post"
+          action="<?php echo appendQueryString(CONFIG_URL_SAVE_TEXT, makeQueryString(array('path'))); ?>">
+        <input type="hidden" name="folder" id="folder" value="<?php echo dirname($path); ?>"/>
+        <input type="hidden" name="name" id="name" value="<?php echo basename($path); ?>"/>
+        <input type="hidden" name="save_as_request" id="save_as_request" value="0"/>
+
+        <div style="display:none"><textarea name="text" id="text"></textarea></div>
+    </form>
+    <a href="#" class="jqmClose" id="windowSaveClose"><?php echo IMG_BTN_CANCEL; ?></a>
+
+    <p><img src="theme/<?php echo CONFIG_THEME_NAME; ?>/images/loading.gif"/></p>
 </div>
 <div id="windowSaveAs" class="jqmWindow" style="display:none">
-    	<a href="#" class="jqmClose" id="windowSaveClose"><?php echo IMG_BTN_CANCEL; ?></a>
-      <form id="formSaveAs" name="formSaveAs" action="" method="post">
-    	<table class="tableForm" cellpadding="0" cellspacing="0">
-      	<thead>
-        	<tr>
-          	<th colspan="2"><?php echo IMG_LBL_SAVE_AS; ?></th>
-          </tr>
-        </thead>
-        <tbody>
-        	<tr>
-          	<th>
-            	<label><?php echo IMG_LBL_NEW_NAME; ?></label>
-            </th>
-            <td>
-            	<input type="text" id="new_name" class="input" name="new_name" value="" />
-              &nbsp;.&nbsp;<select id="ext" name="ext">
-              <?php
-								foreach(getValidTextEditorExts() as $v)
-								{
-									?>
-									<option value="<?php echo $v; ?>" <?php echo (strtolower($v) == strtolower(getFileExt($path))?'selected':''); ?>><?php echo $v; ?></option>
-									<?php
-								}
-							?>
-              </select>
-            </td>
-          </tr>
-          <tr>
-          	<th>
-            	<label><?php echo IMG_LBL_SAVE_TO; ?></label>
-            </th>
-            <td>
-            	<select class="input" name="save_to" id="save_to">
-              	
-              </select>
-            </td>
-          </tr>
-          <tr>
-          	<th>&nbsp;
-            </th>
-            <td>
-            <span class="comments">*</span>
-            <?php echo IMG_NEW_NAME_COMMENTS; ?>
-            </td>
-          </tr>
-        </tbody>
-        <tfoot>
-        	<tr>
-        	<th>&nbsp;</th>
-          <td><input type="button" class="button" value="<?php echo IMG_BTN_SAVE_AS; ?>" onclick="return do_save_as();" /></td>
-          </tr>
-        </tfoot>
-      </table>
-      </form>
-    </div>
+    <a href="#" class="jqmClose" id="windowSaveClose"><?php echo IMG_BTN_CANCEL; ?></a>
+
+    <form id="formSaveAs" name="formSaveAs" action="" method="post">
+        <table class="tableForm" cellpadding="0" cellspacing="0">
+            <thead>
+            <tr>
+                <th colspan="2"><?php echo IMG_LBL_SAVE_AS; ?></th>
+            </tr>
+            </thead>
+            <tbody>
+            <tr>
+                <th>
+                    <label><?php echo IMG_LBL_NEW_NAME; ?></label>
+                </th>
+                <td>
+                    <input type="text" id="new_name" class="input" name="new_name" value=""/>
+                    &nbsp;.&nbsp;<select id="ext" name="ext">
+                        <?php
+                        foreach (getValidTextEditorExts() as $v) {
+                            ?>
+                            <option value="<?php echo $v; ?>" <?php echo(strtolower($v) == strtolower(
+                                getFileExt($path)
+                            ) ? 'selected' : ''); ?>><?php echo $v; ?></option>
+                        <?php
+                        }
+                        ?>
+                    </select>
+                </td>
+            </tr>
+            <tr>
+                <th>
+                    <label><?php echo IMG_LBL_SAVE_TO; ?></label>
+                </th>
+                <td>
+                    <select class="input" name="save_to" id="save_to">
+
+                    </select>
+                </td>
+            </tr>
+            <tr>
+                <th>&nbsp;
+                </th>
+                <td>
+                    <span class="comments">*</span>
+                    <?php echo IMG_NEW_NAME_COMMENTS; ?>
+                </td>
+            </tr>
+            </tbody>
+            <tfoot>
+            <tr>
+                <th>&nbsp;</th>
+                <td><input type="button" class="button" value="<?php echo IMG_BTN_SAVE_AS; ?>"
+                           onclick="return do_save_as();"/></td>
+            </tr>
+            </tfoot>
+        </table>
+    </form>
+</div>
 
-</body></html>
+</body>
+</html>
 

+ 677 - 676
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajaxfilemanager.php

@@ -1,422 +1,416 @@
 <?php
-/**
-* file manager platform
-* @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-* @link www.phpletter.com
-* @since 22/May/2007
-*
-* Modify system config setting for Chamilo
-* @author Juan Carlos Raña Trabado
-* @since 31/December/2008
-*/
-
-include '../../../../../../inc/global.inc.php'; // Integrating with Chamilo
-api_block_anonymous_users();// from Chamilo
+/* For licensing terms, see /license.txt */
 
-require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php";
+/**
+ * file manager platform
+ * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
+ * @link www.phpletter.com
+ * @since 22/May/2007
+ *
+ * Modify system config setting for Chamilo
+ * @author Juan Carlos Raña Trabado
+ * @since 31/December/2008
+ */
+
+require_once '../../../../../../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
 
 require_once CLASS_SESSION_ACTION;
 $sessionAction = new SessionAction();
 
 if (CONFIG_LOAD_DOC_LATTER) {
-	$fileList = array();
-	$folderInfo = array('path'=>getCurrentFolderPath());
+    $fileList   = array();
+    $folderInfo = array('path' => getCurrentFolderPath());
 } else {
-	require_once(CLASS_MANAGER);
-	$manager = new manager();
-	$manager->setSessionAction($sessionAction);
-	$fileList = $manager->getFileList();
-	$folderInfo = $manager->getFolderInfo();
+    require_once(CLASS_MANAGER);
+    $manager = new manager();
+    $manager->setSessionAction($sessionAction);
+    $fileList   = $manager->getFileList();
+    $folderInfo = $manager->getFolderInfo();
 }
 
-if(CONFIG_SYS_THUMBNAIL_VIEW_ENABLE) {
-	$views = array(
-		'detail'=>LBL_BTN_VIEW_DETAILS,
-		'thumbnail'=>LBL_BTN_VIEW_THUMBNAIL,
-	);
+if (CONFIG_SYS_THUMBNAIL_VIEW_ENABLE) {
+    $views = array(
+        'detail'    => LBL_BTN_VIEW_DETAILS,
+        'thumbnail' => LBL_BTN_VIEW_THUMBNAIL,
+    );
 } else {
-	$views = array(
-	  'detail'=>LBL_BTN_VIEW_DETAILS,
-	);
+    $views = array(
+        'detail' => LBL_BTN_VIEW_DETAILS,
+    );
 }
 
-if(!empty($_GET['view'])) {
-	switch($_GET['view']) {
-		case 'detail':
-		case 'thumbnail':
-			$view = Security::remove_XSS($_GET['view']);
-			break;
-		default:
-			$view = CONFIG_DEFAULT_VIEW;
-	}
+if (!empty($_GET['view'])) {
+    switch ($_GET['view']) {
+        case 'detail':
+        case 'thumbnail':
+            $view = Security::remove_XSS($_GET['view']);
+            break;
+        default:
+            $view = CONFIG_DEFAULT_VIEW;
+    }
 } else {
-	$view = CONFIG_DEFAULT_VIEW;
+    $view = CONFIG_DEFAULT_VIEW;
 }
 
 ?>
-<!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" debug="true" xml:lang="<?php echo CONFIG_LANG_DEFAULT; ?>" lang="<?php echo CONFIG_LANG_DEFAULT; ?>"><!--  hack fon lang default Chamilo -->
+<!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" debug="true" xml:lang="<?php echo CONFIG_LANG_DEFAULT; ?>" lang="<?php echo CONFIG_LANG_DEFAULT; ?>">
+<!--  hack fon lang default Chamilo -->
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<title>Ajax File Manager</title>
-
-<script type="text/javascript" src="jscripts/jquery.js"></script>
-<script type="text/javascript" src="jscripts/form.js"></script>
-<script type="text/javascript" src="jscripts/select.js"></script>
-<script type="text/javascript" src="jscripts/thickbox.js"></script>
-<script type="text/javascript" src="jscripts/calendar.js"></script>
-<script type="text/javascript" src="jscripts/contextmenu.js"></script>
-<script type="text/javascript" src="jscripts/media.js"></script>
-<script type="text/javascript" src="jscripts/ajaxfileupload.js"></script>
-<script type="text/javascript" src="jscripts/ajaxfilemanager.js"></script>
-<script type="text/javascript">
-
-	var mode_editor = '<?php echo Security::remove_XSS($_GET['editor']);?>';<!-- Chamilo hack for general my files users  -->
-	if (!mode_editor){
-		// Added by Ivan Tcholakov, 22-JUL-2009.
-		// For integration with the editor's dialig system.
-		var oEditor = null ;
-		if ( !window.opener && window.parent ) {
-			// The file manager is inside a dialog.
-			oEditor = window.parent.InnerDialogLoaded() ;
-		}
-		//end hack
-	}
-	var globalSettings = {'upload_init':false};
-	var queryString = '<?php echo makeQueryString(array('path')); ?>';
-	var paths = {'root':'<?php echo addTrailingSlash(backslashToSlash(CONFIG_SYS_ROOT_PATH)); ?>', 'root_title':'<?php echo LBL_FOLDER_ROOT; ?>'};
-
-	<!-- Chamilo hack for breadcrumb into shared folders -->
-	var shared_folder = '<?php echo get_lang('UserFolders');?>';
-
-	<?php
-    $course_session = array();
-    if (isset($currentPath)) {
-        $course_session = explode('_', basename($currentPath));
-        $course_session = strtolower($course_session[sizeof($course_session) - 1]);
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+    <title>Ajax File Manager</title>
+
+    <script type="text/javascript" src="jscripts/jquery.js"></script>
+    <script type="text/javascript" src="jscripts/form.js"></script>
+    <script type="text/javascript" src="jscripts/select.js"></script>
+    <script type="text/javascript" src="jscripts/thickbox.js"></script>
+    <script type="text/javascript" src="jscripts/calendar.js"></script>
+    <script type="text/javascript" src="jscripts/contextmenu.js"></script>
+    <script type="text/javascript" src="jscripts/media.js"></script>
+    <script type="text/javascript" src="jscripts/ajaxfileupload.js"></script>
+    <script type="text/javascript" src="jscripts/ajaxfilemanager.js"></script>
+    <script type="text/javascript">
+
+        var mode_editor = '<?php echo Security::remove_XSS($_GET['editor']);?>';
+        <!-- Chamilo hack for general my files users  -->
+        if (!mode_editor) {
+            // Added by Ivan Tcholakov, 22-JUL-2009.
+            // For integration with the editor's dialig system.
+            var oEditor = null;
+            if (!window.opener && window.parent) {
+                // The file manager is inside a dialog.
+                oEditor = window.parent.InnerDialogLoaded();
+            }
+            //end hack
+        }
+        var globalSettings = {'upload_init': false};
+        var queryString = '<?php echo makeQueryString(array('path')); ?>';
+        var paths = {'root': '<?php echo addTrailingSlash(backslashToSlash(CONFIG_SYS_ROOT_PATH)); ?>', 'root_title': '<?php echo LBL_FOLDER_ROOT; ?>'};
+
+        <!-- Chamilo hack for breadcrumb into shared folders -->
+        var shared_folder = '<?php echo get_lang('UserFolders'); ?>';
+
+        <?php
+        $course_session = array();
+        if (isset($currentPath)) {
+            $course_session = explode('_', basename($currentPath));
+            $course_session = strtolower($course_session[sizeof($course_session) - 1]);
+        }
+        ?>
+        var shared_folder_session = '<?php echo get_lang('UserFolders').'*';?>';
+        var shared_user_folder = '<?php echo get_lang('User');?>';
+        <!--end hack -->
+
+        var parentFolder = {};
+        var urls = {
+            'upload': '<?php echo CONFIG_URL_UPLOAD; ?>',
+            'preview': '<?php echo CONFIG_URL_PREVIEW; ?>',
+            'cut': '<?php echo CONFIG_URL_CUT; ?>',
+            'copy': '<?php echo CONFIG_URL_COPY; ?>',
+            'paste': '<?php echo CONFIG_URL_FILE_PASTE; ?>',
+            'delete': '<?php echo CONFIG_URL_DELETE; ?>',
+            'rename': '<?php echo CONFIG_URL_SAVE_NAME; ?>',
+            'thumbnail': '<?php echo CONFIG_URL_IMG_THUMBNAIL;  ?>',
+            'create_folder': '<?php echo CONFIG_URL_CREATE_FOLDER; ?>',
+            'text_editor': '<?php echo  CONFIG_URL_TEXT_EDITOR; ?>',
+            'image_editor': '<?php echo  CONFIG_URL_IMAGE_EDITOR; ?>',
+            'download': '<?php echo CONFIG_URL_DOWNLOAD; ?>',
+            'present': '<?php echo getCurrentUrl(); ?>',
+            'home': '<?php echo CONFIG_URL_HOME; ?>',
+            'view': '<?php echo CONFIG_URL_LIST_LISTING; ?>'
+        };
+        var permits = {    'del':<?php echo (CONFIG_OPTIONS_DELETE?1:0); ?>,
+            'cut':<?php echo (CONFIG_OPTIONS_CUT?'1':'0'); ?>,
+            'copy':<?php echo (CONFIG_OPTIONS_COPY?1:0); ?>,
+            'newfolder':<?php echo (CONFIG_OPTIONS_NEWFOLDER?1:0); ?>,
+            'rename':<?php echo (CONFIG_OPTIONS_RENAME?1:0); ?>,
+            'upload':<?php echo (CONFIG_OPTIONS_UPLOAD?1:0); ?>,
+            'edit':<?php echo (CONFIG_OPTIONS_EDITABLE?1:0); ?>,
+            'view_only':<?php echo (CONFIG_SYS_VIEW_ONLY?1:0); ?>};
+        var currentFolder = {};
+        var warningDelete = '<?php echo WARNING_DELETE; ?>';
+        var newFile = {'num': 1, 'label': '<?php echo FILE_LABEL_SELECT; ?>', 'upload': '<?php echo FILE_LBL_UPLOAD; ?>'};
+        var counts = {'new_file': 1};
+        var thickbox = {
+            'width': '<?php echo CONFIG_THICKBOX_MAX_WIDTH; ?>',
+            'height': '<?php echo CONFIG_THICKBOX_MAX_HEIGHT; ?>',
+            'next': '<img src="theme/default/images/next.png" title="<?php echo THICKBOX_NEXT; ?>" style="float:right;">',
+            'previous': '<img src="theme/default/images/prev.png" title="<?php echo THICKBOX_PREVIOUS; ?>" style="float:left">',
+            'close': '<img src="theme/default/images/flagno.png"title="<?php echo THICKBOX_CLOSE; ?>"><?php echo THICKBOX_CLOSE; ?>'
+        };
+
+        var tb_pathToImage = "theme/<?php echo CONFIG_THEME_NAME; ?>/images/loadingAnimation.gif";
+        var msgInvalidFolderName = '<?php echo ERR_FOLDER_FORMAT; ?>';
+        var msgInvalidFileName = '<?php echo ERR_FILE_NAME_FORMAT; ?>';
+        var msgInvalidExt = '<?php echo ERR_FILE_TYPE_NOT_ALLOWED; ?>';
+        var msgNotPreview = '<?php echo PREVIEW_NOT_PREVIEW; ?>';
+
+        var warningCutPaste = '<?php echo WARNING_CUT_PASTE; ?>';
+        var warningCopyPaste = '<?php echo WARNING_COPY_PASTE; ?>';
+        var warningDel = '<?php echo WARNING_DELETE; ?>';
+        var warningNotDocSelected = '<?php echo ERR_NOT_DOC_SELECTED; ?>';
+        //var noFileSelected = '<?php //echo ERR_NOT_FILE_SELECTED; ?>';// Chamilo
+        var noFileSelected = '<?php echo TXT_EXT_NOT_SELECTED; ?>';// Chamilo
+        var unselectAllText = '<?php echo TIP_UNSELECT_ALL; ?>';
+        var selectAllText = '<?php echo TIP_SELECT_ALL; ?>';
+        var action = '<?php echo $sessionAction->getAction(); ?>';
+        var numFiles = <?php echo $sessionAction->count(); ?>;
+        var warningCloseWindow = '<?php echo WARING_WINDOW_CLOSE; ?>';
+        var numRows = 0;
+
+        var wordCloseWindow = '<?php echo LBL_ACTION_CLOSE; ?>';
+        var wordPreviewClick = '<?php echo LBL_CLICK_PREVIEW; ?>';
+
+        var searchRequired = false;
+        var supporedPreviewExts = '<?php echo CONFIG_VIEWABLE_VALID_EXTS; ?>';
+        var supportedUploadExts = '<?php echo CONFIG_UPLOAD_VALID_EXTS; ?>'
+        var elementId = <?php  echo (!empty($_GET['elementId'])?"'" . Security::remove_XSS($_GET['elementId']) . "'":'null'); ?>;
+        var files = {};
+
+        $(document).ready(
+            function () {
+                jQuery(document).bind('keypress', function (event) {
+                    var code = event.charCode || event.keyCode;
+                    if (code && code == 13) {// if enter is pressed
+                        event.preventDefault(); //prevent browser from following the actual href
+                    }
+                    ;
+                });
+                if (typeof(cancelSelectFile) != 'undefined') {
+                    $('#linkClose').show();
+                }
+                $('input[@name=view]').each(
+                    function () {
+                        if (this.value == '<?php echo $view; ?>') {
+                            this.checked = true;
+                        } else {
+                            this.checked = false;
+                        }
+                    }
+                );
+
+                popUpCal.clearText = '<?php echo CALENDAR_CLEAR; ?>';
+                popUpCal.closeText = '<?php echo CALENDAR_CLOSE; ?>';
+                popUpCal.prevText = '<?php echo CALENDAR_PREVIOUS; ?>';
+                popUpCal.nextText = '<?php echo CALENDAR_NEXT; ?>';
+                popUpCal.currentText = '<?php echo CALENDAR_CURRENT; ?>';
+                popUpCal.buttonImageOnly = true;
+                popUpCal.dayNames = new Array('<?php echo CALENDAR_SUN; ?>', '<?php echo CALENDAR_MON; ?>', '<?php echo CALENDAR_TUE; ?>', '<?php echo CALENDAR_WED; ?>', '<?php echo CALENDAR_THU; ?>', '<?php echo CALENDAR_FRI; ?>', '<?php echo CALENDAR_SAT; ?>');
+                popUpCal.monthNames = new Array('<?php echo CALENDAR_JAN; ?>', '<?php echo CALENDAR_FEB; ?>', '<?php echo CALENDAR_MAR; ?>', '<?php echo CALENDAR_APR; ?>', '<?php echo CALENDAR_MAY; ?>', '<?php echo CALENDAR_JUN; ?>', '<?php echo CALENDAR_JUL; ?>', '<?php echo CALENDAR_AUG; ?>', '<?php echo CALENDAR_SEP; ?>', '<?php echo CALENDAR_OCT; ?>', '<?php echo CALENDAR_NOV; ?>', '<?php echo CALENDAR_DEC; ?>');
+                popUpCal.dateFormat = 'YMD-';
+                $('.inputMtime').calendar({autoPopUp: 'both', buttonImage: 'theme/<?php echo CONFIG_THEME_NAME; ?>/images/date_picker.png'});
+                initAfterListingLoaded();
+                //addMoreFile();
+            });
+    </script>
+    <?php
+    if (file_exists(
+            dirname(__FILE__)
+        ).DIRECTORY_SEPARATOR.'jscripts'.DIRECTORY_SEPARATOR.'for_'.CONFIG_EDITOR_NAME.".js"
+    ) {
+        ?>
+        <script type="text/javascript" src="jscripts/<?php echo 'for_'.CONFIG_EDITOR_NAME.'.js'; ?>"></script>
+    <?php
     }
-
-	?>
-	<!--var shared_folder_session = '<?php //echo get_lang('UserFolders').' ('.api_get_session_name($course_session).')';?>'; --><!--// problem does not refresh, does not synchronize with javascript -->
-	var shared_folder_session = '<?php echo get_lang('UserFolders').'*';?>';
-	<?php
-
-	//$userinfo=Database::get_user_info_from_id(substr(basename($folderInfo['path']), 8));	// problem with $folderInfo['path'] does not refresh, sincronisation with javascript?>
-	<!--var shared_user_folder = '<?php //echo api_get_person_name($userinfo['firstname'], $userinfo['lastname']);?>'; --><!--// problem does not refresh, does not synchronize with javascript -->
-	var shared_user_folder = '<?php echo get_lang('User');?>';
-
-	<!--end hack -->
-
-	var parentFolder = {};
-	var urls = {
-        'upload':'<?php echo CONFIG_URL_UPLOAD; ?>',
-        'preview':'<?php echo CONFIG_URL_PREVIEW; ?>',
-        'cut':'<?php echo CONFIG_URL_CUT; ?>',
-        'copy':'<?php echo CONFIG_URL_COPY; ?>',
-        'paste':'<?php echo CONFIG_URL_FILE_PASTE; ?>',
-        'delete':'<?php echo CONFIG_URL_DELETE; ?>',
-        'rename':'<?php echo CONFIG_URL_SAVE_NAME; ?>',
-        'thumbnail':'<?php echo CONFIG_URL_IMG_THUMBNAIL;  ?>',
-        'create_folder':'<?php echo CONFIG_URL_CREATE_FOLDER; ?>',
-        'text_editor':'<?php echo  CONFIG_URL_TEXT_EDITOR; ?>',
-        'image_editor':'<?php echo  CONFIG_URL_IMAGE_EDITOR; ?>',
-        'download':'<?php echo CONFIG_URL_DOWNLOAD; ?>',
-        'present':'<?php echo getCurrentUrl(); ?>',
-        'home':'<?php echo CONFIG_URL_HOME; ?>',
-        'view':'<?php echo CONFIG_URL_LIST_LISTING; ?>'
-    };
-	var permits = {	'del':<?php echo (CONFIG_OPTIONS_DELETE?1:0); ?>,
-					'cut':<?php echo (CONFIG_OPTIONS_CUT?'1':'0'); ?>,
-					'copy':<?php echo (CONFIG_OPTIONS_COPY?1:0); ?>,
-					'newfolder':<?php echo (CONFIG_OPTIONS_NEWFOLDER?1:0); ?>,
-					'rename':<?php echo (CONFIG_OPTIONS_RENAME?1:0); ?>,
-					'upload':<?php echo (CONFIG_OPTIONS_UPLOAD?1:0); ?>,
-					'edit':<?php echo (CONFIG_OPTIONS_EDITABLE?1:0); ?>,
-					'view_only':<?php echo (CONFIG_SYS_VIEW_ONLY?1:0); ?>};
-	var currentFolder = {};
-	var warningDelete = '<?php echo WARNING_DELETE; ?>';
-	var newFile = {'num':1, 'label':'<?php echo FILE_LABEL_SELECT; ?>', 'upload':'<?php echo FILE_LBL_UPLOAD; ?>'};
-	var counts = {'new_file':1};
-	var thickbox = {
-        'width':'<?php echo CONFIG_THICKBOX_MAX_WIDTH; ?>',
-        'height':'<?php echo CONFIG_THICKBOX_MAX_HEIGHT; ?>',
-        'next':'<img src="theme/default/images/next.png" title="<?php echo THICKBOX_NEXT; ?>" style="float:right;">',
-        'previous':'<img src="theme/default/images/prev.png" title="<?php echo THICKBOX_PREVIOUS; ?>" style="float:left">',
-        'close':'<img src="theme/default/images/flagno.png"title="<?php echo THICKBOX_CLOSE; ?>"><?php echo THICKBOX_CLOSE; ?>'
-	};
-
-	var tb_pathToImage = "theme/<?php echo CONFIG_THEME_NAME; ?>/images/loadingAnimation.gif";
-	var msgInvalidFolderName = '<?php echo ERR_FOLDER_FORMAT; ?>';
-	var msgInvalidFileName = '<?php echo ERR_FILE_NAME_FORMAT; ?>';
-	var msgInvalidExt = '<?php echo ERR_FILE_TYPE_NOT_ALLOWED; ?>';
-	var msgNotPreview = '<?php echo PREVIEW_NOT_PREVIEW; ?>';
-
-	var warningCutPaste = '<?php echo WARNING_CUT_PASTE; ?>';
-	var warningCopyPaste = '<?php echo WARNING_COPY_PASTE; ?>';
-	var warningDel = '<?php echo WARNING_DELETE; ?>';
-	var warningNotDocSelected = '<?php echo ERR_NOT_DOC_SELECTED; ?>';
-	//var noFileSelected = '<?php //echo ERR_NOT_FILE_SELECTED; ?>';// Chamilo
-	var noFileSelected = '<?php echo TXT_EXT_NOT_SELECTED; ?>';// Chamilo
-    var unselectAllText = '<?php echo TIP_UNSELECT_ALL; ?>';
-    var selectAllText = '<?php echo TIP_SELECT_ALL; ?>';
-	var action = '<?php echo $sessionAction->getAction(); ?>';
-	var numFiles = <?php echo $sessionAction->count(); ?>;
-	var warningCloseWindow = '<?php echo WARING_WINDOW_CLOSE; ?>';
-	var numRows = 0;
-
-	var wordCloseWindow = '<?php echo LBL_ACTION_CLOSE; ?>';
-	var wordPreviewClick = '<?php echo LBL_CLICK_PREVIEW; ?>';
-
-	var searchRequired = false;
-	var supporedPreviewExts = '<?php echo CONFIG_VIEWABLE_VALID_EXTS; ?>';
-	var supportedUploadExts = '<?php echo CONFIG_UPLOAD_VALID_EXTS; ?>'
-	var elementId = <?php  echo (!empty($_GET['elementId'])?"'" . Security::remove_XSS($_GET['elementId']) . "'":'null'); ?>;
-	var files = {};
-
-    $(document).ready(
-	function() {
-		jQuery(document).bind('keypress', function(event) {
-			var code=event.charCode || event.keyCode;
-			if(code && code == 13) {// if enter is pressed
-	  			event.preventDefault(); //prevent browser from following the actual href
-			};
-		});
-		if(typeof(cancelSelectFile) != 'undefined') {
-			$('#linkClose').show();
-		}
-		$('input[@name=view]').each(
-			function() {
-				if(this.value == '<?php echo $view; ?>') {
-					this.checked = true;
-				} else {
-					this.checked = false;
-				}
-			}
-		);
-
-		popUpCal.clearText = '<?php echo CALENDAR_CLEAR; ?>';
-		popUpCal.closeText = '<?php echo CALENDAR_CLOSE; ?>';
-		popUpCal.prevText = '<?php echo CALENDAR_PREVIOUS; ?>';
-		popUpCal.nextText = '<?php echo CALENDAR_NEXT; ?>';
-		popUpCal.currentText = '<?php echo CALENDAR_CURRENT; ?>';
-		popUpCal.buttonImageOnly = true;
-		popUpCal.dayNames = new Array('<?php echo CALENDAR_SUN; ?>','<?php echo CALENDAR_MON; ?>','<?php echo CALENDAR_TUE; ?>','<?php echo CALENDAR_WED; ?>','<?php echo CALENDAR_THU; ?>','<?php echo CALENDAR_FRI; ?>','<?php echo CALENDAR_SAT; ?>');
-		popUpCal.monthNames = new Array('<?php echo CALENDAR_JAN; ?>','<?php echo CALENDAR_FEB; ?>','<?php echo CALENDAR_MAR; ?>','<?php echo CALENDAR_APR; ?>','<?php echo CALENDAR_MAY; ?>','<?php echo CALENDAR_JUN; ?>','<?php echo CALENDAR_JUL; ?>','<?php echo CALENDAR_AUG; ?>','<?php echo CALENDAR_SEP; ?>','<?php echo CALENDAR_OCT; ?>','<?php echo CALENDAR_NOV; ?>','<?php echo CALENDAR_DEC; ?>');
-		popUpCal.dateFormat = 'YMD-';
-		$('.inputMtime').calendar({autoPopUp:'both', buttonImage:'theme/<?php echo CONFIG_THEME_NAME; ?>/images/date_picker.png'});
-		initAfterListingLoaded();
-		//addMoreFile();
-	} );
-</script>
-<?php
-	if(file_exists(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'jscripts' . DIRECTORY_SEPARATOR . 'for_' . CONFIG_EDITOR_NAME . ".js") {
-	?>
-		<script type="text/javascript" src="jscripts/<?php echo 'for_' . CONFIG_EDITOR_NAME . '.js'; ?>"></script>
-	<?php
-	}
-?>
-<link rel="stylesheet" type="text/css" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/<?php echo CONFIG_EDITOR_NAME; ?>.css" />
-<link rel="stylesheet" type="text/css" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/jquery-calendar.css" />
-<link rel="stylesheet" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/thickbox.css" type="text/css" media="screen" />
-<!--[if IE 6]>
-<link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/ie6.css" type="text/css" rel="Stylesheet" media="screen">
-<![endif]-->
+    ?>
+    <link rel="stylesheet" type="text/css" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/<?php echo CONFIG_EDITOR_NAME; ?>.css"/>
+    <link rel="stylesheet" type="text/css" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/jquery-calendar.css"/>
+    <link rel="stylesheet" href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/thickbox.css" type="text/css" media="screen"/>
+    <!--[if IE 6]>
+    <link href="theme/<?php echo CONFIG_THEME_NAME; ?>/css/ie6.css" type="text/css" rel="Stylesheet" media="screen">
+    <![endif]-->
 </head>
-<body dir="<?php echo CONFIG_LANG_TEXT_DIRECTION_DEFAULT; ?>"><!-- move style to css and hack for default lang Chamilo -->
-	<div id="wrapper">
-  	<div id="header">
-  		<dl id="currentFolderInfo">
-  			<dt><?php echo LBL_CURRENT_FOLDER_PATH; ?></dt>
-  			<dt id="currentFolderPath"><?php echo $folderInfo['path']; ?></dt><!-- hack for breadcrumb for Chamilo change <dd> by <dt> -->
-  		</dl>
-        <br />
-    	<div id="viewList">
-    			<label><?php echo LBL_BTN_VIEW_OPTIONS; ?></label>
-					<?php
-						foreach($views as $k=>$v) {
-							?>
-							<input type="radio" name="view"  class="radio" onclick="return changeView(this);" value="<?php echo $k; ?>" <?php echo ($k==$view?'checked':''); ?>> <?php echo $v; ?> &nbsp;&nbsp;
-							<?php
-						}
-					?></div>
-				<ul id="actionHeader">
-					<li><a href="#" id="actionRefresh" onclick="return windowRefresh();"><span><?php echo LBL_ACTION_REFRESH; ?></span></a></li>
-					<li><a href="#" id="actionSelectAll" class="check_all" onclick="return checkAll(this);"><span><?php echo LBL_ACTION_SELECT_ALL; ?></span></a></li>
-					<?php
-						if (CONFIG_OPTIONS_DELETE) {
-							?>
-							<li><a href="#" id="actionDelete" onclick="return deleteDocuments();"><span><?php echo LBL_ACTION_DELETE; ?></span></a></li>
-							<?php
-						}
-					?>
-					<?php
-						if(CONFIG_OPTIONS_CUT)
-						{
-							?>
-							<li><a href="#" id="actionCut" onclick="return cutDocuments('<?php echo ERR_NOT_DOC_SELECTED_FOR_CUT; ?>');"><span><?php echo LBL_ACTION_CUT; ?></span></a></li>
-							<?php
-						}
-					?>
-					<?php
-						if(CONFIG_OPTIONS_COPY)
-						{
-							?>
-							<li><a href="#" id="actionCopy" onclick="return copyDocuments('<?php echo ERR_NOT_DOC_SELECTED_FOR_COPY; ?>');"><span><?php echo LBL_ACTION_COPY; ?></span></a></li>
-							<?php
-						}
-					?>
-					<?php
-						if(CONFIG_OPTIONS_CUT || CONFIG_OPTIONS_COPY)
-						{
-							?>
-							<li><a href="#" id="actionPaste" onclick="return pasteDocuments('<?php echo ERR_NOT_DOC_SELECTED_FOR_PASTE; ?>');"><span><?php echo LBL_ACTION_PASTE; ?></span></a></li>
-							<?php
-						}
-					?>
-
-					<?php
-						if(CONFIG_OPTIONS_NEWFOLDER)
-						{
-							?>
-							<li><a  id="actionNewFolder" href="#" onclick="return newFolderWin(this);"><span><?php echo LBL_BTN_NEW_FOLDER; ?></span></a></li>
-							<?php
-						}
-					?>
-					<?php
-						if(CONFIG_OPTIONS_UPLOAD)
-						{
-							?>
-							<li><a  id="actionUpload" href="#" onclick="return uploadFileWin(this);"><span><?php echo LBL_BTN_UPLOAD; ?></span></a></li>
-							<?php
-						}
-					?>
-
-<!--					<li><a href="#" id="actionClose" onclick="closeWindow('<?php echo IMG_WARING_WIN_CLOSE; ?>');"><?php echo IMG_BTN_CLOSE; ?></a></li>-->
-					<!--<li><a href="#" class="thickbox" id="actionInfo" onclick="return infoWin(this);"><span>Info</span></a></li> -->
-					<!-- thest functions will be added in the near future
- 					<li ><a href="#" id="actionZip"><span>Zip</span></a><li>
-					<li ><a href="#" id="actionUnzip"><span>Unzip</span></a><li>-->
-				</ul>
-<form action="" method="post" name="formAction" id="formAction">
-	<input type="hidden" name="currentFolderPath" id="currentFolderPathVal" value="" />
-	<select name="selectedDoc[]" id="selectedDoc" style="display:none;" multiple="multiple"></select>
-	<input type="hidden" name="action_value" value="" id="action_value" />
-</form>
+<body dir="<?php echo CONFIG_LANG_TEXT_DIRECTION_DEFAULT; ?>">
+<!-- move style to css and hack for default lang Chamilo -->
+<div id="wrapper">
+<div id="header">
+    <dl id="currentFolderInfo">
+        <dt><?php echo LBL_CURRENT_FOLDER_PATH; ?></dt>
+        <dt id="currentFolderPath"><?php echo $folderInfo['path']; ?></dt>
+        <!-- hack for breadcrumb for Chamilo change <dd> by <dt> -->
+    </dl>
+    <br/>
+    <div id="viewList">
+        <label><?php echo LBL_BTN_VIEW_OPTIONS; ?></label>
+        <?php
+        foreach ($views as $k => $v) {
+            ?>
+            <input type="radio" name="view" class="radio" onclick="return changeView(this);"
+                   value="<?php echo $k; ?>" <?php echo($k == $view ? 'checked' : ''); ?>> <?php echo $v; ?> &nbsp;&nbsp;
+        <?php
+        }
+        ?>
+    </div>
+    <ul id="actionHeader">
+        <li><a href="#" id="actionRefresh"
+               onclick="return windowRefresh();"><span><?php echo LBL_ACTION_REFRESH; ?></span></a></li>
+        <li><a href="#" id="actionSelectAll" class="check_all"
+               onclick="return checkAll(this);"><span><?php echo LBL_ACTION_SELECT_ALL; ?></span></a></li>
+        <?php
+        if (CONFIG_OPTIONS_DELETE) {
+            ?>
+            <li><a href="#" id="actionDelete"
+                   onclick="return deleteDocuments();"><span><?php echo LBL_ACTION_DELETE; ?></span></a></li>
+        <?php
+        }
+        ?>
+        <?php
+        if (CONFIG_OPTIONS_CUT) {
+            ?>
+            <li><a href="#" id="actionCut"
+                   onclick="return cutDocuments('<?php echo ERR_NOT_DOC_SELECTED_FOR_CUT; ?>');"><span><?php echo LBL_ACTION_CUT; ?></span></a>
+            </li>
+        <?php
+        }
+        ?>
+        <?php
+        if (CONFIG_OPTIONS_COPY) {
+            ?>
+            <li><a href="#" id="actionCopy"
+                   onclick="return copyDocuments('<?php echo ERR_NOT_DOC_SELECTED_FOR_COPY; ?>');"><span><?php echo LBL_ACTION_COPY; ?></span></a>
+            </li>
+        <?php
+        }
+        ?>
+        <?php
+        if (CONFIG_OPTIONS_CUT || CONFIG_OPTIONS_COPY) {
+            ?>
+            <li><a href="#" id="actionPaste"
+                   onclick="return pasteDocuments('<?php echo ERR_NOT_DOC_SELECTED_FOR_PASTE; ?>');"><span><?php echo LBL_ACTION_PASTE; ?></span></a>
+            </li>
+        <?php
+        }
+        if (CONFIG_OPTIONS_NEWFOLDER) {
+            ?>
+            <li><a id="actionNewFolder" href="#"
+                   onclick="return newFolderWin(this);"><span><?php echo LBL_BTN_NEW_FOLDER; ?></span></a></li>
+        <?php
+        }
+        if (CONFIG_OPTIONS_UPLOAD) {
+            ?>
+            <li><a id="actionUpload" href="#"
+                   onclick="return uploadFileWin(this);"><span><?php echo LBL_BTN_UPLOAD; ?></span></a></li>
+        <?php
+        }
+        ?>
+    </ul>
+    <form action="" method="post" name="formAction" id="formAction">
+        <input type="hidden" name="currentFolderPath" id="currentFolderPathVal" value=""/>
+        <select name="selectedDoc[]" id="selectedDoc" style="display:none;" multiple="multiple"></select>
+        <input type="hidden" name="action_value" value="" id="action_value"/>
+    </form>
+</div>
+<div id="body">
+<div id="rightCol">
+    <?php
+    if (CONFIG_LOAD_DOC_LATTER) {
+        $currentPath = getCurrentFolderPath();
+        ?>
+        <script type="text/javascript">
+            parentFolder = {'path_base64': '<?php echo base64_encode(getParentFolderPath($currentPath)); ?>', 'path': '<?php echo getParentFolderPath($currentPath); ?>'};
+            currentFolder = {'friendly_path': '<?php echo transformFilePath($currentPath); ?>'};
+            $(document).ready(
+                function () {
+                    var url = getUrl('view', false, false, false);
+                    $('#rightCol').empty();
+                    ajaxStart('#rightCol');
+
+                    $('#rightCol').load(url,
+                        {},
+                        function () {
+                            ajaxStop('#rightCol img.ajaxLoadingImg');
+                            urls.present = getUrl('home', true, true);
+                            initAfterListingLoaded();
+                        });
+                }
+            );
+        </script>
+    <?php
+    } else {
+        include_once CONFIG_URL_LIST_LISTING;
+    }
+    ?>
 </div>
-    <div id="body">
-      <div id="rightCol">
-	      	<?php
-			if(CONFIG_LOAD_DOC_LATTER ) {
-				$currentPath = getCurrentFolderPath();
-				?>
-
-				<script type="text/javascript">
-				parentFolder = {'path_base64':'<?php echo base64_encode(getParentFolderPath($currentPath)); ?>', 'path':'<?php echo getParentFolderPath($currentPath); ?>'};
-
-				currentFolder = {'friendly_path':'<?php echo transformFilePath($currentPath); ?>'};
-					$(document).ready(
-						function()
-						{
-							var url = getUrl('view', false, false, false);
-							$('#rightCol').empty();
-							ajaxStart('#rightCol');
-
-							$('#rightCol').load(url,
-										{},
-										function(){
-												ajaxStop('#rightCol img.ajaxLoadingImg');
-												urls.present = getUrl('home', true, true);
-												initAfterListingLoaded();
-											});
-						}
-					);
-				</script>
-				<?php
-			} else {
-				include_once CONFIG_URL_LIST_LISTING;
-			}
-	      	?>
-      </div>
-
-      <div id="leftCol">
-				<fieldset id="folderFieldSet" >
-
-				<legend><?php echo LBL_FOLDER_INFO; ?></legend>
-				<table cellpadding="0" cellspacing="0" class="tableSummary" id="folderInfo">
-					<tbody>
-						<tr>
-							<th><?php echo LBL_FOLDER_PATH; ?></th>
-							<td colspan="3" id="folderPath"><?php echo transformFilePath($folderInfo['path']); ?></td>
-  						</tr>
-						<tr>
-							<th><?php echo LBL_FOLDER_CREATED; ?></th>
-							<td colspan="3" id="folderCtime"><?php echo (!empty($folderInfo['ctime'])?date(DATE_TIME_FORMAT,$folderInfo['ctime']):'&nbsp;') ; ?></td>
-
-						</tr>
-						<tr>
-							<th><?php echo LBL_FOLDER_MODIFIED; ?></th>
-							 <!-- comment these lines while integrating into Chamilo -->
-							<th><?php //echo LBL_FOLDER_MODIFIED; ?></th>
-						<!--	<td colspan="3" id="folderMtime"><?php //echo (!empty($folderInfo['mtime'])?date(DATE_TIME_FORMAT,$folderInfo['mtime']):'&nbsp;'); ?></td> -->
-						</tr>
-						<tr>
-							<th><?php echo LBL_FOLDER_SUDDIR; ?></th>
-							<td  colspan="3" id="folderSubdir"><?php echo (isset($folderInfo['subdir'])?$folderInfo['subdir']:"&nbsp;"); ?></td>
-
-						</tr>
-						<tr>
-							<th><?php echo LBL_FOLDER_FIELS; ?></th>
-							<td  colspan="3" id="folderFile"><?php echo (isset($folderInfo['file'])?$folderInfo['file']:'&nbsp;'); ?></td>
-						</tr>
-
-						<tr>
-							 <!-- comment these lines while integrating into Chamilo -->
-							<th><?php // echo LBL_FOLDER_WRITABLE; ?></th>
-						<!--	<td id="folderWritable"><span class="<?php //echo (isset($folderInfo['is_readable'])?($folderInfo['is_readable']?'flagYes':'flagNo'):'&nbsp;'); ?>">&nbsp;</span></td> -->
-							<th><?php // echo LBL_FOLDER_READABLE; ?></th>
-							<!--<td  id="folderReadable"><span class="<?php //echo (isset($folderInfo['is_writable'])?($folderInfo['is_writable']?'flagYes':'flagNo'):'&nbsp;'); ?>">&nbsp;</span></td> -->
-						</tr>
-					</tbody>
-				</table>
-				</fieldset>
-			<fieldset id="fileFieldSet" style="display:none" >
-				<legend><?php echo LBL_FILE_INFO; ?></legend>
-				<table cellpadding="0" cellspacing="0" class="tableSummary" id="fileInfo">
-					<tbody>
-						<tr>
-							<th><?php echo LBL_FILE_NAME; ?></th>
-							<td colspan="3" id="fileName"></td>
-						</tr>
-						<tr>
-							<th><?php echo LBL_FILE_CREATED; ?></th>
-							<td colspan="3" id="fileCtime"></td>
-
-						</tr>
-						<tr>
-							 <!-- comment these lines while integrating into Chamilo -->
-							<th><?php //echo LBL_FILE_MODIFIED; ?></th>
-							<!--<td colspan="3" id="fileMtime"></td> -->
-						</tr>
-
-						<tr>
-							<th><?php echo LBL_FILE_SIZE; ?></th>
-							<td  colspan="3" id="fileSize"></td>
-
-						</tr>
-						<tr>
-							<th><?php echo LBL_FILE_TYPE; ?></th>
-							<td  colspan="3" id="fileType"></td>
-						</tr>
-						<tr>
-							 <!-- comment these lines while integrating into Chamilo -->
-							<th><?php //echo LBL_FILE_WRITABLE; ?></th>
-							<!--<td id="fileWritable"><span class="flagYes">&nbsp;</span></td> -->
-							<th><?php //echo LBL_FILE_READABLE; ?></th>
-							<!--<td id="fileReadable"><span class="flagNo">&nbsp;</span></td> -->
-						</tr>
 
-					</tbody>
-				</table>
+<div id="leftCol">
+    <fieldset id="folderFieldSet">
+
+        <legend><?php echo LBL_FOLDER_INFO; ?></legend>
+        <table cellpadding="0" cellspacing="0" class="tableSummary" id="folderInfo">
+            <tbody>
+            <tr>
+                <th><?php echo LBL_FOLDER_PATH; ?></th>
+                <td colspan="3" id="folderPath"><?php echo transformFilePath($folderInfo['path']); ?></td>
+            </tr>
+            <tr>
+                <th><?php echo LBL_FOLDER_CREATED; ?></th>
+                <td colspan="3" id="folderCtime">
+                    <?php echo(!empty($folderInfo['ctime']) ? date(
+                        DATE_TIME_FORMAT,
+                        $folderInfo['ctime']
+                    ) : '&nbsp;'); ?>
+                </td>
+            </tr>
+            <tr>
+                <th><?php echo LBL_FOLDER_MODIFIED; ?></th>
+                <!-- comment these lines while integrating into Chamilo -->
+                <th><?php //echo LBL_FOLDER_MODIFIED; ?></th>
+            </tr>
+            <tr>
+                <th><?php echo LBL_FOLDER_SUDDIR; ?></th>
+                <td colspan="3" id="folderSubdir">
+                    <?php echo(isset($folderInfo['subdir']) ? $folderInfo['subdir'] : "&nbsp;"); ?>
+                </td>
+            </tr>
+            <tr>
+                <th><?php echo LBL_FOLDER_FIELS; ?></th>
+                <td colspan="3" id="folderFile">
+                    <?php echo(isset($folderInfo['file']) ? $folderInfo['file'] : '&nbsp;'); ?>
+                </td>
+            </tr>
+            <tr>
+                <!-- comment these lines while integrating into Chamilo -->
+                <th><?php // echo LBL_FOLDER_WRITABLE; ?></th>
+                <th><?php // echo LBL_FOLDER_READABLE; ?></th>
+            </tr>
+            </tbody>
+        </table>
+    </fieldset>
+    <fieldset id="fileFieldSet" style="display:none">
+        <legend><?php echo LBL_FILE_INFO; ?></legend>
+        <table cellpadding="0" cellspacing="0" class="tableSummary" id="fileInfo">
+            <tbody>
+            <tr>
+                <th><?php echo LBL_FILE_NAME; ?></th>
+                <td colspan="3" id="fileName"></td>
+            </tr>
+            <tr>
+                <th><?php echo LBL_FILE_CREATED; ?></th>
+                <td colspan="3" id="fileCtime"></td>
+            </tr>
+            <tr>
+                <!-- comment these lines while integrating into Chamilo -->
+                <th><?php //echo LBL_FILE_MODIFIED; ?></th>
+                <!--<td colspan="3" id="fileMtime"></td> -->
+            </tr>
+            <tr>
+                <th><?php echo LBL_FILE_SIZE; ?></th>
+                <td colspan="3" id="fileSize"></td>
+            </tr>
+            <tr>
+                <th><?php echo LBL_FILE_TYPE; ?></th>
+                <td colspan="3" id="fileType"></td>
+            </tr>
+            <tr>
+                <!-- comment these lines while integrating into Chamilo -->
+                <th><?php //echo LBL_FILE_WRITABLE; ?></th>
+                <!--<td id="fileWritable"><span class="flagYes">&nbsp;</span></td> -->
+                <th><?php //echo LBL_FILE_READABLE; ?></th>
+                <!--<td id="fileReadable"><span class="flagNo">&nbsp;</span></td> -->
+            </tr>
+            </tbody>
+        </table>
 
         <p class="searchButtons" id="returnCurrentUrl">
         	<span class="right" id="linkSelect">
@@ -424,89 +418,83 @@ if(!empty($_GET['view'])) {
         		<!-- Change button class by Chamilo select_button class -->
         	</span>
         </p>
-		</fieldset>
-
-
-      	<fieldset class="boxSearch">
-      		<legend><?php echo LBL_SEARCH; ?></legend>
-          <table cellpadding="0" cellspacing="0" class="tableSearch">
-          	<tbody>
-	          <tr>
-	          	<td>
-	          		<!-- comment these lines while integrating into Chamilo -->
-	          		<b><?php //echo LBL_SEARCH_NAME; ?></b> <br />
-	            	<input type="text" class="input inputSearch" name="search_name" id="search_name" size="18"/>
-	          	</td>
-
-	         </tr>
-	          <tr>
-	          	<td >
-	          	 <!-- comment these lines while integrating into Chamilo -->
-	          	<b><?php // echo LBL_SEARCH_FOLDER; ?></b><br />
+    </fieldset>
+
+    <fieldset class="boxSearch">
+        <legend><?php echo LBL_SEARCH; ?></legend>
+        <table cellpadding="0" cellspacing="0" class="tableSearch">
+            <tbody>
+            <tr>
+                <td>
+                    <!-- comment these lines while integrating into Chamilo -->
+                    <b><?php //echo LBL_SEARCH_NAME; ?></b> <br/>
+                    <input type="text" class="input inputSearch" name="search_name" id="search_name" size="18"/>
+                </td>
+            </tr>
+            <tr>
+                <td>
+                    <!-- comment these lines while integrating into Chamilo -->
+                    <b><?php // echo LBL_SEARCH_FOLDER; ?></b><br/>
 	          	<span id="searchFolderContainer">
 	          	<?php
-	          		if(CONFIG_LOAD_DOC_LATTER)
-	          		{
-	          			?>
-	          			<script type="text/javascript">
-	          				$(document).ready(
-	          					function()
-	          					{
-	          						ajaxStart('#searchFolderContainer');
-	          						$('#searchFolderContainer').load('<?php echo CONFIG_URL_LOAD_FOLDERS; ?>');
-	          					}
-	          				);
-	          			</script>
-	          			<?php
-	          		}else
-	          		{
-	          	?>
-
-		            <select class="input inputSearchSelect" name="search_folder" id="search_folder"><!-- Chamilo integrating, modify name class for disable by css -->
-		            	<?php
-
-										foreach(getFolderListing(CONFIG_SYS_ROOT_PATH) as $k=>$v)
-										{
-											if(hideFolderName($k))
-											{
-												//show only those permitted by Chamilo
-												?>
-		                  						<option value="<?php echo $v; ?>" <?php echo (removeTrailingSlash(backslashToSlash(($folderInfo['path']))) == removeTrailingSlash(backslashToSlash(($v)))?' selected="selected"':''); ?>><?php echo hideFolderName(shortenFileName($k, 30));
-												?></option>
-
-		                  <?php
-											}
-										}
-
-									?>
-		            </select>
-		      <?php
-	          		}
-		      ?></span>
-	        <!--  </td>
-	         </tr>
-        		<tr>
-        			<td> -->
-        		<b><?php //echo LBL_SEARCH_MTIME; ?></b><br />
-        		<!--<input type="text" class="input inputMtime" name="search_mtime_from" id="search_mtime_from" value="<?php //echo (!empty($_GET['search_mtime_from'])?$_GET['search_mtime_from']:''); ?>" />  -->
-        		<!--<span class="leftToRightArrow">&nbsp;</span> -->
-        		<!--<input type="text" class="input inputMtime" name="search_mtime_to" id="search_mtime_to" value="<?php //echo (!empty($_GET['search_mtime_to'])?$_GET['search_mtime_to']:''); ?>" /> -->
-                 <!--This lines replace above lines while integrating into Chamilo -->
-                <input type="hidden" name="search_mtime_from" id="search_mtime_from" value="<?php //echo (!empty($_GET['search_mtime_from'])?$_GET['search_mtime_from']:''); ?>" />
-        		<input type="hidden" name="search_mtime_to" id="search_mtime_to" value="<?php //echo (!empty($_GET['search_mtime_to'])?$_GET['search_mtime_to']:''); ?>" />
-        	<!--</td></tr>
-			<tr>
-				<td>  --><!-- comment these lines while integrating into Chamilo -->
-                </td><td><!--add a col while integrating -->
-          	<b><?php  // echo LBL_SEARCH_RECURSIVELY; ?></b>&nbsp;&nbsp;
-		<!--change for Chamilo recursively by default  -->
-     <!--     	<input type="radio" name="search_recursively" value="1" id="search_recursively_1" class="radio" <?php //echo (empty($_GET['search_recursively'])?'checked="checked"':''); ?> /> <?php //echo LBL_RECURSIVELY_YES; ?> -->
-        <!--  	<input type="radio" name="search_recursively" value="0" id="search_recursively_0" class="radio" <?php //echo (!empty($_GET['search_recursively'])?'checked="checked"':''); ?> /> <?php //echo LBL_RECURSIVELY_NO; ?> -->
-          	</td>
-
-          </tr>
-          	</tbody>
-</table>
+                if (CONFIG_LOAD_DOC_LATTER) {
+                    ?>
+                    <script type="text/javascript">
+                        $(document).ready(
+                            function () {
+                                ajaxStart('#searchFolderContainer');
+                                $('#searchFolderContainer').load('<?php echo CONFIG_URL_LOAD_FOLDERS; ?>');
+                            }
+                        );
+                    </script>
+                <?php
+                } else {
+                    ?>
+
+                    <select class="input inputSearchSelect" name="search_folder" id="search_folder">
+                        <!-- Chamilo integrating, modify name class for disable by css -->
+                        <?php
+                        foreach (getFolderListing(CONFIG_SYS_ROOT_PATH) as $k => $v) {
+                            if (hideFolderName($k)) {
+                                //show only those permitted by Chamilo
+                                ?>
+                                <option value="<?php echo $v; ?>" <?php echo(removeTrailingSlash(
+                                    backslashToSlash(($folderInfo['path']))
+                                ) == removeTrailingSlash(
+                                    backslashToSlash(($v))
+                                ) ? ' selected="selected"' : ''); ?>><?php echo hideFolderName(shortenFileName($k, 30));
+                                    ?>
+                                </option>
+                            <?php
+                            }
+                        }
+                        ?>
+                    </select>
+                <?php
+                }
+                ?></span>
+                    <b><?php //echo LBL_SEARCH_MTIME; ?></b><br/>
+                    <!--<input type="text" class="input inputMtime" name="search_mtime_from" id="search_mtime_from" value="<?php //echo (!empty($_GET['search_mtime_from'])?$_GET['search_mtime_from']:''); ?>" />  -->
+                    <!--<span class="leftToRightArrow">&nbsp;</span> -->
+                    <!--<input type="text" class="input inputMtime" name="search_mtime_to" id="search_mtime_to" value="<?php //echo (!empty($_GET['search_mtime_to'])?$_GET['search_mtime_to']:''); ?>" /> -->
+                    <!--This lines replace above lines while integrating into Chamilo -->
+                    <input type="hidden" name="search_mtime_from" id="search_mtime_from"
+                           value="<?php //echo (!empty($_GET['search_mtime_from'])?$_GET['search_mtime_from']:''); ?>"/>
+                    <input type="hidden" name="search_mtime_to" id="search_mtime_to"
+                           value="<?php //echo (!empty($_GET['search_mtime_to'])?$_GET['search_mtime_to']:''); ?>"/>
+                    <!--</td></tr>
+                    <tr>
+                        <td>  --><!-- comment these lines while integrating into Chamilo -->
+                </td>
+                <td><!--add a col while integrating -->
+                    <b><?php // echo LBL_SEARCH_RECURSIVELY; ?></b>&nbsp;&nbsp;
+                    <!--change for Chamilo recursively by default  -->
+                    <!--     	<input type="radio" name="search_recursively" value="1" id="search_recursively_1" class="radio" <?php //echo (empty($_GET['search_recursively'])?'checked="checked"':''); ?> /> <?php //echo LBL_RECURSIVELY_YES; ?> -->
+                    <!--  	<input type="radio" name="search_recursively" value="0" id="search_recursively_0" class="radio" <?php //echo (!empty($_GET['search_recursively'])?'checked="checked"':''); ?> /> <?php //echo LBL_RECURSIVELY_NO; ?> -->
+                </td>
+            </tr>
+            </tbody>
+        </table>
         <p class="searchButtons">
         	<span class="left" id="linkClose" style="display:none">
                   <!-- comment these lines while integrating into Chamilo -->
@@ -516,204 +504,217 @@ if(!empty($_GET['view'])) {
         		<input type="button" value="<?php echo BTN_SEARCH; ?>" onclick="return search();" class="search_button">
         	</span>
         </p>
-        </fieldset>
-      </div>
-      <div class="clear"></div>
+    </fieldset>
+</div>
+<div class="clear"></div>
+</div>
+</div>
+<div class="clear"></div>
+<div id="ajaxLoading" style="display:none">
+    <img class="ajaxLoadingImg" src="theme/<?php echo CONFIG_THEME_NAME; ?>/images/ajaxLoading.gif"/></div>
+<div id="winUpload" style="display:none">
+    <div class="jqmContainer">
+        <div class="jqmHeader">
+            <!-- Adding return windowRefresch() for Chamilo -->
+            <a href="#" onclick="tb_remove();return windowRefresh();">
+                <img src="theme/default/images/flagno.png" title="<?php echo LBL_ACTION_CLOSE; ?>">
+                <?php echo LBL_ACTION_CLOSE; ?>
+            </a>
+            <!-- Add close image for Chamilo -->
+        </div>
+        <div class="jqmBody">
+            <form id="formUpload" name="formUpload" method="post" enctype="multipart/form-data" action="">
+                <table class="tableForm" cellpadding="0" cellspacing="0">
+                    <thead>
+                    <tr>
+                        <th colspan="2">
+                            <?php echo FILE_FORM_TITLE; ?>
+                        </th>
+                    </tr>
+                    <tr>
+                        <th colspan="2" align="left">
+                            <label>
+                                <a class="action" href="#" title="<?php echo FILE_LBL_MORE; ?>"
+                                   onclick="return addMoreFile();">
+                                    <label><?php echo FILE_LBL_MORE; ?></label><span class="addMore">&nbsp;</span></a>
+                            </label>
+                        </th>
+                    </tr>
+                    </thead>
+                    <tbody id="fileUploadBody">
+                    <tr style="display:none">
+                        <th><label><?php echo FILE_LABEL_SELECT; ?></label></th>
+                        <td>
+                            <input type="file" class="input" name="file"/>
+                            <input type="button" class="upload_button" value="<?php echo FILE_LBL_UPLOAD; ?>"/><!-- change style of upload button by Chamilo -->
+                            <a href="#" class="action" title="<?php echo get_lang('Cancel') ?>" style="display:none">
+                                <!-- Chamilo lang var added -->
+                                <span class="cancel">&nbsp;</span><span class="uploadProcessing" style="display:none">&nbsp;</span>
+                            </a>
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </div>
     </div>
-  </div>
-  <div class="clear"></div>
-  <div id="ajaxLoading" style="display:none">
-  	<img class="ajaxLoadingImg" src="theme/<?php echo CONFIG_THEME_NAME; ?>/images/ajaxLoading.gif" /></div>
-  <div id="winUpload" style="display:none">
-  	<div class="jqmContainer">
-  		<div class="jqmHeader">
-        	<!-- Adding return windowRefresch() for Chamilo -->
-  			<a href="#" onclick="tb_remove();return windowRefresh();">
-  				<img src="theme/default/images/flagno.png"title="<?php echo LBL_ACTION_CLOSE; ?>">
-  				<?php echo LBL_ACTION_CLOSE; ?>
-  			</a>
-  			<!-- Add close image for Chamilo -->
-  		</div>
-  		<div class="jqmBody">
-		  	<form id="formUpload" name="formUpload" method="post" enctype="multipart/form-data" action="">
-		  	<table class="tableForm" cellpadding="0" cellspacing="0">
-		  		<thead>
-		  			<tr>
-		  				<th colspan="2">
-		  					<?php echo FILE_FORM_TITLE; ?>
-		  				</th>
-		  			</tr>
-		  			<tr>
-		  			<th colspan="2" align="left">
-		  				<label>
-		  				<a class="action" href="#" title="<?php echo FILE_LBL_MORE;  ?>" onclick="return addMoreFile();">
-			  				<label><?php echo FILE_LBL_MORE;  ?></label><span class="addMore">&nbsp;</span></a>
-			  			</label>
-
-		  			</th>
-
-		  			</tr>
-		  		</thead>
-		  		<tbody id="fileUploadBody">
-		  			<tr style="display:none">
-		  				<th><label><?php echo FILE_LABEL_SELECT; ?></label></th>
-		  				<td>
-		  					<input type="file" class="input" name="file"  />
-		  					<input type="button" class="upload_button" value="<?php echo FILE_LBL_UPLOAD; ?>" /><!-- change style of upload button by Chamilo -->
-		  					<a href="#" class="action" title="<?php echo get_lang('Cancel')?>" style="display:none" ><!-- Chamilo lang var added -->
-		  						<span class="cancel">&nbsp;</span><span class="uploadProcessing" style="display:none">&nbsp;</span>
-		  					</a>
-
-		  				</td>
-		  			</tr>
-		  		</tbody>
-		  	</table>
-		  	</form>
-  		</div>
-  	</div>
-  </div>
-  <div id="winNewFolder" style="display:none">
-  	<div class="jqmContainer">
-  		<div class="jqmHeader">
-  			<a href="#" onclick="return tb_remove();"><img src="theme/default/images/flagno.png"title="<?php echo LBL_ACTION_CLOSE; ?>"><?php echo LBL_ACTION_CLOSE; ?></a><!-- Add close image for Chamilo -->
-  		</div>
-  		<div class="jqmBody">
-	    	<form id="formNewFolder" name="formNewFolder" method="post" action="">
-	  	<input type="hidden" name="currentFolderPath" value="" id="currentNewfolderPath" />
-	  	<table class="tableForm" cellpadding="0" cellspacing="0">
-	  		<thead>
-	  			<tr>
-	  				<th colspan="2"><?php echo FOLDER_FORM_TITLE; ?></th>
-	  			</tr>
-	  		</thead>
-	  		<tbody>
-	  			<tr>
-	  				<th><label><?php echo FOLDER_LBL_TITLE; ?></label></th>
-	  				<td><input type="text" name="new_folder" id="new_folder" value="" class="input"></td>
-	  			</tr>
-	  		</tbody>
-	  		<tfoot>
-	  			<tr>
-	  				<th>&nbsp;</th>
-	  				<td><input type="button" value="<?php echo FOLDER_LBL_CREATE; ?>" class="create_button" onclick="return doCreateFolder();"  /></td>
-	  			</tr>
-	  		</tfoot>
-	  	</table>
-	  	</form>
-  		</div>
-  	</div>
-  </div>
-  <div id="winPlay" style="display:none">
-  	<div class="jqmContainer">
-  		<div class="jqmHeader">
-  			<a href="#" onclick="return closeWinPlay();"><img src="theme/default/images/flagno.png"title="<?php echo LBL_ACTION_CLOSE; ?>"><?php echo LBL_ACTION_CLOSE; ?></a><!-- Add close image for Chamilo -->
-  		</div>
-  		<div class="jqmBody">
-  			<div id="playGround"></div>
-  		</div>
-  	</div>
-  </div>
-  <div id="winRename" style="display:none">
-  	<div class="jqmContainer">
-  		<div class="jqmHeader">
-            <a href="#" onclick="return tb_remove();"><img src="theme/default/images/flagno.png"title="<?php echo LBL_ACTION_CLOSE; ?>"><?php echo LBL_ACTION_CLOSE; ?></a><!-- Add close image for Chamilo -->
-  		</div>
-  		<div class="jqmBody">
-		  	<form id="formRename" name="formRename" method="post" action="">
-		  	<input type="hidden" name="original_path" id="original_path" />
-		  	<input type="hidden" name="num" id="renameNum" value="" />
-		  	<table class="tableForm" cellpadding="0" cellspacing="0">
-		  		<thead>
-		  			<tr>
-		  				<th colspan="2"><?php echo RENAME_FORM_TITLE; ?></th>
-		  			</tr>
-		  		</thead>
-		  		<tbody>
-		  			<tr>
-		  				<th><label><?php echo RENAME_NEW_NAME; ?></label></th>
-		  				<td><input type="name" id="renameName" class="input" name="name" /> <!--  Chamilo delete style="width:250px"-->
-		          </td>
-		  			</tr>
-		  		</tbody>
-		  		<tfoot>
-		  			<tr>
-		  				<th>&nbsp;</th>
-		  				<td><input type="button" value="<?php echo RENAME_LBL_RENAME; ?>" class="create_button" onclick="return doRename();"  /></td>
-		  			</tr>
-		  		</tfoot>
-		  	</table>
-		  	</form>
-  		</div>
-
-  	</div>
-
-  </div>
-  <div id="winInfo" style="display:none">
-  	<div class="jqmContainer">
-  		<div class="jqmHeader">
-  			<a href="#" onclick="tb_remove();"><?php echo LBL_ACTION_CLOSE; ?></a>
-  		</div>
-  		<div class="jqmBody">
-   	<table class="tableInfo" cellpadding="0" cellspacing="0">
-  		<tbody>
-  			<tr>
-	  			<th nowrap>
-	  				<label>Author:</label>
-	  			</th>
-	  			<td>
-	  				<a href="&#109;a&#105;l&#116;&#111;:&#99;&#97;&#105;&#108;&#111;&#110;&#103;&#113;&#117;&#110;&#64;&#121;&#97;&#104;&#111;&#111;&#46;&#99;&#111;&#109;&#46;&#99;&#110;">Logan Cai</a>
-	  			</td>
-  			</tr>
-  			<tr>
-  				<th nowrap>
-  					<label>Template Designer:</label>
-  				</th>
-  				<td>
-  					<a href="&#109;a&#105;l&#116;&#111;:&#71;&#97;&#98;&#114;&#105;&#101;&#108;&#64;&#52;&#118;&#46;&#99;&#111;&#109;&#46;&#98;&#114;">Gabriel</a>
-  				</td>
-  			</tr>
-  			<tr>
-  				<th  nowrap>
-  					<label>Official Website:</label>
-  				</th>
-  				<td>
-  					<a href="http://www.phpletter.com">http://www.phpletter.com</a>
-  				</td>
-  			</tr>
-  			<tr>
-  				<th  nowrap>
-  					<label>Support Forum:</label>
-  				</th>
-  				<td>
-  					<a href="http://www.phpletter.com/forum/">http://www.phpletter.com/forum/</a>
-  				</td>
-  			</tr>
-  			<tr>
-  				<th nowrap>
-  					<label>&copy;Copyright:</label>
-  				</th>
-  				<td>
-  					All copyright declarations in the source must remain unchange. Please contact us if you need to make changes to it, in order to avoid any Legal Issues.
-  				</td>
-  			</tr>
-  		</tbody>
-  	</table>
-  		</div>
-  	</div>
-  </div>
-  <div id="contextMenu" style="display:none">
-  	<ul>
-  		<li><a href="#" class="contentMenuItem"  id="menuSelect"><?php echo MENU_SELECT; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuPreview"><?php echo MENU_PREVIEW; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuDownload"><?php echo MENU_DOWNLOAD; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuRename"><?php echo MENU_RENAME; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuEdit"><?php echo MENU_EDIT; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuCut"><?php echo MENU_CUT; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuCopy"><?php echo MENU_COPY; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuPaste"><?php echo MENU_PASTE; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuDelete"><?php echo MENU_DELETE; ?></a></li>
-  		<li><a href="#" class="contentMenuItem"  id="menuPlay"><?php echo MENU_PLAY; ?></a></li>
-  	</ul>
-  </div>
+</div>
+<div id="winNewFolder" style="display:none">
+    <div class="jqmContainer">
+        <div class="jqmHeader">
+            <a href="#" onclick="return tb_remove();">
+                <img src="theme/default/images/flagno.png" title="<?php echo LBL_ACTION_CLOSE; ?>"><?php echo LBL_ACTION_CLOSE; ?>
+            </a><!-- Add close image for Chamilo -->
+        </div>
+        <div class="jqmBody">
+            <form id="formNewFolder" name="formNewFolder" method="post" action="">
+                <input type="hidden" name="currentFolderPath" value="" id="currentNewfolderPath"/>
+                <table class="tableForm" cellpadding="0" cellspacing="0">
+                    <thead>
+                    <tr>
+                        <th colspan="2"><?php echo FOLDER_FORM_TITLE; ?></th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    <tr>
+                        <th><label><?php echo FOLDER_LBL_TITLE; ?></label></th>
+                        <td><input type="text" name="new_folder" id="new_folder" value="" class="input"></td>
+                    </tr>
+                    </tbody>
+                    <tfoot>
+                    <tr>
+                        <th>&nbsp;</th>
+                        <td>
+                            <input type="button" value="<?php echo FOLDER_LBL_CREATE; ?>" class="create_button"
+                                   onclick="return doCreateFolder();"/>
+                        </td>
+                    </tr>
+                    </tfoot>
+                </table>
+            </form>
+        </div>
+    </div>
+</div>
+<div id="winPlay" style="display:none">
+    <div class="jqmContainer">
+        <div class="jqmHeader">
+            <a href="#" onclick="return closeWinPlay();">
+                <img src="theme/default/images/flagno.png" title="<?php echo LBL_ACTION_CLOSE; ?>">
+                <?php echo LBL_ACTION_CLOSE; ?>
+            </a><!-- Add close image for Chamilo -->
+        </div>
+        <div class="jqmBody">
+            <div id="playGround"></div>
+        </div>
+    </div>
+</div>
+<div id="winRename" style="display:none">
+    <div class="jqmContainer">
+        <div class="jqmHeader">
+            <a href="#" onclick="return tb_remove();">
+                <img src="theme/default/images/flagno.png" title="<?php echo LBL_ACTION_CLOSE; ?>">
+                <?php echo LBL_ACTION_CLOSE; ?>
+            </a><!-- Add close image for Chamilo -->
+        </div>
+        <div class="jqmBody">
+            <form id="formRename" name="formRename" method="post" action="">
+                <input type="hidden" name="original_path" id="original_path"/>
+                <input type="hidden" name="num" id="renameNum" value=""/>
+                <table class="tableForm" cellpadding="0" cellspacing="0">
+                    <thead>
+                    <tr>
+                        <th colspan="2"><?php echo RENAME_FORM_TITLE; ?></th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    <tr>
+                        <th><label><?php echo RENAME_NEW_NAME; ?></label></th>
+                        <td><input type="name" id="renameName" class="input" name="name"/>
+                            <!--  Chamilo delete style="width:250px"-->
+                        </td>
+                    </tr>
+                    </tbody>
+                    <tfoot>
+                    <tr>
+                        <th>&nbsp;</th>
+                        <td>
+                            <input type="button" value="<?php echo RENAME_LBL_RENAME; ?>" class="create_button" onclick="return doRename();"/>
+                        </td>
+                    </tr>
+                    </tfoot>
+                </table>
+            </form>
+        </div>
+    </div>
+</div>
+<div id="winInfo" style="display:none">
+    <div class="jqmContainer">
+        <div class="jqmHeader">
+            <a href="#" onclick="tb_remove();"><?php echo LBL_ACTION_CLOSE; ?></a>
+        </div>
+        <div class="jqmBody">
+            <table class="tableInfo" cellpadding="0" cellspacing="0">
+                <tbody>
+                <tr>
+                    <th nowrap>
+                        <label>Author:</label>
+                    </th>
+                    <td>
+                        <a href="&#109;a&#105;l&#116;&#111;:&#99;&#97;&#105;&#108;&#111;&#110;&#103;&#113;&#117;&#110;&#64;&#121;&#97;&#104;&#111;&#111;&#46;&#99;&#111;&#109;&#46;&#99;&#110;">Logan
+                            Cai</a>
+                    </td>
+                </tr>
+                <tr>
+                    <th nowrap>
+                        <label>Template Designer:</label>
+                    </th>
+                    <td>
+                        <a href="&#109;a&#105;l&#116;&#111;:&#71;&#97;&#98;&#114;&#105;&#101;&#108;&#64;&#52;&#118;&#46;&#99;&#111;&#109;&#46;&#98;&#114;">Gabriel</a>
+                    </td>
+                </tr>
+                <tr>
+                    <th nowrap>
+                        <label>Official Website:</label>
+                    </th>
+                    <td>
+                        <a href="http://www.phpletter.com">http://www.phpletter.com</a>
+                    </td>
+                </tr>
+                <tr>
+                    <th nowrap>
+                        <label>Support Forum:</label>
+                    </th>
+                    <td>
+                        <a href="http://www.phpletter.com/forum/">http://www.phpletter.com/forum/</a>
+                    </td>
+                </tr>
+                <tr>
+                    <th nowrap>
+                        <label>&copy;Copyright:</label>
+                    </th>
+                    <td>
+                        All copyright declarations in the source must remain unchange. Please contact us if you need to
+                        make changes to it, in order to avoid any Legal Issues.
+                    </td>
+                </tr>
+                </tbody>
+            </table>
+        </div>
+    </div>
+</div>
+<div id="contextMenu" style="display:none">
+    <ul>
+        <li><a href="#" class="contentMenuItem" id="menuSelect"><?php echo MENU_SELECT; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuPreview"><?php echo MENU_PREVIEW; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuDownload"><?php echo MENU_DOWNLOAD; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuRename"><?php echo MENU_RENAME; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuEdit"><?php echo MENU_EDIT; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuCut"><?php echo MENU_CUT; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuCopy"><?php echo MENU_COPY; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuPaste"><?php echo MENU_PASTE; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuDelete"><?php echo MENU_DELETE; ?></a></li>
+        <li><a href="#" class="contentMenuItem" id="menuPlay"><?php echo MENU_PLAY; ?></a></li>
+    </ul>
+</div>
 </body>
 </html>

+ 0 - 5
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php

@@ -11,9 +11,6 @@
  * @since 31/December/2008
  */
 
-//error_reporting(E_ALL);
-//error_reporting(E_ALL ^ E_NOTICE);
-
 //Access Control Setting
 /**
 * turn off => false
@@ -120,8 +117,6 @@ define('CONFIG_SYS_ROOT_PATH',		$PathChamiloAjaxFileManager);
 
 // end chamilo
 
-
-
 define('CONFIG_SYS_FOLDER_SHOWN_ON_TOP', true); //show your folders on the top of list if true or order by name
 define("CONFIG_SYS_DIR_SESSION_PATH", session_save_path()); // Hack by Juan Carlos Raña
 define("CONFIG_SYS_PATTERN_FORMAT", 'list'); //three options: reg ,csv, list, this option define the parttern format for the following patterns

+ 3 - 4
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.php

@@ -16,8 +16,9 @@
 // Loading the global initialization file.
 require_once '../../../../../../inc/global.inc.php';
 
-// Loading document repositories settings.
+api_block_anonymous_users();
 
+// Loading document repositories settings.
 require_once api_get_path(LIBRARY_PATH).'fckeditor/repository.php';
 
 //FILESYSTEM CONFIG
@@ -48,7 +49,6 @@ define('DIR_AJAX_JS', DIR_AJAX_ROOT.'jscripts'.DIRECTORY_SEPARATOR);
 define('DIR_AJAX_EDIT_AREA', DIR_AJAX_JS.'edit_area'.DIRECTORY_SEPARATOR);
 define('DIR_LANG', DIR_AJAX_ROOT.'langs'.DIRECTORY_SEPARATOR);
 
-
 //Class Declarations
 define('CLASS_FILE', DIR_AJAX_INC.'class.file.php');
 define("CLASS_UPLOAD", DIR_AJAX_INC.'class.upload.php');
@@ -69,7 +69,6 @@ if (CONFIG_QUERY_STRING_ENABLE && !empty($_GET['config']) && file_exists(dirname
 
 require_once dirname(__FILE__).DIRECTORY_SEPARATOR.$configBaseFileName;
 
-
 // Loading the selected language file.
 require_once DIR_AJAX_LANGS.CONFIG_LANG_DEFAULT.".php";
 
@@ -116,4 +115,4 @@ define('CONFIG_URL_SAVE_TEXT', 'ajax_save_text.php');
 define('CONFIG_URL_LIST_LISTING', 'ajax_get_file_listing.php');
 define('CONFIG_URL_IMG_THUMBNAIL', $web_path.'ajax_image_thumbnail.php');
 define('CONFIG_URL_FILEnIMAGE_MANAGER', 'ajaxfilemanager.php');
-define('CONFIG_URL_FILE_PASTE', 'ajax_file_paste.php');
+define('CONFIG_URL_FILE_PASTE', 'ajax_file_paste.php');

+ 0 - 131
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.tinymce.php

@@ -1,131 +0,0 @@
-<?php
-	/**
-	 * sysem base config setting
-	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
-	 * @link www.phpletter.com
-	 * @since 1/August/2007
-	 *
-	 */
-
-
-error_reporting(E_ALL);
-//error_reporting(E_ALL ^ E_NOTICE);
-
-
-
-	//Access Control Setting
-	/**
-	 * turn off => false
-	 * by session => true
-	 */
-	define('CONFIG_ACCESS_CONTROL_MODE', false);
-	define("CONFIG_LOGIN_USERNAME", 'ajax');
-	define('CONFIG_LOGIN_PASSWORD', '123456');
-	define('CONFIG_LOGIN_PAGE', 'ajax_login.php'); //the url to the login page
-
-	//SYSTEM MODE CONFIG
-		/**
-		 * turn it on when you have this system for demo purpose
-		*  that means changes made to each image is not physically applied to it
-		*  and all uploaded files/created folders will be removed automatically
-		*/
-	define('CONFIG_SYS_DEMO_ENABLE', false);
-	define('CONFIG_SYS_VIEW_ONLY', false); //diabled the system, view only
-	define('CONFIG_SYS_THUMBNAIL_VIEW_ENABLE', true);//REMOVE THE thumbnail view if false
-
-	//User Permissions
-	define('CONFIG_OPTIONS_DELETE', true);
-	define('CONFIG_OPTIONS_CUT', true);
-	define('CONFIG_OPTIONS_COPY', true);
-	define('CONFIG_OPTIONS_NEWFOLDER', true);
-	define('CONFIG_OPTIONS_RENAME', true);
-	define('CONFIG_OPTIONS_UPLOAD', true); //
-	define('CONFIG_OPTIONS_EDITABLE', true); //disable image editor and text editor
-	//FILESYSTEM CONFIG
-		/*
-		* CONFIG_SYS_DEFAULT_PATH is the default folder where the files would be uploaded to
-			and it must be a folder under the CONFIG_SYS_ROOT_PATH or the same folder
-			these two paths accept relative path only, don't use absolute path
-		*/
-
-	define('CONFIG_SYS_DEFAULT_PATH', '../uploaded/'); //accept relative path only
-	define('CONFIG_SYS_ROOT_PATH', '../uploaded/');	//accept relative path only
-	define('CONFIG_SYS_FOLDER_SHOWN_ON_TOP', true); //show your folders on the top of list if true or order by name
-	define("CONFIG_SYS_DIR_SESSION_PATH", 'session/');
-	define("CONFIG_SYS_PATTERN_FORMAT", 'list'); //three options: reg ,csv, list, this option define the parttern format for the following patterns
-		/**
-		 * reg => regulare expression
-		 * csv => a list of comma separated file/folder name, (exactly match the specified file/folders)
-		 * list => a list of comma spearated vague file/folder name (partially match the specified file/folders)
-		 *
-		 */
-	//more details about regular expression please visit http://nz.php.net/manual/en/function.eregi.php
-	define('CONFIG_SYS_INC_DIR_PATTERN', ''); //force listing of folders with such pattern(s). separated by , if multiple
-	define('CONFIG_SYS_EXC_DIR_PATTERN', ''); //will prevent listing of folders with such pattern(s). separated by , if multiple
-	define('CONFIG_SYS_INC_FILE_PATTERN', ''); //force listing of fiels with such pattern(s). separated by , if multiple
-	define('CONFIG_SYS_EXC_FILE_PATTERN', ''); //will prevent listing of files with such pattern(s). separated by , if multiple
-	define('CONFIG_SYS_DELETE_RECURSIVE', 1); //delete all contents within a specific folder if set to be 1
-
-	//UPLOAD OPTIONS CONFIG
-	define('CONFIG_UPLOAD_MAXSIZE', 50 * 1024 ); //by bytes
-	//define('CONFIG_UPLOAD_MAXSIZE', 2048); //by bytes
-	//define('CONFIG_UPLOAD_VALID_EXTS', 'txt');//
-
-	define('CONFIG_EDITABLE_VALID_EXTS', 'txt,htm,html,xml,js,css'); //make you include all these extension in CONFIG_UPLOAD_VALID_EXTS if you want all valid
-
-	define('CONFIG_OVERWRITTEN', false); //overwirte when processing paste
-	define('CONFIG_UPLOAD_VALID_EXTS', 'gif,jpg,png,txt'); //
-	//define('CONFIG_UPLOAD_VALID_EXTS', 'gif,jpg,png,bmp,tif,zip,sit,rar,gz,tar,htm,html,mov,mpg,avi,asf,mpeg,wmv,aif,aiff,wav,mp3,swf,ppt,rtf,doc,pdf,xls,txt,xml,xsl,dtd');//
-	define("CONFIG_VIEWABLE_VALID_EXTS", 'gif,bmp,txt,jpg,png,tif,html,htm,js,css,xml,xsl,dtd,mp3,wav,wmv,wma,rm,rmvb,mov,swf');
-	//define('CONFIG_UPLOAD_VALID_EXTS', 'gif,jpg,png,txt'); //
-	define('CONFIG_UPLOAD_INVALID_EXTS', '');
-
-	//Preview
-	define('CONFIG_IMG_THUMBNAIL_MAX_X', 100);
-	define('CONFIG_IMG_THUMBNAIL_MAX_Y', 100);
-	define('CONFIG_THICKBOX_MAX_WIDTH', 700);
-	define('CONFIG_THICKBOX_MAX_HEIGHT', 430);
-
-
-		/**
-		 * CONFIG_URL_PREVIEW_ROOT was replaced by CONFIG_WEBSITE_DOCUMENT_ROOT since v0.8
-		 * Normally, you don't need to bother with CONFIG_WEBSITE_DOCUMENT_ROOT
-		 * Howerver, some Web Hosts do not have standard php.ini setting
-		 * which you will find the file manager can not locate your files correctly
-		 * if you do have such issue, please change it to fit your system.
-		 * so what should you to do get it
-		 *   1. create a php script file (let's call it document_root.php)
-		 *   2. add the following codes in in
-		 * 			<?php
-		 * 				echo dirname(__FILE__);
-		 * 			?>
-		 *   3. upload document_root.php to you website root folder which will only be reached when you visit http://www.domain-name.com or http://localhost/ at localhost computer
-		 *   4. run it via http://www.domain-name.com/document_root.php or http://localhost/docuent_root.php if localhost computer, the url has to be exactly like that
-		 *   5. the value shown on the screen is CONFIG_WEBSITE_DOCUMENT_ROOT should be
-		 *   6. enjoy it
-
-
-		 *
-		 */
-
-
-	define('CONFIG_WEBSITE_DOCUMENT_ROOT', '');
-	//theme related setting
-			/*
-			*	options avaialbe for CONFIG_EDITOR_NAME are:
-					stand_alone
-					tinymce
-					fckeditor
-			*/
-	//CONFIG_EDITOR_NAME replaced CONFIG_THEME_MODE since @version 0.8
-	define('CONFIG_EDITOR_NAME', (CONFIG_QUERY_STRING_ENABLE && !empty($_GET['editor'])?secureFileName($_GET['editor']):'stand_alone'));
-	define('CONFIG_THEME_NAME', (CONFIG_QUERY_STRING_ENABLE && !empty($_GET['theme'])?secureFileName($_GET['theme']):'default'));  //change the theme to your custom theme rather than default
-	define('CONFIG_DEFAULT_VIEW', (CONFIG_SYS_THUMBNAIL_VIEW_ENABLE?'detail':'detail')); //thumnail or detail
-	define('CONFIG_DEFAULT_PAGINATION_LIMIT', 10);
-	define('CONFIG_LOAD_DOC_LATTER', false); //all documents will be loaded up after the template has been loaded to the client
-
-	//General Option Declarations
-	//LANGAUGAE DECLARATIONNS
-	define('CONFIG_LANG_INDEX', 'language'); //the index in the session
-	define('CONFIG_LANG_DEFAULT', (CONFIG_QUERY_STRING_ENABLE && !empty($_GET['language']) && file_exists(DIR_LANG . secureFileName($_GET['language'] . '.php'))?secureFileName($_GET['language']):'en')); //change it to be your language file base name, such en
-?>

+ 0 - 11
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php

@@ -9,17 +9,6 @@
  */
 require_once dirname(__FILE__).DIRECTORY_SEPARATOR."config.php";
 
-/**
- * force to ensure existence of stripos
- */
-if (!function_exists("stripos")) {
-
-    function stripos($str, $needle, $offset = 0) {
-        return @strpos(strtolower($str), strtolower($needle), $offset);
-    }
-
-}
-
 /**
  * get the current Url but not the query string specified in $excls
  *

+ 14 - 11
main/inc/lib/fckeditor/fckeditor.php

@@ -162,12 +162,11 @@ class FCKeditor
      *
      * @return string
      */
-    public function CreateHtml() {
+    public function CreateHtml()
+    {
         // Adaptation for the Chamilo LMS
-
 		//@todo why the BasePath is relative ? we should use this constant WEB_PATH
         $this->BasePath = api_get_path(REL_PATH).'main/inc/lib/fckeditor/';
-        //$this->BasePath = api_get_path(WEB_PATH).'main/inc/lib/fckeditor/';
 
         $config = $this->get_custom_configuration();
         $this->read_configuration($config);
@@ -463,7 +462,14 @@ class FCKeditor
      * This method returns default configuration for document repository that is to be used by the editor.
      * @return array
      */
-    private function & get_repository_configuration() {
+    private function & get_repository_configuration()
+    {
+        // Disabling access for anonymous users.
+        $isAnonymous = api_is_anonymous();
+
+        if ($isAnonymous) {
+            return array();
+        }
 
         // Preliminary calculations for assembling required paths.
         $base_path = $this->BasePath;
@@ -479,6 +485,7 @@ class FCKeditor
         $script_path = api_get_path(WEB_PATH).$script_path;
 
         $use_advanced_filemanager = api_get_setting('advanced_filemanager') == 'true';
+
         // Let javascripts "know" which file manager has been chosen.
         $config['AdvancedFileManager'] = $use_advanced_filemanager;
 
@@ -493,16 +500,12 @@ class FCKeditor
                 } else {
                     // 1.2. Student
                     $current_session_id = api_get_session_id();
-                    if($current_session_id==0)
-                    {
-
+                    if($current_session_id==0) {
                         $config['CreateDocumentWebDir'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/shared_folder/sf_user_'.api_get_user_id().'/';
                         $config['CreateDocumentDir'] = $relative_path_prefix.'courses/'.api_get_course_path().'/document/shared_folder/sf_user_'.api_get_user_id().'/';
                         $config['BaseHref'] = $script_path;
-                    }
-                    else
-                    {
-                        $config['CreateDocumentWebDir'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document//shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().'/';
+                    } else {
+                        $config['CreateDocumentWebDir'] = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().'/';
                         $config['CreateDocumentDir'] = $relative_path_prefix.'courses/'.api_get_course_path().'/document/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().'/';
                         $config['BaseHref'] = $script_path;
                     }

+ 6 - 18
main/inc/lib/fckeditor/fcktemplates.xml.php

@@ -1,17 +1,5 @@
 <?php
-/**
- *	Chamilo LMS
- *
- *	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.
- */
+/* For licensing terms, see /license.txt */
 
 // Setting the encoding to UTF-8.
 header('Content-Type: text/xml; charset=utf-8');
@@ -204,16 +192,16 @@ function load_personal_templates($user_id = 0) {
 
     $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
     $table_document = Database::get_course_table(TABLE_DOCUMENT);
-    
+
     $course_id = api_get_course_int_id();
 
     // The sql statement for getting all the user defined templates
     $sql = "SELECT template.id, template.title, template.description, template.image, template.ref_doc, document.path
             FROM ".$table_template." template, ".$table_document." document
-            WHERE 
-                user_id='".Database::escape_string($user_id)."' AND 
+            WHERE
+                user_id='".Database::escape_string($user_id)."' AND
                 course_code='".Database::escape_string(api_get_course_id())."' AND
-                document.c_id = $course_id AND 
+                document.c_id = $course_id AND
                 document.id = template.ref_doc";
 
     $result_template = Database::query($sql);
@@ -252,7 +240,7 @@ function load_empty_template() {
         <![CDATA[
            <html>
            <head>
-               <meta charset="<?php echo api_get_system_encoding(); ?>" />        
+               <meta charset="<?php echo api_get_system_encoding(); ?>" />
            </head>
            <body  dir="<?php echo api_get_text_direction(); ?>">
            </body>

+ 1 - 19
main/inc/lib/fckeditor/myconfig.php

@@ -1,23 +1,5 @@
 <?php
-
-/*
- *	Chamilo LMS
- *
- *	Copyright (c) 2009-2011 Juan Carlos Raña
- *	Copyright (c) 2009-2011 Ivan Tcholakov
- *	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.
- */
-
+/* For licensing terms, see /license.txt */
 
 /*
  * Custom editor configuration settings, php-side.

+ 72 - 69
main/inc/lib/fckeditor/repository.php

@@ -1,101 +1,104 @@
 <?php
-/**
- *	Chamilo LMS
- *
- *	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.
- */
+/* For licensing terms, see /license.txt */
 
 /**
- * Aditional system config settings for document repositories, the Chamilo LMS
+ * Additional system config settings for document repositories, the Chamilo LMS
  * @author Juan Carlos Raña
  * @since 31/December/2008
  */
 
 require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 
+// Disabling access for anonymous users.
+api_block_anonymous_users();
+
 $permissions_for_new_directories = api_get_permissions_for_new_directories();
 $permissions_for_new_files = api_get_permissions_for_new_files();
 
+$userId = api_get_user_id();
+$sessionId = api_get_session_id();
+
 if (!empty($_course['path'])) {
-	require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-	require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
+    require_once api_get_path(LIBRARY_PATH).'document.lib.php';
+    require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 
     // Get the Chamilo session properties. Before ajaximagemanager!!!
-    $to_group_id = !empty($_SESSION['_gid']) ? $_SESSION['_gid'] : 0 ;
-	$group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
-	$is_user_in_group = GroupManager::is_user_in_group($_user['user_id'],$_SESSION['_gid']);
+    $groupId = api_get_group_id();
+    $group_properties = GroupManager::get_group_properties($groupId);
+    $is_user_in_group = GroupManager::is_user_in_group($userId, $groupId);
 }
 
-$my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'system');
+$sessionName = null;
+if (!empty($sessionId)) {
+    $sessionName = api_get_session_name($sessionId);
+}
+
+$my_path = UserManager::get_user_picture_path_by_id($userId, 'system');
 $user_folder = $my_path['dir'].'my_files/';
 
 // Sanity checks for Chamilo.
 
 // Creation of a user owned folder if it does not exist.
 if (!file_exists($user_folder)) {
-	// A recursive call of mkdir function.
-	@mkdir($user_folder, $permissions_for_new_directories, true);
+    // A recursive call of mkdir function.
+    @mkdir($user_folder, $permissions_for_new_directories, true);
 }
 
-// Creation of repository used by paltform administrators if it does not exist.
+// Creation of repository used by platform administrators if it does not exist.
 if (api_is_platform_admin()) {
-	$homepage_folder = api_get_path(SYS_PATH).'home/default_platform_document/';
-	if (!file_exists($homepage_folder)) {
-		@mkdir($homepage_folder, $permissions_for_new_directories);
-	}
+    $homepage_folder = api_get_path(SYS_PATH).'home/default_platform_document/';
+    if (!file_exists($homepage_folder)) {
+        @mkdir($homepage_folder, $permissions_for_new_directories);
+    }
 }
 
-
 // Create course shared folders
 if (api_is_in_course()) {
-	$course_dir      = $_course['path'].'/document';
-	$sys_course_path = api_get_path(SYS_COURSE_PATH);
-	$base_work_dir   = $sys_course_path.$course_dir;
-	$current_session_id = api_get_session_id();
-	$userinfo = Database::get_user_info_from_id(api_get_user_id());
+    $course_dir      = $_course['path'].'/document';
+    $sys_course_path = api_get_path(SYS_COURSE_PATH);
+    $base_work_dir   = $sys_course_path.$course_dir;
+    $userInfo = api_get_user_info();
 
-	if($current_session_id==0){
-		//Create shared folder. Necessary for courses recycled. Allways session_id should be zero. Allway should be created from a base course, never from a session.
-		if (!file_exists($base_work_dir.'/shared_folder')) {
-			$usf_dir_title = get_lang('SharedFolder');
-			$usf_dir_name = '/shared_folder';
-			$to_group_id = 0;
-			$visibility = 0;
-			create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-		}
-		// Create dynamic user shared folder
-		if (!file_exists($base_work_dir.'/shared_folder/sf_user_'.api_get_user_id())) {
-				$usf_dir_title = api_get_person_name($_user['firstName'], $_user['lastName']);
-				$usf_dir_name = '/shared_folder/sf_user_'.api_get_user_id();
-				$to_group_id = 0;
-				$visibility = 1;
-				create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-		}
-	}
-	else{
-			//Create shared folder session
-			if (!file_exists($base_work_dir.'/shared_folder_session_'.$current_session_id)) {
-				$usf_dir_title = get_lang('SharedFolder').' ('.api_get_session_name($current_session_id).')';
-				$usf_dir_name = '/shared_folder_session_'.$current_session_id;
-				$to_group_id = 0;
-				$visibility = 0;
-				create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-			}
-			//Create dynamic user shared folder into a shared folder session
-			if (!file_exists($base_work_dir.'/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id())) {
-				$usf_dir_title = api_get_person_name($_user['firstName'], $_user['lastName']).'('.api_get_session_name($current_session_id).')';
-				$usf_dir_name = '/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id();
-				$to_group_id = 0;
-				$visibility = 1;
-				create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-			}
-	}
+    if ($sessionId == 0) {
+        /* Create shared folder. Necessary for courses recycled.
+         Always session_id should be zero. Always should be created from a base course, never from a session.*/
+        if (!file_exists($base_work_dir.'/shared_folder')) {
+            $usf_dir_title = get_lang('SharedFolder');
+            $usf_dir_name = '/shared_folder';
+            $visibility = 0;
+            create_unexisting_directory($_course, $userId, $sessionId, 0, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        }
+        // Create dynamic user shared folder
+        if (!file_exists($base_work_dir.'/shared_folder/sf_user_'.$userId)) {
+            $usf_dir_title = $userInfo['complete_name'];
+            $usf_dir_name = '/shared_folder/sf_user_'.$userId;
+            $visibility = 1;
+            create_unexisting_directory($_course, $userId, $sessionId, 0, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        }
+    } else {
+        // Create shared folder session
+        if (!file_exists($base_work_dir.'/shared_folder_session_'.$sessionId)) {
+            $usf_dir_title = get_lang('SharedFolder').' ('.$sessionName.')';
+            $usf_dir_name = '/shared_folder_session_'.$sessionId;
+            $visibility = 0;
+            create_unexisting_directory($_course, $userId, $sessionId, 0, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
+        }
+        // Create dynamic user shared folder into a shared folder session.
+        if (!file_exists($base_work_dir.'/shared_folder_session_'.$sessionId.'/sf_user_'.$userId)) {
+            $usf_dir_title = $userInfo['complete_name'].' ('.$sessionName.')';
+            $usf_dir_name = '/shared_folder_session_'.$sessionId.'/sf_user_'.$userId;
+            $visibility = 1;
+            create_unexisting_directory(
+                $_course,
+                $userId,
+                $sessionId,
+                0,
+                $to_user_id,
+                $base_work_dir,
+                $usf_dir_name,
+                $usf_dir_title,
+                $visibility
+            );
+        }
+    }
 }

+ 9 - 33
main/inc/lib/fileDisplay.lib.php

@@ -9,30 +9,6 @@
 /**
  * Code
  */
-/*	GENERIC FUNCTIONS : FOR OLDER PHP VERSIONS */
-if ( ! function_exists('array_search') ) {
-    /**
-     * Searches haystack for needle and returns the key
-     * if it is found in the array, FALSE otherwise.
-     *
-     * Natively implemented in PHP since 4.0.5 version.
-     * This function is intended for previous version.
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - needle (mixed)
-     * @param  - haystack (array)
-     * @return - array key or FALSE
-     *
-     * @see    - http://www.php.net/array_search
-     */
-    function array_search($needle, $haystack)
-    {
-        while (list($key, $val) = each($haystack))
-            if ($val == $needle)
-                return $key;
-        return false;
-    }
-}
 
 /* FILE DISPLAY FUNCTIONS */
 /**
@@ -215,26 +191,26 @@ function get_total_folder_size($path, $can_see_invisible = false) {
     $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $table_document 	= Database::get_course_table(TABLE_DOCUMENT);
     $tool_document 		= TOOL_DOCUMENT;
-    
+
     $course_id 			= api_get_course_int_id();
     $session_id         = api_get_session_id();
     $session_condition  = api_get_session_condition($session_id, true, true, 'props.id_session');
 
     $visibility_rule = ' props.visibility ' . ($can_see_invisible ? '<> 2' : '= 1');
-    
+
     $sql = "SELECT SUM(table1.size) FROM (
                 SELECT size FROM $table_itemproperty AS props, $table_document AS docs
-                WHERE 	docs.c_id 	= $course_id AND                        
-                        docs.id 	= props.ref AND 
+                WHERE 	docs.c_id 	= $course_id AND
+                        docs.id 	= props.ref AND
                         docs.path LIKE '$path/%' AND
                         props.c_id 	= $course_id AND
-                        props.tool 	= '$tool_document' AND                            
-                        $visibility_rule  
-                        $session_condition 
+                        props.tool 	= '$tool_document' AND
+                        $visibility_rule
+                        $session_condition
                 GROUP BY ref
             ) as table1";
-    
-    $result = Database::query($sql);    
+
+    $result = Database::query($sql);
     if ($result && Database::num_rows($result) != 0) {
         $row = Database::fetch_row($result);
         return $row[0] == null ? 0 : $row[0];

+ 2 - 2
main/inc/lib/groupmanager.lib.php

@@ -1546,8 +1546,8 @@ class GroupManager
      * Is the user part of this group? This can be a tutor or a normal member
      * you should use this function if the access to a tool or functionality is restricted to the people who are actually in the group
      * before you had to check if the user was 1. a member of the group OR 2. a tutor of the group. This function combines both
-     * @param $user_id the id of the user
-     * @param $group_id the id of the group
+     * @param int $user_id the id of the user
+     * @param int $group_id the id of the group
      * @return boolean true/false
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
      */

+ 10 - 10
main/inc/lib/javascript/asciimath/ASCIIMathML.js

@@ -79,17 +79,16 @@ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 //var AMTcgiloc = "http://www.mathtran.org/cgi-bin/mathtran?D=1;tex=";
 //var AMTcgiloc = "http://www.mathtran.org/cgi-bin/mathtran?D=2;tex=";
 //
-//var AMTcgiloc = "http://chart.apis.google.com/chart?cht=tx&chl=";
-//var AMTcgiloc = "http://chart.apis.google.com/chart?cht=tx&chs=1x0&chl=";
+//var AMTcgiloc = "http://chart.googleapis.com/chart?cht=tx&chl=";
+//var AMTcgiloc = "http://chart.googleapis.com/chart?cht=tx&chs=1x0&chl=";
 //
 //var AMTcgiloc = "http://codecogs.izyba.com/gif.latex";
 //var AMTcgiloc = "http://codecogs.izyba.com/png.latex";
 //
-var AMTcgiloc = "http://chart.apis.google.com/chart?cht=tx&chs=1x0&chl=";
-//
+var AMTcgiloc = "//chart.googleapis.com/chart?cht=tx&chs=1x0&chl=";
+var AScgiloc = '//www.imathas.com/imathas/filter/graph/svgimg.php'; //path to CGI script
 
-var AScgiloc = 'http://www.imathas.com/imathas/filter/graph/svgimg.php'; //path to CGI script
-                        //for editor graphs IMG fallback
+//for editor graphs IMG fallback
 var mathcolor = "blue";        // change it to "" (to inherit) or another color
 // Modified by Ivan Tcholakov, 01-JUL-2010.
 //var mathfontsize = "1em";      // change to e.g. 1.2em for larger math
@@ -105,10 +104,11 @@ var checkForMathML = true;     // check if browser can display MathML
 var notifyIfNoMathML = false;   // display note at top if no MathML capability
 var alertIfNoMathML = false;   // show alert box if no MathML capability
 var translateOnLoad = true;    // set to false to do call translators from js
-//Modified by Ivan Tcholakov, 19-OCT-2010.
-//var translateLaTeX = false;     // false to preserve $..$, $$..$$
-var translateLaTeX = true;
-//
+// Originally modified by Ivan Tcholakov, 19-OCT-2010.
+//var translateLaTeX = true;
+// See #6355
+var translateLaTeX = false; // false to preserve $..$, $$..$$
+
 var translateLaTeXformatting = true; // false to preserve \emph,\begin{},\end{}
 var translateASCIIMath = true; // false to preserve `..`
 var translateASCIIsvg = true;  // false to preserve agraph.., \begin{graph}..

+ 21 - 5
main/inc/lib/main_api.lib.php

@@ -178,6 +178,7 @@ define('LOG_CAREER_CREATE',                     'career_created');
 define('LOG_CAREER_DELETE',                     'career_deleted');
 
 define('LOG_USER_PERSONAL_DOC_DELETED',         'user_doc_deleted');
+define('LOG_WIKI_ACCESS',                       'wiki_page_view');
 
 // event logs data types
 define('LOG_COURSE_CODE',                       'course_code');
@@ -196,6 +197,8 @@ define('LOG_GRADEBOOK_LOCKED',                   'gradebook_locked');
 define('LOG_GRADEBOOK_UNLOCKED',                 'gradebook_unlocked');
 define('LOG_GRADEBOOK_ID',                       'gradebook_id');
 
+define('LOG_WIKI_PAGE_ID',                       'wiki_page_id');
+
 define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
 
 //used when login_is_email setting is true
@@ -923,16 +926,17 @@ function api_protect_course_script($print_headers = false, $allow_session_admins
 
 /**
  * Function used to protect an admin script.
- * 
+ *
  * The function blocks access when the user has no platform admin rights with an error message printed on default output
  * @param bool Whether to allow session admins as well
  * @param bool Whether to allow HR directors as well
+ * @param string An optional message (already passed through get_lang)
  * @return bool True if user is allowed, false otherwise. The function also outputs an error message in case not allowed
  * @author Roan Embrechts (original author)
  */
-function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false) {
+function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null) {
     if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
-        api_not_allowed(true);
+        api_not_allowed(true, $message);
         return false;
     }
     return true;
@@ -1152,6 +1156,9 @@ function _api_format_user($user, $add_password = false) {
         $result['password'] = $user['password'];
     }
 
+    $result['creator_id'] = $user['creator_id'];
+    $result['registration_date'] = $user['registration_date'];
+
     return $result;
 }
 
@@ -2960,7 +2967,7 @@ function api_not_allowed($print_headers = false, $message = null) {
         exit;
     }
 
-    if (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE)) {
+    if (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE || $this_section == SECTION_PLATFORM_ADMIN)) {
 
         //only display form and return to the previous URL if there was a course ID included
         if ($user_id != 0 && !api_is_anonymous()) {
@@ -3767,7 +3774,7 @@ function api_max_sort_value($user_course_category, $user_id) {
  * @return boolean true or false
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  */
-function string_2_boolean($string) {
+function api_string_2_boolean($string) {
     if ($string == 'true') {
         return true;
     }
@@ -3777,6 +3784,7 @@ function string_2_boolean($string) {
     return false;
 }
 
+
 /**
  * Determines the number of plugins installed for a given location
  */
@@ -6778,3 +6786,11 @@ function api_can_login_as($loginAsUserId, $userId = null)
 
     return (api_is_platform_admin() OR (api_is_session_admin() && $user_info['status'] == 5) OR $isDrh());
 }
+
+/**
+ * @return bool
+ */
+function api_is_allowed_in_course()
+{
+    return Session::read('is_allowed_in_course');
+}

+ 83 - 42
main/inc/lib/message.lib.php

@@ -32,7 +32,10 @@ define('MESSAGE_STATUS_INVITATION_DENIED', '7');
  */
 class MessageManager
 {
-
+    /**
+     * @param int $current_user_id
+     * @return array
+     */
     public static function get_online_user_list($current_user_id)
     {
         //@todo this is a bad idea to parse all users online
@@ -50,7 +53,6 @@ class MessageManager
      */
     public static function display_success_message($uid)
     {
-        global $charset;
         if ($_SESSION['social_exist'] === true) {
             $redirect = "#remote-tab-2";
             if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
@@ -117,8 +119,6 @@ class MessageManager
     public static function get_number_of_messages($unread = false)
     {
         $table_message = Database::get_main_table(TABLE_MESSAGE);
-
-        $condition_msg_status = '';
         if ($unread) {
             $condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
         } else {
@@ -192,19 +192,30 @@ class MessageManager
     /**
      * Sends a message to a user/group
      *
-     * @param int 	  receiver user id
-     * @param string  subject
-     * @param string  content
-     * @param array   attachment files array($_FILES) (optional)
-     * @param array   comments about attachment files (optional)
-     * @param int     group id (optional)
-     * @param int     parent id (optional)
-     * @param int 	  message id for updating the message (optional)
-     * @param int    sender id (optional) the default value is the current user_id
+     * @param int 	  $receiver_user_id
+     * @param string  $subject
+     * @param string  $content
+     * @param array   $file_attachments files array($_FILES) (optional)
+     * @param array   $file_comments about attachment files (optional)
+     * @param int     $group_id id (optional)
+     * @param int     $parent_id id (optional)
+     * @param int 	  $edit_message_id id for updating the message (optional)
+     * @param int     $topic_id id (optional) the default value is the current user_id
+     * @param int     $sender_id
      * @return bool
      */
-    public static function send_message($receiver_user_id, $subject, $content, $file_attachments = array(), $file_comments = array(), $group_id = 0, $parent_id = 0, $edit_message_id = 0, $topic_id = 0, $sender_id = null)
-    {
+    public static function send_message(
+        $receiver_user_id,
+        $subject,
+        $content,
+        $file_attachments = array(),
+        $file_comments = array(),
+        $group_id = 0,
+        $parent_id = 0,
+        $edit_message_id = 0,
+        $topic_id = 0,
+        $sender_id = null
+    ) {
         $table_message = Database::get_main_table(TABLE_MESSAGE);
         $group_id = intval($group_id);
         $receiver_user_id = intval($receiver_user_id);
@@ -212,6 +223,15 @@ class MessageManager
         $edit_message_id = intval($edit_message_id);
         $topic_id = intval($topic_id);
 
+        if (!empty($receiver_user_id)) {
+            $receiverUserInfo = api_get_user_info($receiver_user_id);
+
+            // Disabling messages for inactive users.
+            if ($receiverUserInfo['active'] == 0) {
+                return false;
+            }
+        }
+
         if (empty($sender_id)) {
             $user_sender_id = api_get_user_id();
         } else {
@@ -225,7 +245,7 @@ class MessageManager
             }
         }
 
-        // validating fields
+        // Validating fields
         if (empty($subject) && empty($group_id)) {
             return get_lang('YouShouldWriteASubject');
         } else if ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) {
@@ -247,13 +267,14 @@ class MessageManager
             //message in inbox for user friend
             //@todo it's possible to edit a message? yes, only for groups
             if ($edit_message_id) {
-                $query = " UPDATE $table_message SET update_date = '".$now."', content = '$clean_content' WHERE id = '$edit_message_id' ";
-                $result = Database::query($query);
+                $query = " UPDATE $table_message SET update_date = '".$now."', content = '$clean_content'
+                           WHERE id = '$edit_message_id' ";
+                Database::query($query);
                 $inbox_last_id = $edit_message_id;
             } else {
-                $query = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content, group_id, parent_id, update_date ) ".
-                    "VALUES ('$user_sender_id', '$receiver_user_id', '1', '".$now."','$clean_subject','$clean_content','$group_id','$parent_id', '".$now."')";
-                $result = Database::query($query);
+                $query = "INSERT INTO $table_message (user_sender_id, user_receiver_id, msg_status, send_date, title, content, group_id, parent_id, update_date ) ".
+                         "VALUES ('$user_sender_id', '$receiver_user_id', '1', '".$now."','$clean_subject','$clean_content','$group_id','$parent_id', '".$now."')";
+                Database::query($query);
                 $inbox_last_id = Database::insert_id();
             }
 
@@ -287,7 +308,7 @@ class MessageManager
                 }
             }
 
-            //Load user settings
+            // Load user settings.
             $notification = new Notification();
             $sender_info = api_get_user_info($user_sender_id);
 
@@ -333,7 +354,6 @@ class MessageManager
      */
     public static function update_parent_ids_from_reply($parent_id, $receiver_user_id, $message_id)
     {
-
         $table_message = Database::get_main_table(TABLE_MESSAGE);
         $parent_id = intval($parent_id);
         $receiver_user_id = intval($receiver_user_id);
@@ -354,6 +374,11 @@ class MessageManager
         Database::query($sql_upd);
     }
 
+    /**
+     * @param int $user_receiver_id
+     * @param int $id
+     * @return bool|resource
+     */
     public static function delete_message_by_user_receiver($user_receiver_id, $id)
     {
         $table_message = Database::get_main_table(TABLE_MESSAGE);
@@ -370,7 +395,6 @@ class MessageManager
             $res = self::delete_message_attachment_file($id, $user_receiver_id);
             // delete message
             $query = "UPDATE $table_message SET msg_status=3 WHERE user_receiver_id=".$user_receiver_id." AND id=".$id;
-            //$query = "DELETE FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_receiver_id)." AND id=".$id;
             $result = Database::query($query);
             return $result;
         } else {
@@ -420,9 +444,14 @@ class MessageManager
      * @param  int		group id (optional)
      * @return void
      */
-    public static function save_message_attachment_file($file_attach, $file_comment, $message_id, $receiver_user_id = 0, $sender_user_id = 0, $group_id = 0)
-    {
-
+    public static function save_message_attachment_file(
+        $file_attach,
+        $file_comment,
+        $message_id,
+        $receiver_user_id = 0,
+        $sender_user_id = 0,
+        $group_id = 0
+    ) {
         $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 
         // Try to add an extension to the file if it hasn't one
@@ -479,14 +508,12 @@ class MessageManager
      */
     public static function delete_message_attachment_file($message_id, $message_uid, $group_id = 0)
     {
-
         $message_id = intval($message_id);
         $message_uid = intval($message_uid);
         $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 
         $sql = "SELECT * FROM $table_message_attach WHERE message_id = '$message_id'";
         $rs = Database::query($sql);
-        $new_paths = array();
         while ($row = Database::fetch_array($rs)) {
             $path = $row['path'];
             $attach_id = $row['id'];
@@ -502,7 +529,7 @@ class MessageManager
             if (is_file($path_message_attach.$path)) {
                 if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
                     $sql_upd = "UPDATE $table_message_attach set path='$new_path' WHERE id ='$attach_id'";
-                    $rs_upd = Database::query($sql_upd);
+                    Database::query($sql_upd);
                 }
             }
         }
@@ -520,9 +547,15 @@ class MessageManager
             return false;
         $table_message = Database::get_main_table(TABLE_MESSAGE);
         $query = "UPDATE $table_message SET msg_status = '0' WHERE msg_status<>4 AND user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
-        $result = Database::query($query);
+        Database::query($query);
     }
 
+    /**
+     * @param int $user_id
+     * @param int $message_id
+     * @param string $type
+     * @return bool
+     */
     public static function update_message_status($user_id, $message_id,$type)
     {
         $type = intval($type);
@@ -531,7 +564,7 @@ class MessageManager
         }
         $table_message = Database::get_main_table(TABLE_MESSAGE);
         $query = "UPDATE $table_message SET msg_status = '$type' WHERE user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
-        $result = Database::query($query);
+        Database::query($query);
     }
 
     /**
@@ -574,7 +607,8 @@ class MessageManager
 
     /**
      * get messages by group id
-     * @param  int      group id
+     * @param  int $group_id
+     * @param int $message_id
      * @return array
      */
     public static function get_messages_by_group_by_message($group_id, $message_id)
@@ -609,10 +643,10 @@ class MessageManager
      */
     public static function get_messages_by_parent($parent_id, $group_id = '', $offset = 0, $limit = 0)
     {
-        if ($parent_id != strval(intval($parent_id)))
+        if ($parent_id != strval(intval($parent_id))) {
             return false;
+        }
         $table_message = Database::get_main_table(TABLE_MESSAGE);
-        $current_uid = api_get_user_id();
         $parent_id = intval($parent_id);
 
         $condition_group_id = "";
@@ -627,7 +661,9 @@ class MessageManager
             $condition_limit = " LIMIT $offset,$limit ";
         }
 
-        $query = "SELECT * FROM $table_message WHERE parent_id='$parent_id' AND msg_status <> ".MESSAGE_STATUS_OUTBOX." $condition_group_id ORDER BY send_date DESC $condition_limit ";
+        $query = "SELECT * FROM $table_message
+                 WHERE parent_id='$parent_id' AND msg_status <> ".MESSAGE_STATUS_OUTBOX." $condition_group_id
+                 ORDER BY send_date DESC $condition_limit ";
         $rs = Database::query($query);
         $data = array();
         if (Database::num_rows($rs) > 0) {
@@ -841,8 +877,6 @@ class MessageManager
      */
     public static function show_message_box_sent()
     {
-        global $charset;
-
         $table_message = Database::get_main_table(TABLE_MESSAGE);
         $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 
@@ -1227,7 +1261,6 @@ class MessageManager
      */
     public static function get_links_message_attachment_files($message_id, $type = '')
     {
-
         $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
         $message_id = intval($message_id);
 
@@ -1271,7 +1304,12 @@ class MessageManager
         return $item;
     }
 
-    static function generate_message_form($id, $params = array())
+    /**
+     * @param $id
+     * @param array $params
+     * @return string
+     */
+    public static function generate_message_form($id, $params = array())
     {
         $form = new FormValidator('send_message', null, 'post', null, array('id' => $id.'_form', 'class' => 'form-vertical'));
         $form->addElement('text', 'subject', get_lang('Subject'), array('id' => 'subject_id', 'class' => 'span5'));
@@ -1280,7 +1318,7 @@ class MessageManager
         return $div;
     }
 
-    static function generate_invitation_form($id, $params = array())
+    public static function generate_invitation_form($id, $params = array())
     {
         $form = new FormValidator('send_invitation', null, 'post', null, array('id' => $id.'_form', 'class' => 'form-vertical'));
         //$form->addElement('text', 'subject', get_lang('Subject'), array('id' => 'subject_id'));
@@ -1291,7 +1329,7 @@ class MessageManager
 
     //@todo this functions should be in the message class
 
-    static function inbox_display()
+    public static function inbox_display()
     {
         $success = get_lang('SelectedMessagesDeleted');
         $success_read = get_lang('SelectedMessagesRead');
@@ -1348,6 +1386,9 @@ class MessageManager
         return $html;
     }
 
+    /**
+     * @return string
+     */
     static function outbox_display()
     {
         $social_link = false;

+ 2 - 2
main/inc/lib/model.lib.php

@@ -9,8 +9,8 @@
  * Class
  * @package chamilo.library
  */
-class Model {
-
+class Model
+{
     public $table;
     public $columns;
     public $required;

+ 15 - 11
main/inc/lib/notebook.lib.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
@@ -8,10 +7,11 @@
  * 	@author Carlos Vargas <litox84@gmail.com>, move code of main/notebook up here
  * 	@package chamilo.library
  */
-class NotebookManager {
+class NotebookManager
+{
 
-    private function __construct() {
-        
+    private function __construct()
+    {
     }
 
     /**
@@ -22,7 +22,8 @@ class NotebookManager {
      * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
      * @version januari 2009, dokeos 1.8.6
      */
-    static function javascript_notebook() {
+    static function javascript_notebook()
+    {
         return "<script>
 				function confirmation (name)
 				{
@@ -44,7 +45,8 @@ class NotebookManager {
      * @version januari 2009, dokeos 1.8.6
      *
      */
-    static function save_note($values) {
+    static function save_note($values)
+    {
         if (!is_array($values) or empty($values['note_title'])) {
             return false;
         }
@@ -132,7 +134,8 @@ class NotebookManager {
         }
     }
 
-    static function delete_note($notebook_id) {
+    static function delete_note($notebook_id)
+    {
         if (empty($notebook_id) or $notebook_id != strval(intval($notebook_id))) {
             return false;
         }
@@ -152,7 +155,8 @@ class NotebookManager {
         return true;
     }
 
-    static function display_notes() {
+    static function display_notes()
+    {
 
         global $_user;
         if (!$_GET['direction']) {
@@ -165,7 +169,7 @@ class NotebookManager {
             $sort_direction = 'DESC';
             $link_sort_direction = 'ASC';
         }
-        
+
         // action links
         echo '<div class="actions">';
         if (!api_is_anonymous()) {
@@ -223,6 +227,6 @@ class NotebookManager {
             echo '<a href="' . api_get_self() . '?action=editnote&amp;notebook_id=' . $row['notebook_id'] . '">' . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . '</a>';
             echo '<a href="' . api_get_self() . '?action=deletenote&amp;notebook_id=' . $row['notebook_id'] . '" onclick="return confirmation(\'' . $row['title'] . '\');">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
             echo '</div>';
-        }        
+        }
     }
-}
+}

+ 22 - 11
main/inc/lib/notification.lib.php

@@ -47,6 +47,9 @@ class Notification extends Model
     const NOTIFICATION_TYPE_INVITATION = 2;
     const NOTIFICATION_TYPE_GROUP = 3;
 
+    /**
+     *
+     */
     public function __construct()
     {
         $this->table = Database::get_main_table(TABLE_NOTIFICATION);
@@ -63,16 +66,23 @@ class Notification extends Model
 
     /**
      *  Send the notifications
-     *  @param int notification frecuency
+     *  @param int notification frequency
      */
-    public function send($frec = 8)
+    public function send($frequency = 8)
     {
-        $notifications = $this->find('all', array('where' => array('sent_at IS NULL AND send_freq = ?' => $frec)));
+        $notifications = $this->find('all', array('where' => array('sent_at IS NULL AND send_freq = ?' => $frequency)));
 
         if (!empty($notifications)) {
             foreach ($notifications as $item_to_send) {
                 // Sending email
-                api_mail_html($item_to_send['dest_mail'], $item_to_send['dest_mail'], Security::filter_terms($item_to_send['title']), Security::filter_terms($item_to_send['content']), $this->admin_name, $this->admin_email);
+                api_mail_html(
+                    $item_to_send['dest_mail'],
+                    $item_to_send['dest_mail'],
+                    Security::filter_terms($item_to_send['title']),
+                    Security::filter_terms($item_to_send['content']),
+                    $this->admin_name,
+                    $this->admin_email
+                );
                 if ($this->debug) {
                     error_log('Sending message to: '.$item_to_send['dest_mail']);
                 }
@@ -104,15 +114,15 @@ class Notification extends Model
         $avoid_my_self = false;
 
         switch ($this->type) {
-            case self::NOTIFICATION_TYPE_MESSAGE;
+            case self::NOTIFICATION_TYPE_MESSAGE:
                 $setting_to_check = 'mail_notify_message';
                 $default_status = self::NOTIFY_MESSAGE_AT_ONCE;
                 break;
-            case self::NOTIFICATION_TYPE_INVITATION;
+            case self::NOTIFICATION_TYPE_INVITATION:
                 $setting_to_check = 'mail_notify_invitation';
                 $default_status = self::NOTIFY_INVITATION_AT_ONCE;
                 break;
-            case self::NOTIFICATION_TYPE_GROUP;
+            case self::NOTIFICATION_TYPE_GROUP:
                 $setting_to_check = 'mail_notify_group_message';
                 $default_status = self::NOTIFY_GROUP_AT_ONCE;
                 $avoid_my_self = true;
@@ -130,7 +140,7 @@ class Notification extends Model
                 }
                 $user_info = api_get_user_info($user_id);
 
-                //Extra field was deleted or removed? Use the default status
+                // Extra field was deleted or removed? Use the default status.
                 if (empty($setting_info)) {
                     $user_setting = $default_status;
                 } else {
@@ -162,7 +172,7 @@ class Notification extends Model
                             }
                         }
                         $params['sent_at'] = api_get_utc_datetime();
-                    //Saving the notification to be sent some day
+                        // Saving the notification to be sent some day.
                     default:
                         $params['dest_user_id'] = $user_id;
                         $params['dest_mail'] = $user_info['mail'];
@@ -178,8 +188,9 @@ class Notification extends Model
 
     /**
      * Formats the content in order to add the welcome message, the notification preference, etc
-     * @param	string 	the content
-     * @param	array	result of api_get_user_info() or GroupPortalManager:get_group_data()
+     * @param   string 	the content
+     * @param   array	result of api_get_user_info() or GroupPortalManager:get_group_data()
+     * @return string
      * */
     public function format_content($content, $sender_info)
     {

+ 96 - 87
main/inc/lib/promotion.lib.php

@@ -13,28 +13,29 @@ require_once 'career.lib.php';
 require_once 'fckeditor/fckeditor.php';
 
 define ('PROMOTION_STATUS_ACTIVE',  1);
-define ('PROMOTION_STATUS_INACTIVE',0);   
+define ('PROMOTION_STATUS_INACTIVE', 0);
 /**
  * @package chamilo.library
  */
-class Promotion extends Model {
-    
-    var $table;
-    var $columns = array('id','name','description','career_id','status','created_at','updated_at');
-    
-	public function __construct() {
+class Promotion extends Model
+{
+    public $table;
+    public $columns = array('id','name','description','career_id','status','created_at','updated_at');
+
+	public function __construct()
+    {
         $this->table =  Database::get_main_table(TABLE_PROMOTION);
 	}
-    
+
      /**
      * Get the count of elements
      */
-    public function get_count() {        
-        $row = Database::select('count(*) as count', $this->table, array(),'first');
+    public function get_count()
+    {
+        $row = Database::select('count(*) as count', $this->table, array(), 'first');
         return $row['count'];
     }
-    
-	
+
 	/**
 	* Copies the promotion to a new one
 	* @param   integer     Promotion ID
@@ -42,54 +43,55 @@ class Promotion extends Model {
 	* @param   boolean     Whether or not to copy the sessions inside
 	* @return  integer     New promotion ID on success, false on failure
 	*/
-	public function copy($id, $career_id = null, $copy_sessions = false) {
+	public function copy($id, $career_id = null, $copy_sessions = false)
+    {
 		$pid = false;
-		$promotion = $this->get($id);		
-		if (!empty($promotion)) {
-			$new = array();
-			foreach ($promotion as $key => $val) {
-				switch ($key) {
-					case 'id':
-					case 'updated_at':
-						break;
-					case 'name':
-						$val .= ' '.get_lang('CopyLabelSuffix');
-						$new[$key] = $val;
-						break;
-					case 'created_at':
-						$val = api_get_utc_datetime();
-						$new[$key] = $val;
-						break;
-					case 'career_id':
-						if (!empty($career_id)) {
-							$val = (int)$career_id;
-						}
-						$new[$key] = $val;
-					default:
-						$new[$key] = $val;
-					break;
-				}
-			}
-			
+		$promotion = $this->get($id);
+        if (!empty($promotion)) {
+            $new = array();
+            foreach ($promotion as $key => $val) {
+                switch ($key) {
+                    case 'id':
+                    case 'updated_at':
+                        break;
+                    case 'name':
+                        $val .= ' '.get_lang('CopyLabelSuffix');
+                        $new[$key] = $val;
+                        break;
+                    case 'created_at':
+                        $val = api_get_utc_datetime();
+                        $new[$key] = $val;
+                        break;
+                    case 'career_id':
+                        if (!empty($career_id)) {
+                            $val = (int)$career_id;
+                        }
+                        $new[$key] = $val;
+                    default:
+                        $new[$key] = $val;
+                    break;
+                }
+            }
+
 			if ($copy_sessions) {
 				/**
 				 * When copying a session we do:
 				 * 1. Copy a new session from the source
 				 * 2. Copy all courses from the session (no user data, no user list)
 				 * 3. Create the promotion
-				 */				
+				 */
 				$session_list   = SessionManager::get_all_sessions_by_promotion($id);
-				
+
 				if (!empty($session_list)) {
-					$pid = $this->save($new);				
+					$pid = $this->save($new);
 					if (!empty($pid)) {
                         $new_session_list = array();
-                        
+
 						foreach($session_list as $item) {
-							$sid = SessionManager::copy_session($item['id'], true, false, false, true);						
+							$sid = SessionManager::copy_session($item['id'], true, false, false, true);
                             $new_session_list[] = $sid;
 						}
-                        
+
                         if (!empty($new_session_list)) {
                             SessionManager::suscribe_sessions_to_promotion($pid, $new_session_list);
                         }
@@ -101,20 +103,26 @@ class Promotion extends Model {
 		}
 		return $pid;
 	}
-	
+
     /**
      * Gets all promotions by career id
      * @param   int     career id
+     * @param bool $order
      * @return  array   results
      */
-    public function get_all_promotions_by_career_id($career_id, $order = false) {        
+    public function get_all_promotions_by_career_id($career_id, $order = false)
+    {
         return Database::select('*', $this->table, array('where'=>array('career_id = ?'=>$career_id),'order' =>$order));
     }
-    
-    public function get_status_list() {
+
+    /**
+     * @return array
+     */
+    public function get_status_list()
+    {
     	return array(PROMOTION_STATUS_ACTIVE => get_lang('Active'), PROMOTION_STATUS_INACTIVE => get_lang('Inactive'));
-    } 
-   
+    }
+
     /**
      * Displays the title + grid
      * @return  string  html code
@@ -123,44 +131,45 @@ class Promotion extends Model {
 		// action links
 		echo '<div class="actions" style="margin-bottom:20px">';
         echo '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';
-		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_promotion.png',get_lang('Add'),'','32').'</a>';			
-		echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('new_session.png',get_lang('AddSession'),'','32').'</a>';			
+		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_promotion.png',get_lang('Add'),'','32').'</a>';
+		echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('new_session.png',get_lang('AddSession'),'','32').'</a>';
 		echo '</div>';
-        echo Display::grid_html('promotions');  
+        echo Display::grid_html('promotions');
 	}
-    
+
     /**
      * Update all session status by promotion
      * @param   int     promotion id
      * @param   int     status (1, 0)
     */
-    public function update_all_sessions_status_by_promotion_id($promotion_id, $status) {
-        $session_list   = SessionManager::get_all_sessions_by_promotion($promotion_id);    
+    public function update_all_sessions_status_by_promotion_id($promotion_id, $status)
+    {
+        $session_list   = SessionManager::get_all_sessions_by_promotion($promotion_id);
         if (!empty($session_list)) {
             foreach($session_list  as $item) {
-                SessionManager::set_session_status($item['id'], $status);            
+                SessionManager::set_session_status($item['id'], $status);
             }
         }
     }
-    
-   
+
+
     /**
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  header name
-     * @return  obj     form validator obj 
+     * @return  obj     form validator obj
      */
-     
-    function return_form($url, $action = 'add') {
-    	
+
+    function return_form($url, $action = 'add')
+    {
 		$oFCKeditor = new FCKeditor('description') ;
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Height		= '200';
 		$oFCKeditor->Value		= '';
-		$oFCKeditor->CreateHtml();		
-		
+		$oFCKeditor->CreateHtml();
+
 		$form = new FormValidator('promotion', 'post', $url);
         // Settting the form elements
         $header = get_lang('Add');
@@ -168,31 +177,31 @@ class Promotion extends Model {
         	$header = get_lang('Modify');
         }
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
-        
+
         $form->addElement('header', '', $header);
         $form->addElement('hidden', 'id', $id);
-        $form->addElement('text', 'name', get_lang('Name'), array('size' => '70','id' => 'name'));        
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));       
+        $form->addElement('text', 'name', get_lang('Name'), array('size' => '70','id' => 'name'));
+        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
         $career = new Career();
         $careers = $career->get_all();
-        $career_list = array();    
-        foreach($careers as $item) {        
+        $career_list = array();
+        foreach($careers as $item) {
             $career_list[$item['id']] = $item['name'];
         }
         $form->addElement('select', 'career_id', get_lang('Career'), $career_list);
-        
-        $status_list = $this->get_status_list();         
+
+        $status_list = $this->get_status_list();
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         if ($action == 'edit') {
             $form->addElement('text', 'created_at', get_lang('CreatedAt'));
             $form->freeze('created_at');
-        }         
+        }
       	if ($action == 'edit') {
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         } else {
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         }
-    
+
         // Setting the defaults
         $defaults = $this->get($id);
         if (!empty($defaults['created_at'])) {
@@ -200,31 +209,31 @@ class Promotion extends Model {
         }
         if (!empty($defaults['updated_at'])) {
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
-        }            
+        }
         $form->setDefaults($defaults);
-    
+
         // Setting the rules
         $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-        
+
         return $form;
     }
-    
-    public function save($params, $show_query = false) {
+
+    public function save($params, $show_query = false)
+    {
     	$id = parent::save($params, $show_query);
     	if (!empty($id)) {
     		event_system(LOG_PROMOTION_CREATE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());
     	}
-    	return $id;	
+    	return $id;
     }
-    
-    public function delete($id) {
+
+    public function delete($id)
+    {
     	if (parent::delete($id)) {
            SessionManager::clear_session_ref_promotion($id);
     	   event_system(LOG_PROMOTION_DELETE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());
         } else {
             return false;
-        }   	
+        }
     }
-   
-    
 }

File diff suppressed because it is too large
+ 777 - 82
main/inc/lib/sessionmanager.lib.php


+ 18 - 0
main/inc/lib/text.lib.php

@@ -764,4 +764,22 @@ function return_datetime_from_array($array) {
         $datetime = $year.'-'.$month.'-'.$day.' '.$hours.':'.$minutes.':'.$seconds;
     }
     return $datetime;
+}
+
+/**
+ * Converts an string CLEANYO[admin][amann,acostea]
+ * into an array:
+ *
+ * array(
+ *  CLEANYO
+ *  admin
+ *  amann,acostea
+ * )
+ *
+ * @param $array
+ * @return array
+ */
+function bracketsToArray($array)
+{
+    return preg_split('/[\[\]]+/', $array, -1, PREG_SPLIT_NO_EMPTY);
 }

+ 96 - 69
main/inc/lib/timeline.lib.php

@@ -10,85 +10,97 @@
  */
 define('TIMELINE_STATUS_ACTIVE', '1');
 define('TIMELINE_STATUS_INACTIVE', '2');
+
 /**
  * Timeline model class definition
  */
-class Timeline extends Model {    
-    var $table;
-    var $columns = array('headline', 'type', 'start_date', 'end_date', 'text', 'media', 'media_credit', 'media_caption', 'title_slide', 'parent_id', 'status','c_id');
-    var $is_course_model = true;
-    
-	public function __construct() {
+class Timeline extends Model
+{
+    public $table;
+    public $columns = array('headline', 'type', 'start_date', 'end_date', 'text', 'media', 'media_credit', 'media_caption', 'title_slide', 'parent_id', 'status','c_id');
+    public $is_course_model = true;
+
+	public function __construct()
+    {
         $this->table =  Database::get_course_table(TABLE_TIMELINE);
-	}    
-    
+	}
+
     /**
      * Get the count of elements
      */
-    public function get_count() {        
+    public function get_count()
+    {
         $course_id = api_get_course_int_id();
         $row = Database::select('count(*) as count', $this->table, array('where' => array('parent_id = ? AND c_id = ?' => array('0', $course_id))), 'first');
         return $row['count'];
-    }     
-    
-    public function get_all($where_conditions = array()) {        
+    }
+
+    /**
+     * @param array $where_conditions
+     * @return array
+     */
+    public function get_all($where_conditions = array())
+    {
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'headline ASC'));
     }
-    
+
     /**
      * Displays the title + grid
      */
-	public function listing() {
+	public function listing()
+    {
 		// action links
-		$html .= '<div class="actions">';
-        //$html .= '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';     	
-		$html .= '<a href="'.api_get_self().'?action=add">'.Display::return_icon('add.png', get_lang('Add'),'','32').'</a>';        				
+		$html = '<div class="actions">';
+        //$html .= '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';
+		$html .= '<a href="'.api_get_self().'?action=add">'.Display::return_icon('add.png', get_lang('Add'),'','32').'</a>';
 		$html .= '</div>';
-        $html .= Display::grid_html('timelines');  
+        $html .= Display::grid_html('timelines');
         return $html;
 	}
-    
-    public function get_status_list() {
+
+    public function get_status_list()
+    {
         return array(TIMELINE_STATUS_ACTIVE => get_lang('Active'), TIMELINE_STATUS_INACTIVE => get_lang('Inactive'));
     }
-    
+
     /**
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  action add, edit
-     * @return  obj     form validator obj 
+     * @return  obj     form validator obj
      */
-    public function return_form($url, $action) {
+    public function return_form($url, $action)
+    {
         $form = new FormValidator('timeline', 'post', $url);
         // Setting the form elements
-        $header = get_lang('Add');        
+        $header = get_lang('Add');
         if ($action == 'edit') {
             $header = get_lang('Modify');
-        }        
+        }
         $form->addElement('header', $header);
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $form->addElement('hidden', 'id', $id);
-        
+
         $form->addElement('text', 'headline', get_lang('Name'), array('size' => '70'));
-        //$form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));	   
-	    $status_list = $this->get_status_list();         
+        //$form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+	    $status_list = $this->get_status_list();
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         if ($action == 'edit') {
             //$form->addElement('text', 'created_at', get_lang('CreatedAt'));
             //$form->freeze('created_at');
-        }                
+        }
         if ($action == 'edit') {
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         } else {
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         }
-        
+
         $form->addRule('headline', get_lang('ThisFieldIsRequired'), 'required');
-    
+
         // Setting the defaults
         $defaults = $this->get($id);
-        
+
         /*if (!empty($defaults['created_at'])) {
         	$defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
         }
@@ -96,27 +108,33 @@ class Timeline extends Model {
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
         }*/
         $form->setDefaults($defaults);
-    
+
         // Setting the rules
-        $form->addRule('headline', get_lang('ThisFieldIsRequired'), 'required');               
-		return $form;                                
+        $form->addRule('headline', get_lang('ThisFieldIsRequired'), 'required');
+		return $form;
     }
-    
-    public function return_item_form($url, $action) {	
-        
+
+    /**
+     * @param $url
+     * @param $action
+     * @return FormValidator
+     */
+    public function return_item_form($url, $action)
+    {
+
         $form = new FormValidator('item_form', 'post', $url);
         // Settting the form elements
-        $header = get_lang('Add');        
+        $header = get_lang('Add');
         if ($action == 'edit') {
             $header = get_lang('Modify');
-        }        
+        }
         $form->addElement('header', $header);
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $parent_id = isset($_GET['parent_id']) ? intval($_GET['parent_id']) : '';
-        $form->addElement('hidden', 'parent_id', $parent_id);      
+        $form->addElement('hidden', 'parent_id', $parent_id);
         $form->addElement('hidden', 'id', $id);
         $form->addElement('text', 'headline', get_lang('Name'), array('class' => 'span4'));
-        
+
         //@todo fix this
         $form->addElement('text', 'start_date', get_lang('StartDate'), array('size' => '70'));
         $form->addElement('text', 'end_date', get_lang('EndDate'), array('size' => '70'));
@@ -125,13 +143,13 @@ class Timeline extends Model {
         $form->addElement('text', 'media_caption', get_lang('TimelineItemMediaCaption'), array('size' => '70'));
         $form->addElement('text', 'media_credit', get_lang('TimelineItemMediaCredit'), array('size' => '70'));
         $form->addElement('text', 'title_slide', get_lang('TimelineItemTitleSlide'), array('size' => '70'));
-        
+
         $form->addRule('headline', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('start_date', get_lang('ThisFieldIsRequired'), 'required');
-       
-        
-        //$form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));	   
-	    
+
+
+        //$form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+
         if ($action == 'edit') {
             // Setting the defaults
             $defaults = $this->get($id);
@@ -139,7 +157,7 @@ class Timeline extends Model {
         } else {
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         }
-        
+
         /*if (!empty($defaults['created_at'])) {
         	$defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
         }
@@ -147,22 +165,31 @@ class Timeline extends Model {
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
         }*/
         $form->setDefaults($defaults);
-    
+
         // Setting the rules
-        $form->addRule('headline', get_lang('ThisFieldIsRequired'), 'required');               
-		return $form; 
-        
+        $form->addRule('headline', get_lang('ThisFieldIsRequired'), 'required');
+		return $form;
+
     }
-    
-    public function save_item($params) {
-        $params['c_id'] = api_get_course_int_id();        
+
+    /**
+     * @param array $params
+     * @return bool
+     */
+    public function save_item($params)
+    {
+        $params['c_id'] = api_get_course_int_id();
 	    $id = parent::save($params);
 	    if (!empty($id)) {
 	    	//event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
    		}
-   		return $id;   
+   		return $id;
     }
-    
+
+    /**
+     * @param array $params
+     * @return bool
+     */
     public function save($params) {
         $params['c_id'] = api_get_course_int_id();
         $params['parent_id'] = '0';
@@ -173,25 +200,25 @@ class Timeline extends Model {
    		}
    		return $id;
     }
-    
+
     public function delete($id) {
 	    parent::delete($id);
 	    //event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
     }
-    
+
     public function get_url($id) {
         return api_get_path(WEB_AJAX_PATH).'timeline.ajax.php?a=get_timeline_content&id='.intval($id);
     }
-    
+
     public function get_timeline_content($id) {
         $timeline = array();
         $course_id = api_get_course_int_id();
-        $timeline['timeline'] = $this->process_item($this->get($id));        
-        $items = $this->process_items($this->get_all(array('parent_id = ? AND c_id = ? ' =>array($id, $course_id))));                
+        $timeline['timeline'] = $this->process_item($this->get($id));
+        $items = $this->process_items($this->get_all(array('parent_id = ? AND c_id = ? ' =>array($id, $course_id))));
         $timeline['timeline']['date'] = $items;
         return $timeline;
     }
-    
+
     function process_items($items) {
         foreach ($items as &$item) {
             $item = $this->process_item($item);
@@ -208,15 +235,15 @@ class Timeline extends Model {
         if (!empty($item['end_date'])) {
             $item['endDate'] = $item['end_date'];
         } else {
-            unset($item['endDate']);            
+            unset($item['endDate']);
         }
         unset($item['end_date']);
         // Assets
         $item['asset'] = array( 'media'     => $item['media'],
-                                'credit'    => $item['media_credit'],  
-                                'caption'   => $item['media_caption'],  
+                                'credit'    => $item['media_credit'],
+                                'caption'   => $item['media_caption'],
          );
-        
+
         //Cleaning items
         unset($item['id']);
         if (empty($item['type'])) {
@@ -227,8 +254,8 @@ class Timeline extends Model {
         unset($item['media_caption']);
         unset($item['status']);
         unset($item['title_slide']);
-        unset($item['parent_id']);        
+        unset($item['parent_id']);
         unset($item['c_id']);
-        return $item;        
+        return $item;
     }
 }

+ 50 - 32
main/inc/lib/tracking.lib.php

@@ -1312,7 +1312,7 @@ class Tracking {
      * @param    int        Coach id
      * @return    array    Sessions list
      */
-    public static function get_sessions_coached_by_user($coach_id)
+    public static function get_sessions_coached_by_user($coach_id, $start = 0, $limit = 0, $getCount = false)
     {
         // table definition
         $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
@@ -1320,52 +1320,70 @@ class Tracking {
 
         $coach_id = intval($coach_id);
 
-        // session where we are general coach
-        $sql = 'SELECT DISTINCT id, name, date_start, date_end
-                    FROM ' . $tbl_session . '
-                    WHERE id_coach=' . $coach_id;
+        $select = " SELECT * FROM ";
 
-        if (api_is_multiple_url_enabled()) {
-            $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 DISTINCT id, name, date_start, date_end
-                    FROM ' . $tbl_session . ' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
-                    ON (session.id = session_rel_url.session_id)
-                    WHERE id_coach=' . $coach_id.' AND access_url_id = '.$access_url_id;
-            }
+        if ($getCount) {
+            $select = " SELECT count(DISTINCT id) as count FROM ";
         }
 
-        $rs = Database::query($sql);
-        while ($row = Database::fetch_array($rs)) {
-            $a_sessions[$row["id"]] = $row;
+        $limitCondition = null;
+        if (!empty($start) && !empty($limit)) {
+            $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
         }
 
-        // session where we are coach of a course
-        $sql = 'SELECT DISTINCT session.id, session.name, session.date_start, session.date_end
-                    FROM ' . $tbl_session . ' as session
-                    INNER JOIN ' . $tbl_session_course_user . ' as session_course_user
+        // session where we are general coach
+        $sql = " $select
+
+                (SELECT DISTINCT id, name, date_start, date_end
+                    FROM $tbl_session
+                    WHERE id_coach = $coach_id
+                UNION
+
+                SELECT DISTINCT session.id, session.name, session.date_start, session.date_end
+                    FROM $tbl_session as session
+                    INNER JOIN $tbl_session_course_user  as session_course_user
                         ON session.id = session_course_user.id_session
-                        AND session_course_user.id_user=' . $coach_id.' AND session_course_user.status=2';
+                        AND session_course_user.id_user= $coach_id AND session_course_user.status=2
+                )
+                as sessions $limitCondition
+                ";
 
         if (api_is_multiple_url_enabled()) {
             $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 DISTINCT session.id, session.name, session.date_start, session.date_end
-                    FROM ' . $tbl_session . ' as session
-                    INNER JOIN ' . $tbl_session_course_user . ' as session_course_user
-                        ON session.id = session_course_user.id_session AND session_course_user.id_user=' . $coach_id.' AND session_course_user.status=2
-                    INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
-                    ON (session.id = session_rel_url.session_id)
-                    WHERE access_url_id = '.$access_url_id;
+                $sql = "
+                    $select
+                    (
+                        SELECT DISTINCT id, name, date_start, date_end
+                        FROM $tbl_session session INNER JOIN $tbl_session_rel_access_url session_rel_url
+                        ON (session.id = session_rel_url.session_id)
+                        WHERE id_coach = $coach_id AND access_url_id = $access_url_id
+
+                        UNION
+
+                        SELECT DISTINCT session.id, session.name, session.date_start, session.date_end
+                        FROM $tbl_session as session
+                        INNER JOIN $tbl_session_course_user as session_course_user
+                            ON session.id = session_course_user.id_session AND session_course_user.id_user= $coach_id AND session_course_user.status=2
+                        INNER JOIN $tbl_session_rel_access_url session_rel_url
+                        ON (session.id = session_rel_url.session_id)
+                        WHERE access_url_id = $access_url_id
+                    ) as sessions $limitCondition
+                    ";
             }
         }
 
         $rs = Database::query($sql);
+        if ($getCount) {
+            $row = Database::fetch_array($rs);
+            return $row['count'];
+        }
+
         while ($row = Database::fetch_array($rs)) {
             $a_sessions[$row["id"]] = $row;
         }
+
         if (is_array($a_sessions)) {
             foreach ($a_sessions as & $session) {
                 if ($session['date_start'] == '0000-00-00') {
@@ -2035,7 +2053,7 @@ class Tracking {
      * Get total clicks by session
      * @param    int        Session id (optional), if param $session_id is null(default) it'll return results including sessions, 0 = session is not filtered
      * @return    array     data
-     * @todo    implement total click by $course_id 
+     * @todo    implement total click by $course_id
      */
     public static function get_total_clicks_by_session($session_id = null) {
         $tables = array(
@@ -2057,12 +2075,12 @@ class Tracking {
             #TABLE_STATISTIC_TRACK_E_OPEN,
             );
 
-        if (isset($_GET['session_id']) && !empty($_GET['session_id'])) 
+        if (isset($_GET['session_id']) && !empty($_GET['session_id']))
         {
             $sessionId = intval($_GET['session_id']);
         }
 
-        foreach ($tables as $tableName => $fields) 
+        foreach ($tables as $tableName => $fields)
         {
             $sql = sprintf('SELECT %s as user, count(*) as total FROM %s WHERE %s = %s GROUP BY %s', $fields[1], $tableName, $fields[0], $sessionId, $fields[1]);
             $rs = Database::query($sql);

+ 29 - 10
main/inc/lib/usermanager.lib.php

@@ -2256,20 +2256,40 @@ class UserManager
         }
 
         // Get the list of sessions where the user is subscribed
+        // This is divided into two different queries
+        $sessions = array();
         $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
                         FROM $tbl_session_user, $tbl_session
                         WHERE (
                             id_session = id AND
                             id_user = $user_id AND
                             relation_type <> ".SESSION_RELATION_TYPE_RRHH."
-                        ) OR (
+                        )
+                        $coachCourseConditions
+                        ORDER BY date_start, date_end, name";
+
+        $result = Database::query($sessions_sql);
+        if (Database::num_rows($result)>0) {
+            while ($row = Database::fetch_assoc($result)) {
+                $sessions[$row['id']] = $row;
+            }
+        }
+        $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
+                        FROM $tbl_session_user, $tbl_session
+                        WHERE (
                             id_coach = $user_id
                         )
                         $coachCourseConditions
                         ORDER BY date_start, date_end, name";
 
         $result = Database::query($sessions_sql);
-        $sessions = Database::store_result($result, 'ASSOC');
+        if (Database::num_rows($result)>0) {
+            while ($row = Database::fetch_assoc($result)) {
+                if (empty($sessions[$row['id']])) {
+                    $sessions[$row['id']] = $row;
+                }
+            }
+        }
 
         if (api_is_allowed_to_create_course()) {
 
@@ -2423,7 +2443,7 @@ class UserManager
                 }
             }
         }
-
+        $course_list = array();
         if (api_is_drh()) {
             $session_list = SessionManager::get_sessions_followed_by_drh($user_id);
             $session_list = array_keys($session_list);
@@ -2439,13 +2459,11 @@ class UserManager
             //check if user is general coach for this session
             $s = api_get_session_info($session_id);
             if ($s['id_coach'] == $user_id) {
-                if (count($course_list)==0) {
-                    $course_list = SessionManager::get_course_list_by_session_id($session_id);
-                    if (!empty($course_list)) {
-                        foreach ($course_list as $course) {
-                            if (!in_array($course['code'],$courses)) {
-                                $personal_course_list[] = $course;
-                            }
+                $course_list = SessionManager::get_course_list_by_session_id($session_id);
+                if (!empty($course_list)) {
+                    foreach ($course_list as $course) {
+                        if (!in_array($course['code'],$courses)) {
+                            $personal_course_list[] = $course;
                         }
                     }
                 }
@@ -2464,6 +2482,7 @@ class UserManager
         if (empty($username)) {
             return false;
         }
+        $username = trim($username);
         $username = Database::escape_string($username);
         $t_user = Database::get_main_table(TABLE_MAIN_USER);
         $sql = "SELECT user_id FROM $t_user WHERE username = '$username'";

+ 23 - 7
main/inc/local.inc.php

@@ -964,18 +964,18 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset))
             Session::write('_courseUser',$_courseUser);
         }
 
-        //We are in a session course? Check session permissions
+        // We are in a session course? Check session permissions
         if (!empty($session_id)) {
-            //I'm not the teacher of the course
+            // I'm not the teacher of the course
             if ($is_courseAdmin == false) {
-                // this user has no status related to this course
+                // This user has no status related to this course
                 // The user is subscribed in a session? The user is a Session coach a Session admin ?
 
                 $tbl_session             = Database :: get_main_table(TABLE_MAIN_SESSION);
                 $tbl_session_course      = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
                 $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
-                //Session coach, session admin, course coach admin
+                // Session coach, session admin or course coach admin
                 $sql = "SELECT session.id_coach, session_admin_id, session_rcru.id_user
                         FROM $tbl_session session, $tbl_session_course_user session_rcru
                         WHERE  session_rcru.id_session  = session.id AND
@@ -986,9 +986,9 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset))
                         ";
 
                 $result = Database::query($sql);
-                $row     = Database::store_result($result);
+                $row = Database::store_result($result);
 
-                //Am I a session admin?
+                // Am I a session admin?
                 if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
                     $_courseUser['role'] = 'Professor';
                     $is_courseMember     = false;
@@ -1005,6 +1005,7 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset))
                            "AND session.id_coach = $user_id ".
                            "AND sc.course_code = '$_cid'";
                     $result = Database::query($sql);
+
                     if (Database::num_rows($result)) {
                         $_courseUser['role'] = 'Professor';
                         $is_courseMember     = true;
@@ -1063,7 +1064,7 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset))
                                     break;
                             }
                         } else {
-                            //unregister user
+                            // Unregister user
                             $is_courseMember     = false;
                             $is_courseTutor      = false;
                             $is_courseAdmin      = false;
@@ -1073,6 +1074,21 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset))
                         }
                     }
                 }
+
+                // Drh can enter to a course as an student see BT#6770
+                if (api_drh_can_access_all_session_content()) {
+                    $sessionInfo = SessionManager::getSessionFollowedByDrh($user_id, $session_id);
+                    if (!empty($sessionInfo) && !empty($sessionInfo['course_list'])) {
+                        if (isset($sessionInfo['course_list'][$_course['real_id']])) {
+                            $_courseUser['role'] = '';
+                            $is_courseMember     = true;
+                            $is_courseTutor      = false;
+                            $is_courseCoach      = false;
+                            $is_sessionAdmin     = false;
+                        }
+                    }
+                }
+
             }
 
             //If I'm the admin platform i'm a teacher of the course

+ 23 - 2
main/install/configuration.dist.php

@@ -163,5 +163,26 @@ $_configuration['deny_delete_users'] = false;
 // Version settings
 $_configuration['system_version']    = '{NEW_VERSION}';
 $_configuration['system_stable']     = NEW_VERSION_STABLE;
-$_configuration['hide_home_top_when_connected'] = true;
-$_configuration['hide_global_announcements_when_not_connected'] = true;
+
+/**
+ * Settings to be included as settings_current in future versions
+ */
+// Hide the main home section for connected users (to show announcements instead)
+//$_configuration['hide_home_top_when_connected'] = true;
+// Hide the global announcements for non-connected users
+//$_configuration['hide_global_announcements_when_not_connected'] = true;
+// Use this course as template for all new courses (define course real ID as value)
+//$_configuration['course_creation_use_template'] = 14;
+// Uncomment the following to prevent all admins to use the "login as" feature
+//$_configuration['login_as_forbidden_globally'] = true;
+// Add password strength checker
+//$_configuration['allow_strength_pass_checker'] = true;
+// Enable captcha
+//$_configuration['enable_captcha'] = true;
+//$_configuration['allow_captcha'] = true;
+// Prevent account from logging in for a certain amount of time if captcha is wrong for the specified number of times
+//$_configuration['captcha_number_mistakes_to_block_account'] = 5;
+// Prevent account from logging in for the specified number of minutes
+//$_configuration['captcha_time_to_block'] = 5;//minutes
+// Allow DRH role to access all content and users from the sessions he follows
+//$_configuration['drh_can_access_all_session_content'] = true;

+ 2 - 0
main/lang/english/trad4all.inc.php

@@ -2,6 +2,8 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$CreatedByXYOnZ = "Create by <a href=\"%s\">%s</a> on %s";
+$LoginWithExternalAccount = "Login without an institutional account";
 $NumberOfGroupsToCreate = "Number of groups to create";
 $CoachesSubscribedAsATeacherInCourseX = "Coaches subscribed as teachers in course %s";
 $EnrollStudentsFromExistingSessions = "Enroll students from existing sessions";

+ 1 - 1
main/lang/french/admin.inc.php

@@ -1288,7 +1288,7 @@ $ShowLinkBugNotificationTitle = "Lien de rapport d'erreur";
 $ShowLinkBugNotificationComment = "Montrer un lien dans l'en-tête qui mène directement vers notre plateforme de support (http://support.chamilo.org). Lorsque l'utilisateur clique sur ce lien, il est envoyé sur notre plateforme de support, vers une page qui lui expliquera comment rapporter un bug.";
 $DataFiller = "Remplisseur de données";
 $GradebookActivateScoreDisplayCustom = "Activer la libellisation des niveaux de compétences personnalisés pour les scores";
-$GradebookScoreDisplayCustomValues = "Valeurs personnalisées de niveaux de compétences";
+$GradebookScoreDisplayCustomValues = "Valeurs personnalisées de niveaux de notes";
 $GradebookNumberDecimals = "Nombre de décimales";
 $GradebookNumberDecimalsComment = "Permet de configurer le nombre de décimales autorisées dans les scores";
 $EditExtraFieldOptions = "Modifier les options de champs";

+ 2 - 2
main/lang/french/exercice.inc.php

@@ -419,9 +419,9 @@ $ExerciseEditionNotAvailableInSession = "Édition d'exercice de cours interdite
 $UniqueAnswerNoOption = "Rép. unique avec ne-sais-pas";
 $MultipleAnswerTrueFalse = "Rép. multiples vrai/faux/ne-sais-pas";
 $MultipleAnswerCombinationTrueFalse = "C. exacte vrai/faux/ne-sais-pas";
-$DontKnow = "Ne sais pas";
+$DontKnow = "Ne sait pas";
 $False = "Faux";
-$DoubtScore = "Ne sais pas";
+$DoubtScore = "Ne sait pas";
 $HotSpotDelineation = "Délinéation sur image";
 $PropagateNegativeResults = "Propager les résultats négatifs entre les questions";
 $InsertALinkToThisQuestionInTheExercise = "Insérer cette question dans l'exercice comme un lien (pas une copie)";

+ 1 - 1
main/lang/french/forum.inc.php

@@ -122,7 +122,7 @@ $NotifyMe = "M'alerter";
 $ConfirmUserQualification = "Confirmer cote apprenant";
 $NotChanged = "Non modifié";
 $TitleColumnGradebook = "Titre de colonne dans le rapport";
-$QualifyThreadGradebook = "Noter ce fil de discussion dans le rapport de compétences";
+$QualifyThreadGradebook = "Noter ce fil de discussion dans le cahier de notes";
 $QualifyWeight = "Pondération de la note";
 $QualifyNumeric = "Score maximum";
 $AlterQualifyThread = "Changer la cotation du fil de discussion";

+ 1 - 0
main/lang/french/install.inc.php

@@ -2,6 +2,7 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$DateTimezoneSettingNotSet = "Votre installation de PHP ne définit pas le paramètre date.timezone. Ce paramètre est important pour l'installation de Chamilo.<br/>Avant de continuer nous vous conseillons vivement de vérifiez ce paramètre dans votre fichier php.ini.<br/>L'installation peut ne pas s'achever correctement le cas échéant.";
 $langStatDB = "Base pour le tracking.  Utile uniquement si vous séparez les bases centrale et tracking";
 $langEnableTracking = "Activer le Tracking";
 $langInstituteShortName = "Nom abrégé de l'organisation";

+ 4 - 1
main/lang/french/trad4all.inc.php

@@ -2,6 +2,10 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$CreatedByXYOnZ = "Créé(e) par <a href=\"%s\">%s</a>, le %s";
+$LoginWithExternalAccount = "S'authentifier avec un compte extérieur à l'établissement";
+$CasDirectCourseAccess = "Accèder au cours avec l'authentification CAS";
+$SelectAnOption = "Sélectionner une option";
 $YourPasswordCannotBeTheSameAsYourUsername = "Votre mot de passe ne peut être identique à votre nom d'utilisateur";
 $CheckEasyPasswords = "Vérifier mots de passe trop simples";
 $PasswordVeryStrong = "Très fort";
@@ -1433,5 +1437,4 @@ $DataTableSearch = "Recherche";
 $HideColumn = "Cacher la colonne";
 $DisplayColumn = "Montrer la colonne";
 $LegalAgreementAccepted = "Conditions légales acceptées";
-$SelectAnOption = "Sélectionner une option";
 ?>

+ 5 - 4
main/lang/french/work.inc.php

@@ -2,6 +2,7 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$FolderDoesntExistsInFileSystem = "Le dossier de destination est introuvable sur le serveur.";
 $HandedOutDate = "Date de réception";
 $HandedOut = "Remis";
 $HandOutDateLimit = "Date limite de remise";
@@ -28,7 +29,7 @@ $langMustBeRegisteredUser = "Seuls les utilisateurs enregistrés de ce cours peu
 $langListDel = "Supprimer la liste";
 $langNameDir = "Nom du nouveau répertoire";
 $langFileExists = "Impossible d'effectuer cette opération.<br />Un fichier portant ce nom existe déjà.";
-$CreateDirectory = "Créer un répertoire";
+$CreateDirectory = "Enregistrer le travail";
 $langCurrentDir = "répertoire courant";
 $UploadADocument = "Envoyer un document";
 $EditToolOptions = "Éditer les options des travaux";
@@ -39,9 +40,9 @@ $ValidateChanges = "Valider les changements";
 $FolderUpdated = "Dosier mis à jour";
 $EndsAt = "Envoi impossible à partir du";
 $QualificationOfAssignment = "Évaluation de la tâche";
-$MakeQualifiable = "Activer l'évaluation";
+$MakeQualifiable = "Activer dans le cahier de notes";
 $QualificationNumberOver = "Évaluation sur...";
-$WeightInTheGradebook = "Pondération dans le rapport de compétences";
+$WeightInTheGradebook = "Pondération dans le cahier de notes";
 $DatesAvailables = "Dates disponibles";
 $ExpiresAt = "Expire le";
 $AddToCalendar = "Ajouter au calendrier";
@@ -62,7 +63,7 @@ $ExpiryDateAlreadyPassed = "La date d'expiration est déjà passée";
 $EndDateAlreadyPassed = "La date de fin est déjà passée";
 $MoveXTo = "Déplacer %s vers";
 $QualificationMustNotBeMoreThanQualificationOver = "La cote ne peut pas être supérieure à la qualification maximale";
-$ModifyDirectory = "Modifier le répertoire";
+$ModifyDirectory = "Modifier le travail";
 $DeleteAllFiles = "Supprimer tous les travaux";
 $BackToWorksList = "Retour à la liste de travaux";
 $EditMedia = "Éditer et coter le travail";

+ 43 - 0
main/lang/slovak/admin.inc.php

@@ -326,6 +326,7 @@ $NoticeText = "Text Oznamu";
 $LinkName = "Text Odkazu";
 $LinkURL = "URL Odkazu";
 $OpenInNewWindow = "Otvoriť v novom okne";
+$langLimitUsersListDefaultMaxComment = "V obrazovkách, ktoré umožňujú pridávanie používateľov k tréningu alebo do tried, v prípade ak prvý nefiltrovaný zoznam obsahuje viac ako je tento počet používateľov, potom sa prepne na prvé písmeno (A)";
 $Plugins = "Zásuvné moduly";
 $HideDLTTMarkupComment = "Skryť značky [=...=] keď  premenná jazyka nie je preložená";
 $Info = "Informácia";
@@ -1013,14 +1014,56 @@ $AllowSkillsToolTitle = "Povoliť nástroj Zručnosti";
 $AllowPublicCertificatesTitle = "Povoliť verejné certifikáty";
 $YouShouldCreateTermAndConditionsForAllAvailableLanguages = "Mali by ste vytvoriť \"Pojmy a podmienky\" pre všetky dostupné jazyky.";
 $ActivateEmailTemplateTitle = "Povoliť e-mailové šablóny upozornení";
+$ActivateEmailTemplateComment = "Definovať domáce e-mail upozornenia, ktoré budú vyhodené pre konkrétne udalosti (a na konkrétnych používateľov)";
 $SystemManagement = "Správa systému";
 $RemoveOldDatabaseMessage = "Odstrániť staré databázy";
 $RemoveOldTables = "Odstrániť staré tabuľky";
+$TotalSpaceUsedByPortalXLimitIsYMB = "Celkové miesto používané portálom %s limit je %s MB";
+$EventMessageManagement = "Správa správ udalosti";
 $Events = "Udalosti";
+$ToBeWarnedUserList = "Ak chcete byť upozornení zoznamom používateľov";
+$HideCampusFromPublicPlatformsList = "Skryť školu zo zoznamu verejných platforiem";
+$ChamiloOfficialServicesProviders = "Oficiálny poskytovatelia Chamilo služieb";
 $Reader = "Čitateľ";
+$Zombies = "Zombi";
+$ActiveOnly = "Iba aktívne";
+$AuthenticationSource = "Zdroj overovania";
+$RegisteredDate = "Dátum registrovania";
+$FilterTermsTitle = "Podmienky filtrovania";
+$FilterTermsComment = "Uveďte zoznam termínov, jeden po riadku, ktoré majú byť filtrované z webových stránok a e-mailov. Tieto podmienky budú nahradené ***.";
+$UseCustomPagesTitle = "Použiť vlastné stránky";
 $StudentPageAfterLoginTitle = "Stránka študenta po prihlásení";
+$StudentPageAfterLoginComment = "Táto stránka sa zobrazí všetkým študentom po prihlásení";
+$TeacherPageAfterLoginTitle = "Stránka lektora po prihlásení";
+$TeacherPageAfterLoginComment = "Táto stránka bude načítaná po prihlásení pre všetkých lektorov";
+$DRHPageAfterLoginTitle = "Stránka manažéra ľudských zdrojov po prihlásení";
+$DRHPageAfterLoginComment = "Táto stránka bude načítaná po prihlásení pre všetkých manažérov ľudských zdrojov";
+$StudentAutosubscribeTitle = "Automatické prihlásenie študenta";
+$StudentAutosubscribeComment = "Automatické prihlásenie študenta - zatiaľ nie je k dispozícii";
+$TeacherAutosubscribeTitle = "Automatické prihlásenie Lektora";
+$TeacherAutosubscribeComment = "Automatické prihlásenie Lektora - zatiaľ nie je k dispozícii";
+$DRHAutosubscribeTitle = "Automatické prihlásenie Riaditeľa ľudských zdrojov";
+$DRHAutosubscribeComment = "Automatické prihlásenie Riaditeľa ľudských zdrojov - zatiaľ nie je k dispozícií";
+$ScormCumulativeSessionTimeTitle = "Súhrny čas stretnutia pre SCORM";
+$ScormCumulativeSessionTimeComment = "Ak je povolené, bude čas stretnutia pre SCORM učebné osnovy súhrnný, inak bude počítaný iba z posledného pokusu o aktualizáciu času.";
+$SessionAdminPageAfterLoginTitle = "Administrátorská stránka stretnutia po prihlásení";
+$SessionAdminPageAfterLoginComment = "Stránka nahraná po prihlásení pre správcu stretnutia";
+$SessionadminAutosubscribeTitle = "Automatické prihlásenie správcu stretnutia";
+$SessionadminAutosubscribeComment = "Automatické prihlásenie správcu stretnutia - zatiaľ nie je k dispozícií";
+$ToolVisibleByDefaultAtCreationTitle = "Nástroj viditeľný pri tvorbe kurzu";
+$ToolVisibleByDefaultAtCreationComment = "Vyberte nástroje, ktoré budú viditeľné pri vytváraní kurzov - zatiaľ nie je k dispozícii";
+$casAddUserActivatePlatform = "CAS vnútorné nastavenie";
+$casAddUserActivateLDAP = "CAS vnútorné nastavenie";
+$UpdateUserInfoCasWithLdapTitle = "CAS vnútorné nastavenie";
+$UpdateUserInfoCasWithLdapComment = "CAS vnútorné nastavenie";
 $ShowAllUsers = "Ukázať všetkých používateľov";
+$ShowUsersNotAddedInTheURL = "Zobraziť používateľov, ktorí nie sú pridaný do URL";
+$UserNotAddedInURL = "Používatelia nepridaní do URL";
+$UsersRegisteredInNoSession = "Používatelia nie sú registrovaní v žiadnom stretnutí";
+$CommandLineInterpreter = "Interpret príkazového riadku (CLI)";
 $PleaseVisitOurWebsite = "Prosím navštívte naše webové stránky: http://www.chamilo.org";
+$SpaceUsedOnSystemCannotBeMeasuredOnWindows = "Priestor použitý na disku nie je možné správne merať na systémoch založených na systéme Windows.";
 $XOldTablesDeleted = "%d staré tabuľky zmazané";
 $XOldDatabasesDeleted = "%d staré databázy zmazané";
+$ExtensionShouldBeLoaded = "Toto rozšírenie by malo byť nahrané.";
 ?>

+ 2 - 0
main/lang/slovak/create_course.inc.php

@@ -103,9 +103,11 @@ $NewCourseCreatedIn = "Nový kurz vytvorený v";
 $ExplicationTrainers = "Lektor je nastavený teraz ako vy. Toto nastavenie môžete zmeniť neskôr v nastavení konfigurácie kurzu";
 $Objectives = "Ciele";
 $TargetAudience = "Cieľová skupina";
+$CourseRequestCreated = "Vaša žiadosť o nový kurz bola úspešne odoslaná. Môžete dostať odpoveď čoskoro, v priebehu jedného alebo dvoch dní.";
 $CreateThisCourseRequest = "Požiadať o vytvorenie kurzu";
 $CourseRequestDate = "Dátum požiadavky";
 $AcceptThisCourseRequest = "Akceptovať tento kurz";
+$ANewCourseWillBeCreated = "Nový kurz %s bude vytvorený. Je to v poriadku pre ďalšie pokračovanie?";
 $DeleteThisCourseRequest = "Odstrániť túto požiadavku kurzu";
 $CourseRequestEdit = "Upraviť požiadavku kurzu";
 $Accept = "Prijať";

+ 16 - 16
main/lang/slovak/exercice.inc.php

@@ -2,6 +2,14 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$ImportAikenQuizExplanationExample = "Toto je text pre otázku 1 A. Odpoveď 1 B. Odpoveď 2 C. Odpoveď 3 ANSWER: B Toto je text pre otázku 2 A. Odpoveď 1 B. Odpoveď 2 C. Odpoveď 3 D. Odpoveď 4 ANSWER: D ANSWER_EXPLANATION: to je voliteľná komentár spätnej väzby, ktorý sa zobrazí vedľa správnej odpovede.";
+$ImportAikenQuizExplanation = "Formát Aiken je v jednoduchom textovom súbore (.txt), s niekoľkými blokmi otázok, z ktorých každý je oddelený prázdnym riadkom. Prvý riadok je otázka, riadky s odpoveďou je označený písmenom a bodkou, a správna odpoveď príde s ďalšou ODPOVEĎOU: predpona. Viď príklad nižšie.";
+$ExerciseAikenErrorNoAnswerOptionGiven = "Importovaný súbor má aspoň jednu otázku bez odpovede (alebo odpovede neobsahujú požadovanú predponu listu). Uistite sa, že každá otázka má aspoň jednu odpoveď, a že má predponu písmeno a bodkou alebo zátvorku, ako je tento: A. jednu odpoveď";
+$ExerciseAikenErrorNoCorrectAnswerDefined = "Importovaný súbor obsahuje aspoň jednu otázku bez akejkoľvek správnej definovanej odpovede. Uistite sa, že všetky otázky majú ODPOVEĎ: [Letter] riadok.";
+$ThereWasAProblemWithYourFile = "Bol tam neznámy problém so súborom. Prosím skontrolujte jeho formát a skúste to znova.";
+$YouMustUploadAZipOrTxtFile = "Musíte nahrať .txt alebo .zip súbor";
+$NoTxtFileFoundInTheZip = "Nenájdený žiadny .txt súbor v súbore zip";
+$ImportAikenQuiz = "Importovať Aiken test";
 $ExerciseWasActivatedFromXToY = "Cvičenie bolo aktivované od %s do %s";
 $SelectAnAnswerToContinue = "Vyberte odpoveď pre pokračovanie";
 $IfYouContinueYourAnswerWillBeSavedAnyChangeWillBeNotAllowed = "Ak budete pokračovať vaše odpovede budú uložené, akákoľvek zmena urobená neskôr nie je dovolená. Ste si istí, že chcete pokračovať?";
@@ -11,18 +19,10 @@ $QuestionReused = "Otázka pridaná do cvičenia";
 $QuestionCopied = "Otázka skopírovaná do cvičenia";
 $ZeroMeansNoQuestionWillBeSelectedMinusOneMeansThatAllQuestionsWillBeSelected = "-1 = Budú vybrané všetky otázky. 0 = Budú vybrané žiadne otázky.";
 $EmailNotificationTemplateDescription = "Môžete prispôsobiť e-mail, ktorý sa posiela používateľom pri dokončení cvičenia. Môžete použiť tieto značky:<br>
-1. {{ student.username }}<br>
-2. {{ student.firstname }}<br>
-3. {{ student.lastname }}<br>
-4. {{ student.official_code }}<br>
-5. {{ exercise.title }}<br>
-6. {{ exercise.start_time }}<br>
-7. {{ exercise.end_time }}<br>
-8. {{ course.title }}<br>
-9. {{ course.code }}";
+1. {{ student.username }} 2. {{ student.firstname }} 3. {{ student.lastname }} 4. {{ student.official_code }} 5. {{ exercise.title }} 6. {{ exercise.start_time }} 7. {{ exercise.end_time }} 8. {{ course.title }} 9. {{ course.code }}";
 $EmailNotificationTemplate = "Šablóna e-mailu upozornenia";
 $ExerciseEndButtonDisconnect = "Odhlásiť";
-$ExerciseEndButtonExerciseHome = "Zoznam cvičenia";
+$ExerciseEndButtonExerciseHome = "Zoznam cvičenia.";
 $ExerciseEndButtonCourseHome = "Domov kurzu";
 $ExerciseEndButton = "Domovská stránka kurzu";
 $HideQuestionTitle = "Skryť názov otázky";
@@ -45,7 +45,7 @@ $MediaQuestions = "Zdieľané vyhlásenia";
 $AddedToLPCannotBeAccessed = "Toto zadanie bolo zahrnuté do učebnej osnovy, nemôže byť zobrazené študentmi priamo tu. Ak chcete, aby rovnaké zadanie bolo k dispozícii prostredníctvom nástroja zadanie, prosím urobte kópiu aktuálneho zadania pomocou ikony kopírovania.";
 $langExercice = "Test";
 $langActivate = "Ukázať";
-$langDeactivate = "Schovaj";
+$langDeactivate = "Skryť";
 $langNoEx = "Momentálne tu nie je žiadny test";
 $langNewEx = "Nový test";
 $langQuestion = "Otázka";
@@ -87,9 +87,9 @@ $langUseTagForBlank = "použiť hranaté zátvorky [...] na definovanie jedného
 $langQuestionWeighting = "Váha";
 $langMoreAnswers = "+odp";
 $langLessAnswers = "-odp";
-$langMoreElements = "+elem";
-$langLessElements = "-elem";
-$langTypeTextBelow = "Prosím nižšie napíšte svoj text";
+$langMoreElements = "+prvok";
+$langLessElements = "-prvok";
+$langTypeTextBelow = "Prosím napíšte svoj text nižšie";
 $langDefaultTextInBlanks = "[Briti] žijú vo [Veľkej Británii].";
 $langDefaultMatchingOptA = "bohatý";
 $langDefaultMatchingOptB = "pekný";
@@ -148,7 +148,7 @@ $langIntroduction = "Úvod";
 $langTitleAssistant = "Pomocník pre tvorbu testov";
 $langQuesList = "zoznam otázok";
 $langSaveEx = "uložiť cvičenia";
-$langFinish = "Ukončiť";
+$langFinish = "Ukončiť test";
 $langCancel = "Zrušiť";
 $langQImage = "Otázka s obrázkom";
 $langAddQ = "Pridať otázku";
@@ -164,7 +164,7 @@ $langReplaced = "Vymenený";
 $langSuperior = "hodnota väčšia ako 20";
 $langRep20 = "Nahradiť 20";
 $langDefault = "Prednastavené hodnoty *";
-$langDefComment = "predchádzajúce hodnoty budú nahradené klikom na tlačidlo \"prednastavené hodnoty\"";
+$langDefComment = "predchádzajúce hodnoty budú nahradené kliknutím na tlačidlo \"prednastavené hodnoty\"";
 $langScoreGet = "čierne čísla = skóre";
 $langShowScor = "Zobraziť hodnotenie študentom:";
 $langStep1 = "Etapa 1";

+ 41 - 4
main/lang/slovak/install.inc.php

@@ -2,8 +2,11 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$DateTimezoneSettingNotSet = "Zistili sme, že vaša inštalácia PHP nedefinuje nastavenie date.timezone. Toto je požiadavka Chamilo. Prosím uistite sa, že je nastavená konfigurácia php.ini podľa kontroly, inak sa dostanete do problémov. Varovali sme vás!";
 $langStatDB = "Štatistická databáza";
 $langEnableTracking = "Aktivovať štatistiku";
+$langInstituteShortName = "Skrátený názov vašej spoločnosti";
+$langWarningResponsible = "Použite tohto skript iba po zálohovaní. Tím Chamilo nie je zodpovedný za stratené alebo poškodené údaje.";
 $langAllowSelfRegProf = "Povoliť samo-registráciu ako tvorcu kurzu";
 $langEG = "napr.";
 $langDBHost = "Hostiteľ databázy";
@@ -12,6 +15,7 @@ $langDBPassword = "Databázové heslo";
 $langMainDB = "Hlavná Chamilo databáza (DB)";
 $langAllFieldsRequired = "všetky polia povinné";
 $langPrintVers = "Verzia pre tlač";
+$langLocalPath = "Zodpovedajúca lokálnej ceste";
 $langAdminEmail = "Email administrátora";
 $langAdminName = "Meno administrátora";
 $langAdminSurname = "Priezvisko administrátora";
@@ -19,6 +23,7 @@ $langAdminLogin = "Prihlásenie administrátora";
 $langAdminPass = "Heslo administrátora (<font color=\"red\">môžete ho zmeniť</font>)";
 $langEducationManager = "Projektový manažér";
 $langCampusName = "Meno portálu";
+$langDBSettingIntro = "Inštalačný skript vytvorí hlavnú Chamilo databázu(y). Vezmite prosím na vedomie, že Chamilo bude musieť vytvoriť viac databáz. Ak vaša Hostingová služba má povolené používať iba jednu databázu, Chamilo nebude fungovať, ak ste zvolili možnosť \"Jedna databáza\".";
 $langStep1 = "Etapa 1";
 $langStep2 = "Etapa 2";
 $langStep3 = "Etapa 3 zo 6";
@@ -43,7 +48,7 @@ $langAdminPhone = "Telefónne číslo administrátora";
 $OK = "OK";
 $langAdminFirstName = "Meno administrátora";
 $langInstituteURL = "URL organizácie";
-$langDokeosURL = "URL Chamilo-u";
+$langDokeosURL = "URL Chamilo";
 $langUserDB = "Používateľ DB";
 $PleaseWait = "Čakajte prosím";
 $PleaseCheckTheseValues = "Prosím skontrolujte tieto hodnoty";
@@ -60,6 +65,7 @@ $of = "z";
 $Step = "Etapa";
 $MoreDetails = "Pre viac detailov";
 $ServerRequirements = "Požiadavky serveru";
+$ServerRequirementsInfo = "Váš server musí poskytnúť nasledujúce knižnice, aby boli povolené všetky funkcie Chamilo. Chýbajúce knižnice zobrazené písmenami na oranžovo sú nepovinné, ale niektoré funkcie Chamilo môžu byť zakázané, pokiaľ nie sú nainštalované. Stále môžete nainštalovať tieto knižnice neskôr a povoliť chýbajúce funkcie.";
 $PHPVersion = "PHP verzia";
 $support = "podpora";
 $PHPVersionOK = "PHP verzia je OK";
@@ -68,34 +74,65 @@ $RecommendedSettingsInfo = "Odporúčané nastavenia pre konfiguráciu Vášho s
 $Setting = "Nastavenie";
 $Actual = "Aktuálne";
 $DirectoryAndFilePermissions = "Povolenia pre katalógy a súbory";
+$DirectoryAndFilePermissionsInfo = "Niektoré adresáre a súbory, ktoré obsahujú, musia byť zapisovateľné webovým serverom, aby ich Chamilo spustil (používateľ nahral súbory, domovské súbory html, ...). Toto by mohlo znamenať, vykonať ručné zmeny na vašom serveri (mimo toto rozhranie).";
 $NotWritable = "Nie je možné prepísať";
 $Writable = "Možnosť prepísať";
 $ExtensionLDAPNotAvailable = "LDAP rozšírenie nedostupné";
 $ExtensionGDNotAvailable = "GD rozšírenie nedostupné";
+$DokeosLicenseInfo = "Chamilo je free softvér distribuovaný pod licenciou GNU General Public licence (GPL).";
 $IAccept = "Súhlasím";
 $ConfigSettingsInfo = "Nasledujúce hodnoty budú zapísané vo Vašom konfiguračnom súbore";
 $DokeosInstallation = "Chamilo inštalácia";
 $InstallDokeos = "Inštalovať Chamilo";
 $GoToYourNewlyCreatedPortal = "Choďte na Váš novo zriadený portál.";
+$FirstUseTip = "Keď prvýkrát vstúpite na portál, najlepší spôsob, ako ho pochopiť, je vytvoriť kurz s \"Vytvoriť kurz\" odkazom v menu a pohrajte sa s ním trochu.";
 $Version_ = "Verzia";
-$UpdateFromDokeosVersion = "Aktualizácia z Chamilo-u";
-$WelcomToTheDokeosInstaller = "Vitajte v inštalačnom programe Chamilo-u";
+$UpdateFromDokeosVersion = "Aktualizácia z Chamilo";
+$WelcomToTheDokeosInstaller = "Vitajte v inštalátore Chamilo";
 $PleaseSelectInstallationProcessLanguage = "Prosím vyberte jazyk, ktorý chcete použiť pri inštalácii";
 $ReadTheInstallGuide = "čítať návod na inštaláciu";
 $HereAreTheValuesYouEntered = "Tu sú hodnoty, ktoré ste zadali";
 $PrintThisPageToRememberPassAndOthers = "Vytlačte túto stránku, aby ste nezabudli vaše heslo a ďalšie nastavenia";
+$TheInstallScriptWillEraseAllTables = "Inštalačný skript zmaže všetky tabuľky z vybraných databáz. Silno vám odporúčame vykonať ich úplnú zálohu pred potvrdením tohto posledného kroku inštalácie.";
 $Warning = "Upozornenie";
 $ReadWarningBelow = "Čítať upozornenie nižšie";
 $SecurityAdvice = "Rada ohľadne bezpečnosti";
+$YouHaveMoreThanXCourses = "Máte viac ako %d kurzov na vašej platforme Chamilo! Iba %d kurzy boli aktualizované. Ak chcete aktualizovať ďalšie kurzy, %s kliknite tu %s";
+$ToProtectYourSiteMakeXAndYReadOnly = "Ak chcete chrániť svoje stránky, nastavte %s a %s (ale nie ich adresáre) len na čítanie (CHMOD 444).";
 $Error = "Chyba";
 $Back = "Späť";
 $HasNotBeenFound = "nenájdený";
-$PleaseGoBackToStep1 = "Prosím choďte späť na etapu 1";
+$PleaseGoBackToStep1 = "Prosím choďte späť na Krok 1";
 $HasNotBeenFoundInThatDir = "nebol nájdený v tomto katalógu";
+$OldVersionRootPath = "Stará verzia koreňovej cesty";
+$NoWritePermissionPleaseReadInstallGuide = "Niektoré súbory alebo priečinky nemajú oprávnenie na zápis. Aby bolo možné nainštalovať Chamilo, mali by ste najprv zmeniť ich oprávnenie (pomocou CHMOD). Prečítajte si prosím %s inštalačnú príručku %s";
 $DBServerDoesntWorkOrLoginPassIsWrong = "Server databázy nefunguje alebo prihlasovacie meno / heslo nie je správne";
 $PleaseGoBackToStep = "Prosím choďte späť na etapu";
+$DBSettingUpgradeIntro = "Upgrade skript obnoví a aktualizuje Chamilo databázu(y). Za týmto účelom bude tento skript používať databázy a nastavenie definované nižšie. Pretože náš softvér beží na širokej škále systémov a pretože všetky z nich nemusia byť testované, dôrazne odporúčame vykonať úplnú zálohu databázy, pred tým ako budete pokračovať s upgradom!";
 $ExtensionMBStringNotAvailable = "MBString rozšírenie nedostupné";
 $ExtensionMySQLNotAvailable = "MySQL rozšírenie nedostupné";
+$DokeosArtLicense = "Obrázky a mediálne galérie Chamilo používajú obrázky z Nuvola, Crystal Clear a Tango ikon galérií. Ďalšie obrázky a médiá, ako sú diagramy a Flash animácie sú požičané od Wikimedia a Ali Pakdel a Denis Hoa kurzy s ich súhlasom, a je uvoľnený pod BY-SA Creative Commons licencie. Podrobnosti o licencii môžete nájsť na <a href=\"http://creativecommons.org/licenses/by-sa/3.0/\" target=\"_blank\">CC webových stránkach</a>, kde je plné znenie licencie poskytované v dolnej časti stránky.";
 $OptionalParameters = "Nepovinné parametre";
 $FailedConectionDatabase = "Pripojenie k databáze bolo neúspešné. Obvykle je to kvôli nesprávnemu používateľovi, heslu alebo predpone databázy zadanej hore. Skontrolujte prosím tieto nastavenia a skúste znova.";
+$EncryptMethodUserPass = "Metóda šifrovania";
+$UpgradeFromDokeos16x = "Upgrade z Chamilo 1.6.x";
+$UpgradeFromDokeos18x = "Upgrade z Chamilo 1.8.x";
+$Step7 = "Krok 7";
+$SuggestionOnlyToEnableCSSUploadFeature = "Navrhnite iba v prípade, ak chcete povoliť CSS funkciu odoslania";
+$SuggestionOnlyToEnableSubLanguageFeature = "Návrh iba v prípade, že chcete povoliť funkciu pod-jazyka";
+$ToProtectYourSiteMakeXReadOnlyAndDeleteY = "Ak chcete chrániť vašu stránku, nastavte celý adresár %s iba na čítanie (chmod 0555 na Linuxe) a odstráňte  %s adresár.";
+$IfYouPlanToUpgradeFromOlderVersionYouMightWantToHaveAlookAtTheChangelog = "Ak plánujete upgrade zo staršej verzie Chamilo, možno sa budete <a href=\"https://translate.chamilo.org/documentation/changelog.html\" target=\"_blank\">chcieť pozrieť na zoznam zmien</a> a vedieť, čo je nové a čo sa zmenilo";
+$WelcomeToTheDokeosInstaller = "Vitajte v inštalácií Chamilo";
+$PHPVersionError = "Vaša PHP verzia nezodpovedá požiadavkám pre tento softvér. Skontrolujte prosím, či máte najnovšiu verziu a skúste to znova.";
+$ExtensionSessionsNotAvailable = "Rozšírenie spojenia nie je k dispozícií";
+$ExtensionZlibNotAvailable = "Zlib rozšírenie nie je k dispozícií";
+$ExtensionPCRENotAvailable = "PCRE rozšírenie nie je k dispozícií";
+$DatabaseXWillBeCreated = "Databáza %s bude vytvorená";
+$ADatabaseWithTheSameNameAlreadyExists = "Databáza s rovnakým názvom <strong>už existuje.</strong>";
+$UserXCantHaveAccessInTheDatabaseX = "Používateľ %s nemá prístup do databázy %s";
+$DatabaseXCantBeCreatedUserXDoestHaveEnoughPermissions = "Databázu %s nie je možné vytvoriť, používateľ %s nemá dostatočné oprávnenia";
+$CourseTestWasCreated = "Skúšobný kurz bol úspešne vytvorený";
+$InstallExecution = "Spustiť proces inštalácie";
+$UpdateExecution = "Aktualizovať proces spustenia";
+$PleaseWaitThisCouldTakeAWhile = "Čakajte prosím. Môže to chvíľu trvať ...";
 ?>

+ 23 - 0
main/lang/slovak/tracking.inc.php

@@ -138,7 +138,9 @@ $langAllRight = "Nie je tu žiadny nezvy&#269;ajný prípad";
 $langDefcon = "Objavené problematické prípady !!";
 $langNULLValue = "Prázdny (alebo NULA)";
 $langTrafficDetails = "Podrobnosti prevádzky";
+$langSeeIndividualTracking = "Pre individuálne sledovane pozrite <a href=../user/user.php>Používateľské</a> nástroje.";
 $langPathNeverOpenedByAnybody = "Táto osnova nebola nikdy otvorená.";
+$SynthesisView = "Syntéza pohľad";
 $Visited = "Navštívený";
 $FirstAccess = "Prvý prístup";
 $LastAccess = "Posledný prístup";
@@ -224,6 +226,7 @@ $FollowingFieldsWillAlsoBeExported = "Nasledujúce polia budú tiež exportovan
 $TotalExercisesScoreObtained = "Celkové skóre získané z cvičení";
 $TotalExercisesScorePossible = "Celkové možné skóre cvičení";
 $TotalExercisesAnswered = "Počet zodpovedaných cvičení";
+$TotalExercisesScorePercentage = "Celkové percentuálne skóre pre testy";
 $ForumForumsNumber = "Počet fór";
 $ForumThreadsNumber = "Počet tém";
 $ForumPostsNumber = "Počet správ";
@@ -233,16 +236,24 @@ $CourseInformation = "Informácie o kurze";
 $NoAdditionalFieldsWillBeExported = "Žiadne ďalšie polia nebudú exportované";
 $langSendNotification = "Poslať oznámenia";
 $TimeOfActiveByTraining = "Čas v kurze";
+$AvgAllUsersInAllCourses = "Priemer všetkých študentov vo všetkých kurzoch";
+$AvgExercisesScore = "Skóre testov";
 $TrainingTime = "Čas";
 $CourseProgress = "Pokrok";
 $ViewMinus = "Ukázať mínus";
 $DashboardBlocks = "Dashboard bloky";
 $DashboardList = "Dashboard zoznam";
 $AddADateTime = "Pridať čas a dátum";
+$DateLock = "Dátum zamknutia";
 $CountOfUsers = "Spočítať používateľov";
+$CountOfSubscriptions = "Počet predplatného";
+$FolderCreated = "Nová zložka vytvorená";
+$LearnpathVisible = "Zviditeľniť učebnú osnovu";
+$LinkInvisible = "Zneviditeľniť Odkaz";
 $LinkAdded = "Odkaz pridaný";
 $Minutes = "Minúty";
 $BackupCreated = "Záloha vytvorená";
+$CountCertificates = "Spočítať certifikáty";
 $AverageHoursPerStudent = "Priem. hodiny/študent";
 $TrainingHoursAccumulated = "Nahromadené tréningové hodiny";
 $ManHours = "Človekohodín";
@@ -260,8 +271,20 @@ $BestAttempt = "Najlepší pokus";
 $Untitled = "Bez názvu";
 $Quantity = "Množstvo";
 $UploadedDocuments = "Nahrané dokumenty";
+$ExerciseProgress = "Postup v Cvičení";
 $NumberOfStudents = "Počet študentov";
+$NumberStudentsAccessingCourse = "Počet študentov vstupujúcich na kurz";
+$AverageOfActivitiesCompletedPerStudent = "Priemerný počet dokončených aktivít na študenta";
+$TotalTimeSpentInTheCourse = "Celkový čas strávený v kurze";
+$AverageTimePerStudentInCourse = "Priemerný čas na študenta strávený v kurze";
+$NumberOfDocumentsInLearnpath = "Počet dokumentov v Učebnej osnove";
+$NumberOfExercisesInLearnpath = "Počet cvičení v Učebnej osnove";
 $NumberOfLinksInLearnpath = "Počet odkazov v učebnej osnove";
+$NumberOfForumsInLearnpath = "Počet Fór v Učebnej osnove";
+$NumberOfAssignmentsInLearnpath = "Počet zadaní v Učebnej osnove";
+$NumberOfAnnouncementsInCourse = "Počet oznámení v kurze";
+$CurrentCoursesReport = "Správa aktuálnych kurzov";
+$NumberOfPublishedExercises = "# publikovaných cvičení";
 $NumberOfPublishedLps = "# publikovaných učebných osnov";
 $EventType = "Typ udalosti";
 $NbInactiveSessions = "Počet neaktívnych stretnutí";

+ 1 - 1
main/lang/slovak/trad4all.inc.php

@@ -50,7 +50,7 @@ $PasswordNormal = "Normálne";
 $PasswordWeak = "Slabé";
 $PasswordIsTooShort = "Heslo je príliš krátke";
 $BadCredentials = "Zlé poverenia";
-$BreadcrumbNavigationDisplayComment = "Zobraziť alebo skryť maličkú navigáciu, tá sa objaví tesne pod hlavnou navigáciou v kartách. Dôrazne sa odporúča, aby sa táto navigácia zobrazovala používateľom, pretože to im umožňuje lokalizovať svoju aktuálnu polohu a ľahko ich to naviguje na predchádzajúce stránky.
+$BreadcrumbNavigationDisplayComment = "Zobraziť alebo skryť maličkú navigáciu, tá sa objaví tesne pod hlavnou navigáciou v kartách. Dôrazne sa odporúča, aby sa táto navigácia zobrazovala používateľom, pretože to im umožňuje lokalizovať svoju aktuálnu polohu a ľahko ich to naviguje na predchádzajúce stránky. 
 
 Niekedy, môže byť však potrebné to skryť (napr. v prípade skúšky), aby sa zabránilo používateľom použiť navigáciu na stránky, na ktorých by to nemalo byť vidieť.";
 $BreadcrumbNavigationDisplayTitle = "Maličká navigácia";

+ 1 - 0
main/lang/spanish/trad4all.inc.php

@@ -2,6 +2,7 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$CreatedByXYOnZ = "Creado/a por <a href=\"%s\">%s</a> el %s";
 $NumberOfGroupsToCreate = "Cantidad de grupos a crear";
 $CoachesSubscribedAsATeacherInCourseX = "Tutores inscritos como profesores en curso %s";
 $EnrollStudentsFromExistingSessions = "Suscribir estudiantes de sesiones existentes";

+ 14 - 6
main/mySpace/company_reports.php

@@ -29,12 +29,19 @@ $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_user_course_report';
 $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
 
 //The order is important you need to check the the $column variable in the model.ajax.php file
-$columns = array(get_lang('Course'), get_lang('User'), get_lang('ManHours'), get_lang('CertificateGenerated'), get_lang('Approved'), get_lang('CourseAdvance'));
+$columns = array(
+    get_lang('Course'),
+    get_lang('User'),
+    get_lang('ManHours'),
+    get_lang('CertificateGenerated'),
+    get_lang('Approved'),
+    get_lang('CourseAdvance')
+);
 
 //Column config
 $column_model = array(
-    array('name'=>'course',         'index'=>'title',       'width'=>'180', 'align'=>'left'),
-    array('name'=>'user',           'index'=>'user',        'width'=>'100', 'align'=>'left','sortable'=>'false'),
+    array('name'=>'course',         'index'=>'title',       'width'=>'180', 'align'=>'left', 'wrap_cell' => 'true'),
+    array('name'=>'user',           'index'=>'user',        'width'=>'100', 'align'=>'left','sortable'=>'false', 'wrap_cell' => 'true'),
     array('name'=>'time',           'index'=>'time',        'width'=>'50',  'align'=>'left','sortable'=>'false'),
     array('name'=>'certificate',    'index'=>'certificate', 'width'=>'50',  'align'=>'left','sortable'=>'false'),
     array('name'=>'progress_100',   'index'=>'progress_100',       'width'=>'50',  'align'=>'left','sortable'=>'false'),
@@ -45,9 +52,10 @@ if (!empty($extra_fields)) {
     foreach ($extra_fields as $extra) {
         $col = array(
             'name' => $extra['1'],
-            'index'=> $extra['1'],
-            'width'=>'120',
-            'sortable'=>'false'
+            'index' => $extra['1'],
+            'width' => '120',
+            'sortable' =>'false',
+            'wrap_cell' => 'true'
         );
         $column_model[] = $col;
 

+ 33 - 8
main/mySpace/company_reports_resumed.php

@@ -9,6 +9,7 @@
  */
 $language_file = array('admin', 'gradebook', 'tracking');
 $cidReset = true;
+
 require_once '../inc/global.inc.php';
 
 if (!(api_is_platform_admin(false, true))) {
@@ -18,22 +19,27 @@ if (!(api_is_platform_admin(false, true))) {
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('MySpace'));
 
 $tool_name = get_lang('Report');
-
 $this_section = SECTION_TRACKING;
-
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
-//jqgrid will use this URL to do the selects
+// jqgrid will use this URL to do the selects
 $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_user_course_report_resumed';
 
 $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
 
-//The order is important you need to check the the $column variable in the model.ajax.php file
-$columns = array(get_lang('Company'), get_lang('TrainingHoursAccumulated'), get_lang('CountOfSubscriptions'), get_lang('CountOfUsers'), get_lang('AverageHoursPerStudent'), get_lang('CountCertificates'));
+// The order is important you need to check the the $column variable in the model.ajax.php file.
+$columns = array(
+    get_lang('Company'),
+    get_lang('TrainingHoursAccumulated'),
+    get_lang('CountOfSubscriptions'),
+    get_lang('CountOfUsers'),
+    get_lang('AverageHoursPerStudent'),
+    get_lang('CountCertificates')
+);
 
-//Column config
+// Column config.
 $column_model = array(
-    array('name' => 'extra_ruc', 'index' => 'extra_ruc', 'width' => '100', 'align' => 'left', 'sortable' => 'false'),
+    array('name' => 'extra_ruc', 'index' => 'extra_ruc', 'width' => '100', 'align' => 'left', 'sortable' => 'false', 'wrap_cell' => 'true'),
     array('name' => 'training_hours', 'index' => 'training_hours', 'width' => '100', 'align' => 'left'),
     array('name' => 'count_users', 'index' => 'count_users', 'width' => '100', 'align' => 'left', 'sortable' => 'false'),
     array('name' => 'count_users_registered', 'index' => 'count_users_registered', 'width' => '100', 'align' => 'left', 'sortable' => 'false'),
@@ -41,7 +47,26 @@ $column_model = array(
     array('name' => 'count_certificates', 'index' => 'count_certificates', 'width' => '100', 'align' => 'left', 'sortable' => 'false'),
 );
 
-//Autowidth
+if (!empty($extra_fields)) {
+    foreach ($extra_fields as $extra) {
+        if ($extra['1'] == 'ruc') {
+            continue;
+        }
+        $col = array(
+            'name' => $extra['1'],
+            'index' => $extra['1'],
+            'width' => '120',
+            'sortable' =>'false',
+            'wrap_cell' => 'true'
+        );
+        $column_model[] = $col;
+
+        $columns[] = $extra['3'];
+    }
+}
+
+
+// Autowidth.
 $extra_params['autowidth'] = 'true';
 //height auto
 $extra_params['height'] = 'auto';

+ 281 - 280
main/mySpace/index.php

@@ -29,10 +29,10 @@ ob_start();
 $export_csv  = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
 $display 	 = isset($_GET['display']) ? Security::remove_XSS($_GET['display']) : null;
 $csv_content = array();
-$nameTools   		= get_lang('MySpace');
+$nameTools = get_lang('MySpace');
 
-$user_id 	 		= api_get_user_id();
-$is_coach 			= api_is_coach($_GET['session_id']); // This is used?
+$user_id = api_get_user_id();
+$is_coach = api_is_coach($_GET['session_id']); // This is used?
 
 $session_id = isset($_GET['session_id']) ? intval($_GET['session_id']) : 0;
 
@@ -44,20 +44,20 @@ $count_sessions 	= 0;
 $count_courses		= 0;
 $title 				= null;
 
-// access control
+// Access control
 api_block_anonymous_users();
 
 if (!$export_csv) {
     Display :: display_header($nameTools);
 } else {
     if ($_GET['view'] == 'admin') {
-        if($display == 'useroverview') {
+        if ($display == 'useroverview') {
             MySpace::export_tracking_user_overview();
             exit;
-        } else if($display == 'sessionoverview') {
+        } elseif ($display == 'sessionoverview') {
             MySpace::export_tracking_session_overview();
             exit;
-        } else if($display == 'courseoverview') {
+        } elseif ($display == 'courseoverview') {
             MySpace::export_tracking_course_overview();
             exit;
         }
@@ -69,8 +69,7 @@ $tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
 $tbl_sessions 				= Database :: get_main_table(TABLE_MAIN_SESSION);
 $tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
-
-/* * FUNCTIONS */
+/* FUNCTIONS */
 function count_coaches() {
 	global $total_no_coaches;
 	return $total_no_coaches;
@@ -85,67 +84,66 @@ function rsort_users($a, $b) {
 }
 
 function count_sessions_coached() {
-	global $count_sessions;
-	return $count_sessions;
+    global $count_sessions;
+    return $count_sessions;
 }
 
 function sort_sessions($a, $b) {
-	global $tracking_column;
-	if ($a[$tracking_column] > $b[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
+    global $tracking_column;
+    if ($a[$tracking_column] > $b[$tracking_column]) {
+        return 1;
+    } else {
+        return -1;
+    }
 }
 
 function rsort_sessions($a, $b) {
-	global $tracking_column;
-	if ($b[$tracking_column] > $a[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
+    global $tracking_column;
+    if ($b[$tracking_column] > $a[$tracking_column]) {
+        return 1;
+    } else {
+        return -1;
+    }
 }
 
-/* * MAIN CODE  */
+/* MAIN CODE  */
 
 if ($is_session_admin) {
-	header('location:session.php');
-	exit;
+    header('location:session.php');
+    exit;
 }
 
 // Get views
 $views = array('admin', 'teacher', 'coach', 'drh');
 $view  = 'teacher';
 if (isset($_GET['view']) && in_array($_GET['view'], $views)) {
-	$view = $_GET['view'];
+    $view = $_GET['view'];
 }
 
 $menu_items = array();
 global $_configuration;
 
 if ($is_platform_admin) {
-	if ($view == 'admin') {
-		$title = get_lang('CoachList');
-		$menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('TeacherInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=teacher');
-		$menu_items[] = Display::url(Display::return_icon('star_na.png', get_lang('AdminInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=admin');
+    if ($view == 'admin') {
+        $title = get_lang('CoachList');
+        $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('TeacherInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=teacher');
+        $menu_items[] = Display::url(Display::return_icon('star_na.png', get_lang('AdminInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=admin');
         $menu_items[] = Display::url(Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'tracking/exams.php');
         $menu_items[] = Display::url(Display::return_icon('statistics.png', get_lang('CurrentCoursesReport'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'mySpace/current_courses.php');
-	} else {
-		$menu_items[] = Display::url(Display::return_icon('teacher_na.png', get_lang('TeacherInterface'), array(), ICON_SIZE_MEDIUM), '');
-		$menu_items[] = Display::url(Display::return_icon('star.png', get_lang('AdminInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=admin');
+    } else {
+        $menu_items[] = Display::url(Display::return_icon('teacher_na.png', get_lang('TeacherInterface'), array(), ICON_SIZE_MEDIUM), '');
+        $menu_items[] = Display::url(Display::return_icon('star.png', get_lang('AdminInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=admin');
         $menu_items[] = Display::url(Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'tracking/exams.php');
         $menu_items[] = Display::url(Display::return_icon('statistics.png', get_lang('CurrentCoursesReport'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'mySpace/current_courses.php');
-	}
+    }
 }
 
 if ($is_drh) {
 	$view = 'drh';
-	$menu_items[] = Display::url(Display::return_icon('user_na.png', get_lang('Students'), array(), ICON_SIZE_MEDIUM), '#');
-	$menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
-	$menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), 'course.php');
-	$menu_items[] = Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), 'session.php');
-
+    $menu_items[] = Display::url(Display::return_icon('user_na.png', get_lang('Students'), array(), ICON_SIZE_MEDIUM), '#');
+    $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
+    $menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), 'course.php');
+    $menu_items[] = Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), 'session.php');
     $menu_items[] = Display::url(Display::return_icon('empty_evaluation.png', get_lang('CompanyReports'), array(), ICON_SIZE_MEDIUM), 'company_reports.php');
     $menu_items[] = Display::url(Display::return_icon('evaluation_rate.png', get_lang('CompanyReportResumed'), array(), ICON_SIZE_MEDIUM), 'company_reports_resumed.php');
 }
@@ -154,26 +152,25 @@ echo '<div id="actions" class="actions">';
 echo '<span style="float:right">';
 
 if ($display == 'useroverview' || $display == 'sessionoverview' || $display == 'courseoverview') {
-	echo '<a href="'.api_get_self().'?display='.$display.'&export=csv&view='.$view.'">';
-    echo Display::return_icon("export_csv.png", get_lang('ExportAsCSV'),array(), 32);
+    echo '<a href="'.api_get_self().'?display='.$display.'&export=csv&view='.$view.'">';
+    echo Display::return_icon("export_csv.png", get_lang('ExportAsCSV'), array(), 32);
     echo '</a>';
 }
 echo '<a href="javascript: void(0);" onclick="javascript: window.print()">'.
-      Display::return_icon('printer.png', get_lang('Print'),'',ICON_SIZE_MEDIUM).'</a>';
+    Display::return_icon('printer.png', get_lang('Print'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '</span>';
 
-if (!empty($session_id) && !in_array($display, array('accessoverview','lpprogressoverview'))) {
-	echo '<a href="index.php">'.Display::return_icon('back.png', get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
+if (!empty($session_id) && !in_array($display, array('accessoverview','lpprogressoverview','progressoverview','exerciseprogress'))) {
+    echo '<a href="index.php">'.Display::return_icon('back.png', get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
     if (!api_is_platform_admin()) {
         if (api_get_setting('add_users_by_coach') == 'true') {
-	        if ($is_coach) {
-		        echo "<div align=\"right\">";
+            if ($is_coach) {
+                echo "<div align=\"right\">";
                 echo '<a href="user_import.php?id_session='.$session_id.'&action=export&amp;type=xml">'.
                         Display::return_icon('excel.gif', get_lang('ImportUserList')).'&nbsp;'.get_lang('ImportUserList').'</a>';
                 echo "</div><br />";
-	        }
-	    }
-
+            }
+        }
     } else {
         echo "<div align=\"right\">";
         echo '<a href="user_import.php?id_session='.$session_id.'&action=export&amp;type=xml">'.
@@ -186,63 +183,57 @@ if (!empty($session_id) && !in_array($display, array('accessoverview','lpprogres
 
 // Actions menu
 $nb_menu_items = count($menu_items);
-if (empty($session_id) || in_array($display, array('accessoverview','lpprogressoverview'))) {
-	if ($nb_menu_items > 1) {
-    	foreach ($menu_items as $key => $item) {
-	    	echo $item;
-		}
-	}
+if (empty($session_id) || in_array($display, array('accessoverview','lpprogressoverview', 'progressoverview', 'exerciseprogress'))) {
+    if ($nb_menu_items > 1) {
+        foreach ($menu_items as $key => $item) {
+            echo $item;
+        }
+    }
 }
 // Create a filter by session
-    $sessionFilter = new FormValidator('course_filter', 'get', '', '', array('class'=> 'form-search'), false);
-    $url = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_session';
+$sessionFilter = new FormValidator('course_filter', 'get', '', '', array('class'=> 'form-search'), false);
+$url = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_session';
+$sessionList = array();
+$sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : null;
+if (!empty($sessionId)) {
     $sessionList = array();
-    $sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : null;
-    if (!empty($sessionId)) {
-        $sessionList = array();
-        $sessionInfo = SessionManager::fetch($sessionId);
-        $sessionList[] = array('id' => $sessionInfo['id'], 'text' => $sessionInfo['name']);
-    }
-    $sessionFilter->addElement('select_ajax', 'session_name', get_lang('SearchCourseBySession'), null, array('url' => $url, 'defaults' => $sessionList));
-    $courseListUrl = api_get_self();
-
-    #show filter by session
-    if ($is_platform_admin && $view == 'admin' && in_array($display, array('accessoverview','lpprogressoverview'))) {
-        echo '<div class="pull-right">';
-        echo $sessionFilter->return_form();
-        echo '</div>';
-        echo '<script>$(function() {
-            $("#session_name").on("change", function() {
-               var sessionId = $(this).val();
-               window.location = "'.$courseListUrl.'?view=admin&display='.$display.'&session_id="+sessionId;
-            });
-            });</script>';
-    }
+    $sessionInfo = SessionManager::fetch($sessionId);
+    $sessionList[] = array('id' => $sessionInfo['id'], 'text' => $sessionInfo['name']);
+}
+$sessionFilter->addElement('select_ajax', 'session_name', get_lang('SearchCourseBySession'), null, array('url' => $url, 'defaults' => $sessionList));
+$courseListUrl = api_get_self();
+
+#show filter by session
+if ($is_platform_admin && $view == 'admin' && in_array($display, array('accessoverview','lpprogressoverview', 'progressoverview', 'exerciseprogress'))) {
+    echo '<div class="pull-right">';
+    echo $sessionFilter->return_form();
+    echo '</div>';
+    echo '<script>
+    $(function() {
+        $("#session_name").on("change", function() {
+           var sessionId = $(this).val();
+           window.location = "'.$courseListUrl.'?view=admin&display='.$display.'&session_id="+sessionId;
+        });
+    });
+    </script>';
+}
 
 echo '</div>';
 
 if (empty($session_id)) {
 
 	// Getting courses followed by a coach (No session courses)
-	$courses  = CourseManager::get_course_list_as_coach($user_id, false);
+    $courses  = CourseManager::get_course_list_as_coach($user_id, false);
 
-	if (isset($courses[0])) {
-		$courses = $courses[0];
-	}
-
-	// Getting students from courses and courses in sessions (To show the total students that the user follows)
-	$students = CourseManager::get_user_list_from_courses_as_coach($user_id);
-    /*$studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh', api_get_user_id());
-    $students = array();
-    foreach ($studentList as $studentData) {
-        $students[] = $studentData['user_id'];
-    }*/
+    if (isset($courses[0])) {
+        $courses = $courses[0];
+    }
 
-	// Sessions for the coach
-	$sessions = Tracking::get_sessions_coached_by_user($user_id);
+    // Getting students from courses and courses in sessions (To show the total students that the user follows)
+    $students = CourseManager::get_user_list_from_courses_as_coach($user_id);
 
-	// If is drh
-	if ($is_drh) {
+    // If is drh
+    if ($is_drh) {
         if (api_drh_can_access_all_session_content()) {
             $studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh_all', api_get_user_id());
 
@@ -265,27 +256,28 @@ if (empty($session_id)) {
             }
             $sessions = SessionManager::get_sessions_followed_by_drh($user_id);
         }
-	}
-
-    //var_dump(count($students));exit;
+    } else {
+        // Sessions for the coach
+        $sessions = Tracking::get_sessions_coached_by_user($user_id);
+    }
 
-	// Courses for the user
-	$count_courses = count($courses);
+    // Courses for the user
+    $count_courses = count($courses);
 
-	// Sessions for the user
-	$count_sessions = count($sessions);
+    // Sessions for the user
+    $count_sessions = count($sessions);
 
-	// Students
-	$nb_students = count($students);
+    // Students
+    $nb_students = count($students);
 
-	$total_time_spent 			= 0;
-	$total_courses 				= 0;
-	$avg_total_progress 		= 0;
-	$avg_results_to_exercises 	= 0;
-	$nb_inactive_students 		= 0;
-	$nb_posts = $nb_assignments = 0;
+    $total_time_spent 			= 0;
+    $total_courses 				= 0;
+    $avg_total_progress 		= 0;
+    $avg_results_to_exercises 	= 0;
+    $nb_inactive_students 		= 0;
+    $nb_posts = $nb_assignments = 0;
 
-	if (!empty($students)) {
+    if (!empty($students)) {
         foreach ($students as $student_id) {
             // inactive students
             $last_connection_date = Tracking :: get_last_connection_date($student_id, true, true);
@@ -310,8 +302,9 @@ if (empty($session_id)) {
                     $avg_student_progress  += Tracking :: get_avg_student_progress($student_id, $course_code);
                     $myavg_temp 			= Tracking :: get_avg_student_score($student_id, $course_code);
 
-                     if (is_numeric($myavg_temp))
+                     if (is_numeric($myavg_temp)) {
                         $avg_student_score += $myavg_temp;
+                     }
 
                     if ($nb_posts !== null && $nb_assignments !== null && $avg_student_progress !== null && $avg_student_score !== null) {
                         //if one of these scores is null, it means that we had a problem connecting to the right database, so don't count it in
@@ -329,55 +322,62 @@ if (empty($session_id)) {
         }
     }
 
-	if ($nb_students > 0 && $view != 'admin') {
-
-		// average progress
-		$avg_total_progress = $avg_total_progress / $nb_students;
-		// average results to the tests
-		$avg_results_to_exercises = $avg_results_to_exercises / $nb_students;
-		// average courses by student
-		$avg_courses_per_student = round($count_courses / $nb_students, 2);
-		// average time spent on the platform
-		$avg_time_spent = $total_time_spent / $nb_students;
-		// average assignments
-		$nb_assignments = $nb_assignments / $nb_students;
-		// average posts
-		$nb_posts = $nb_posts / $nb_students;
+    if ($nb_students > 0 && $view != 'admin') {
+
+        // average progress
+        $avg_total_progress = $avg_total_progress / $nb_students;
+        // average results to the tests
+        $avg_results_to_exercises = $avg_results_to_exercises / $nb_students;
+        // average courses by student
+        $avg_courses_per_student = round($count_courses / $nb_students, 2);
+        // average time spent on the platform
+        $avg_time_spent = $total_time_spent / $nb_students;
+        // average assignments
+        $nb_assignments = $nb_assignments / $nb_students;
+        // average posts
+        $nb_posts = $nb_posts / $nb_students;
 
         echo Display::page_subheader('<img src="'.api_get_path(WEB_IMG_PATH).'teachers.gif">&nbsp;'.get_lang('Overview'));
 
         echo '<div class="report_section">
-					<table class="table table-bordered">
+                    <table class="table table-bordered">
                         <tr>
-							<td>'.get_lang('FollowedUsers').'</td>
-							<td align="right">'.$nb_students.'</td>
-						</tr>
+                            <td>'.get_lang('FollowedUsers').'</td>
+                            <td align="right">'.$nb_students.'</td>
+                        </tr>
                         <tr>
-							<td>'.get_lang('FollowedCourses').'</td>
-							<td align="right">'.$count_courses.'</td>
-						</tr>
+                            <td>'.get_lang('FollowedCourses').'</td>
+                            <td align="right">'.$count_courses.'</td>
+                        </tr>
                         <tr>
-							<td>'.get_lang('FollowedSessions').'</td>
-							<td align="right">'.$count_sessions.'</td>
-						</tr>
+                            <td>'.get_lang('FollowedSessions').'</td>
+                            <td align="right">'.$count_sessions.'</td>
+                        </tr>
                         </table>';
         echo '</div>';
 
-		echo Display::page_subheader('<img src="'.api_get_path(WEB_IMG_PATH).'students.gif">
-		    &nbsp;'.get_lang('Students').' ('.$nb_students.')');
+        echo Display::page_subheader(Display::return_icon('students.gif').'&nbsp;'.get_lang('Students').' ('.$nb_students.')');
+
+        if ($export_csv) {
+            //csv part
+            $csv_content[] = array(get_lang('Students', ''));
+            $csv_content[] = array(get_lang('InactivesStudents', ''), $nb_inactive_students );
+            $csv_content[] = array(get_lang('AverageTimeSpentOnThePlatform', ''), $avg_time_spent);
+            $csv_content[] = array(get_lang('AverageCoursePerStudent', ''), $avg_courses_per_student);
+            $csv_content[] = array(get_lang('AverageProgressInLearnpath', ''), is_null($avg_total_progress) ? null : round($avg_total_progress, 2).'%');
+            $csv_content[] = array(get_lang('AverageResultsToTheExercices', ''), is_null($avg_results_to_exercises) ? null : round($avg_results_to_exercises, 2).'%');
+            $csv_content[] = array(get_lang('AveragePostsInForum', ''), $nb_posts);
+            $csv_content[] = array(get_lang('AverageAssignments', ''), $nb_assignments);
+            $csv_content[] = array();
+        } else {
 
-		if ($export_csv) {
-			//csv part
-			$csv_content[] = array(get_lang('Students', ''));
-			$csv_content[] = array(get_lang('InactivesStudents', ''), $nb_inactive_students );
-			$csv_content[] = array(get_lang('AverageTimeSpentOnThePlatform', ''), $avg_time_spent);
-			$csv_content[] = array(get_lang('AverageCoursePerStudent', ''), $avg_courses_per_student);
-			$csv_content[] = array(get_lang('AverageProgressInLearnpath', ''), is_null($avg_total_progress) ? null : round($avg_total_progress, 2).'%');
-			$csv_content[] = array(get_lang('AverageResultsToTheExercices', ''), is_null($avg_results_to_exercises) ? null : round($avg_results_to_exercises, 2).'%');
-			$csv_content[] = array(get_lang('AveragePostsInForum', ''), $nb_posts);
-			$csv_content[] = array(get_lang('AverageAssignments', ''), $nb_assignments);
-			$csv_content[] = array();
-		} else {
+            $countActiveUsers = SessionManager::getCountUserTracking(null, 1);
+            $countInactiveUsers = SessionManager::getCountUserTracking(null, 0);
+
+            $lastConnectionDate = api_get_utc_datetime(strtotime('15 days ago'));
+
+            $countSleepingTeachers = SessionManager::getTeacherTracking(api_get_user_id(), 1, $lastConnectionDate, true);
+            $countSleepingStudents =SessionManager::getCountUserTracking(null, 1, $lastConnectionDate);
 
             $form = new FormValidator('search_user', 'get', api_get_path(WEB_CODE_PATH).'mySpace/student.php');
             $form->addElement('text', 'keyword', get_lang('User'));
@@ -385,60 +385,76 @@ if (empty($session_id)) {
             $form->display();
 
             // html part
-			echo '<div class="report_section">
-					<table class="table table-bordered">
+            echo '<div class="report_section">
+                    <table class="table table-bordered">
                         <tr>
-							<td>'.get_lang('AverageCoursePerStudent').'</td>
-							<td align="right">'.(is_null($avg_courses_per_student) ? '' : $avg_courses_per_student).'</td>
-						</tr>
+                            <td>'.Display::url(get_lang('ActiveUsers'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?active=1').'</td>
+                            <td align="right">'.$countActiveUsers.'</td>
+                        </tr>
+
                         <tr>
-							<td>'.get_lang('InactivesStudents').'</td>
-							<td align="right">'.$nb_inactive_students.'</td>
-						</tr>
-						<tr>
-							<td>'.get_lang('AverageTimeSpentOnThePlatform').'</td>
-							<td align="right">'.(is_null($avg_time_spent) ? '' : api_time_to_hms($avg_time_spent)).'</td>
-						</tr>
-						<tr>
-							<td>'.get_lang('AverageProgressInLearnpath').'</td>
-							<td align="right">'.(is_null($avg_total_progress) ? '' : round($avg_total_progress, 2).'%').'</td>
-						</tr>
-						<tr>
-							<td>'.get_lang('AvgCourseScore').'</td>
-							<td align="right">'.(is_null($avg_results_to_exercises) ? '' : round($avg_results_to_exercises, 2).'%').'</td>
-						</tr>
-						<tr>
-							<td>'.get_lang('AveragePostsInForum').'</td>
-							<td align="right">'.(is_null($nb_posts) ? '' : round($nb_posts, 2)).'</td>
-						</tr>
-						<tr>
-							<td>'.get_lang('AverageAssignments').'</td>
-							<td align="right">'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'</td>
-						</tr>
-					</table>
-					<a class="btn" href="student.php">
-					'.get_lang('SeeStudentList').'
-					</a>
-				 </div><br />';
-		}
-	} else {
-		$avg_total_progress = null;
-		$avg_results_to_exercises = null;
-		$avg_courses_per_student = null;
-		$avg_time_spent = null;
-		$nb_assignments = null;
-		$nb_posts = null;
-	}
-} else {
-	$courses = Tracking::get_courses_followed_by_coach($user_id, $session_id);
+                            <td>'.Display::url(get_lang('InactiveUsers'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?active=0').'</td>
+                            <td align="right">'.$countInactiveUsers.'</td>
+                        </tr>
 
+                        <tr>
+                            <td>'.Display::url(get_lang('SleepingTeachers'), api_get_path(WEB_CODE_PATH).'mySpace/teachers.php?sleeping_days=15').'</td>
+                            <td align="right">'.$countSleepingTeachers.'</td>
+                        </tr>
+                        <tr>
+                            <td>'.Display::url(get_lang('SleepingStudents'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?sleeping_days=15').'</td>
+                            <td align="right">'.$countSleepingStudents.'</td>
+                        </tr>
+
+                        <tr>
+                            <td>'.get_lang('AverageCoursePerStudent').'</td>
+                            <td align="right">'.(is_null($avg_courses_per_student) ? '' : $avg_courses_per_student).'</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('InactivesStudents').'</td>
+                            <td align="right">'.$nb_inactive_students.'</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('AverageTimeSpentOnThePlatform').'</td>
+                            <td align="right">'.(is_null($avg_time_spent) ? '' : api_time_to_hms($avg_time_spent)).'</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('AverageProgressInLearnpath').'</td>
+                            <td align="right">'.(is_null($avg_total_progress) ? '' : round($avg_total_progress, 2).'%').'</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('AvgCourseScore').'</td>
+                            <td align="right">'.(is_null($avg_results_to_exercises) ? '' : round($avg_results_to_exercises, 2).'%').'</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('AveragePostsInForum').'</td>
+                            <td align="right">'.(is_null($nb_posts) ? '' : round($nb_posts, 2)).'</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('AverageAssignments').'</td>
+                            <td align="right">'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'</td>
+                        </tr>
+                    </table>
+                    <a class="btn" href="'.api_get_path(WEB_CODE_PATH).'mySpace/student.php'.'">
+                    '.get_lang('SeeStudentList').'
+                    </a>
+                 </div><br />';
+        }
+    } else {
+        $avg_total_progress = null;
+        $avg_results_to_exercises = null;
+        $avg_courses_per_student = null;
+        $avg_time_spent = null;
+        $nb_assignments = null;
+        $nb_posts = null;
+    }
+} else {
     // If is drh
 	if ($is_drh) {
         $courses_of_the_platform = CourseManager::get_courses_followed_by_drh($user_id);
         $courses_from_session = SessionManager::get_course_list_by_session_id($session_id);
 
         $courses = array();
-
         foreach ($courses_from_session as $course_item) {
             if (api_drh_can_access_all_session_content()) {
                 $courses[$course_item['code']] = $course_item['code'];
@@ -452,7 +468,9 @@ if (empty($session_id)) {
         if (empty($courses)) {
             Display::display_warning_message(get_lang('NoResults'));
         }
-	}
+	} else {
+        $courses = Tracking::get_courses_followed_by_coach($user_id, $session_id);
+    }
 
     //Courses for the user
     $count_courses = count($courses);
@@ -465,7 +483,7 @@ if ($count_courses || $count_sessions) {
 	//If we are in course
 	if (empty($session_id)) {
 		if ($count_courses) {
-			$title = '<img src="'.api_get_path(WEB_IMG_PATH).'course.gif"> '.get_lang('Courses').' ('.$count_courses.') ';
+			$title = Display::return_icon('course.gif').' '.get_lang('Courses').' ('.$count_courses.') ';
 		}
 	} else {
 		//If we are in Course Session
@@ -512,68 +530,38 @@ if ((api_is_allowed_to_create_course() || api_is_drh()) && in_array($view, array
 	// Display list of sessions
 
 	if ($count_sessions > 0 && !isset($_GET['session_id'])) {
-		echo Display::page_subheader('<img src="'.api_get_path(WEB_IMG_PATH).'session.png">&nbsp;'.get_lang('Sessions').' ('.$count_sessions.')');
-
-		$table = new SortableTable('tracking_sessions_myspace', 'count_sessions_coached');
-		$table->set_header(0, get_lang('Title'), false);
-        $table->set_header(1, get_lang('Date'), false);
-        $table->set_header(2, get_lang('NbCoursesPerSession'), false);
-		$table->set_header(3, get_lang('NbStudentPerSession'), false);
-		$table->set_header(4, get_lang('Details'), false);
-
-		$all_data = array();
-		foreach ($sessions as $session) {
-            if (api_drh_can_access_all_session_content()) {
-                $count_courses_in_session = count(SessionManager::get_course_list_by_session_id($session['id']));
-            } else {
-                $count_courses_in_session = count(Tracking::get_courses_followed_by_coach($user_id, $session['id']));
-            }
-
-            $count_users_in_session = count(SessionManager::get_users_by_session($session['id'], 0));
-			$row = array();
-			$row[] = $session['name'];
-
-            $session_date = array();
-			if (!empty($session['date_start']) && $session['date_start'] != '0000-00-00') {
-                $session_date[] = get_lang('From').' '.api_format_date($session['date_start'], DATE_FORMAT_SHORT);
-            }
-
-            if (!empty($session['date_end']) && $session['date_end'] != '0000-00-00') {
-                $session_date[] = get_lang('Until').' '.api_format_date($session['date_end'], DATE_FORMAT_SHORT);
-            }
-
-            if (empty($session_date)) {
-                $session_date_string = '-';
-            } else {
-                $session_date_string = implode(' ', $session_date);
-            }
-
-            $row[] = $session_date_string;
-            $row[] = $count_courses_in_session;
-            $row[] = $count_users_in_session;
-			$row[] = '<a href="'.api_get_self().'?session_id='.$session['id'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-			$all_data[] = $row;
-		}
-
-		if (!isset($tracking_column)) {
-			$tracking_column = 0;
-		}
-
-		if (isset($_GET['tracking_direction']) &&  $_GET['tracking_direction'] == 'DESC') {
-			usort($all_data, 'rsort_sessions');
-		} else {
-			usort($all_data, 'sort_sessions');
-		}
-
-		if ($export_csv) {
-			usort($csv_content, 'sort_sessions');
-		}
-
-		foreach ($all_data as $row) {
-			$table -> addRow($row);
-		}
-
-		/*  Start session over view stats */
+		echo Display::page_subheader(Display::return_icon('session.png').' '.get_lang('Sessions').' ('.$count_sessions.')');
+
+        $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions_tracking';
+
+        //The order is important you need to check the the $column variable in the model.ajax.php file
+        $columns = array(
+            get_lang('Title'),
+            get_lang('Date'),
+            get_lang('NbCoursesPerSession'),
+            get_lang('NbStudentPerSession'),
+            get_lang('Details')
+        );
+
+        // Column config
+        $columnModel   = array(
+            array('name'=>'name',               'index'=>'name',        'width'=>'255',   'align'=>'left'),
+            array('name'=>'date',                'index'=>'date', 'width'=>'150',  'align'=>'left','sortable'=>'false'),
+            array('name'=>'course_per_session',  'index'=>'course_per_session',     'width'=>'150','sortable'=>'false'),
+            array('name'=>'student_per_session', 'index'=>'student_per_session',     'width'=>'100','sortable'=>'false'),
+            array('name'=>'details',             'index'=>'details',     'width'=>'100','sortable'=>'false'),
+        );
+
+        $extraParams = array(
+            'autowidth' => 'true',
+            'height' => 'auto'
+        );
+
+        $js = '<script>
+        $(function() {
+            '.Display::grid_js('session_tracking', $url, $columns, $columnModel, $extraParams, array(), null, true).'
+        });
+        </script>';
 
 		$nb_sessions_past = $nb_sessions_current = 0;
 		$courses = array();
@@ -601,7 +589,6 @@ if ((api_is_allowed_to_create_course() || api_is_drh()) && in_array($view, array
 			$csv_content[] = array(get_lang('Sessions', ''));
 			$csv_content[] = array(get_lang('NbActiveSessions', '').';'.$nb_sessions_current);
 			$csv_content[] = array(get_lang('NbInactiveSessions', '').';'.$nb_sessions_past);
-			//$csv_content[] = array(get_lang('NbFutureSessions', '').';'.$nb_sessions_future);
             $csv_content[] = array(get_lang('NbCoursesPerSession', '').';'.$nb_courses_per_session);
 			$csv_content[] = array(get_lang('NbStudentPerSession', '').';'.$nb_students_per_session);
 			$csv_content[] = array();
@@ -620,9 +607,9 @@ if ((api_is_allowed_to_create_course() || api_is_drh()) && in_array($view, array
 				</table>
 			</div>';
 		}
-		/*  End session overview */
-		$table -> display();
-	}
+        echo $js;
+        echo Display::grid_html('session_tracking');
+    }
 }
 
 if ($is_platform_admin && in_array($view, array('admin')) && $display != 'yourstudents') {
@@ -634,13 +621,14 @@ if ($is_platform_admin && in_array($view, array('admin')) && $display != 'yourst
 	}
 	echo ' | <a href="'.api_get_self().'?view=admin&amp;display=sessionoverview">'.get_lang('DisplaySessionOverview').'</a>';
 	echo ' | <a href="'.api_get_self().'?view=admin&amp;display=accessoverview">'.get_lang('DisplayAccessOverview').'</a>';
-    echo ' | <a href="'.api_get_self().'?view=admin&amp;display=lpprogressoverview">'.get_lang('Displaylpprogressoverview').'</a>';
+    echo ' | <a href="'.api_get_self().'?view=admin&amp;display=lpprogressoverview">'.get_lang('DisplayLpProgressOverview').'</a>';
+    echo ' | <a href="'.api_get_self().'?view=admin&amp;display=progressoverview">'.get_lang('DisplayProgressOverview').'</a>';
+    echo ' | <a href="'.api_get_self().'?view=admin&amp;display=exerciseprogress">'.get_lang('DisplayExerciseProgress').'</a>';
 	echo ' | <a href="'.api_get_self().'?view=admin&amp;display=courseoverview">'.get_lang('DisplayCourseOverview').'</a>';
     echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'tracking/question_course_report.php?view=admin">'.get_lang('LPQuestionListResults').'</a>';
     echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'tracking/course_session_report.php?view=admin">'.get_lang('LPExerciseResultsBySession').'</a>';
-
-
 	echo '<br /><br />';
+
 	if ($display === 'useroverview') {
 		MySpace::display_tracking_user_overview();
 	} else if($display == 'sessionoverview') {
@@ -653,7 +641,19 @@ if ($is_platform_admin && in_array($view, array('admin')) && $display != 'yourst
         }
     } else if($display == 'lpprogressoverview') {
         if (!empty($_GET['session_id'])) {
-            echo MySpace::display_tracking_lp_progress_overview($_GET['session_id']);
+            echo MySpace::display_tracking_lp_progress_overview(intval($_GET['session_id']));
+        } else {
+            Display::display_warning_message(get_lang('ChooseSession'));
+        }
+    } else if($display == 'progressoverview') {
+        if (!empty($_GET['session_id'])) {
+            echo MySpace::display_tracking_progress_overview(intval($_GET['session_id']));
+        } else {
+            Display::display_warning_message(get_lang('ChooseSession'));
+        }
+    } else if($display == 'exerciseprogress') {
+        if (!empty($_GET['session_id'])) {
+            echo MySpace::display_tracking_exercise_progress_overview(intval($_GET['session_id']));
         } else {
             Display::display_warning_message(get_lang('ChooseSession'));
         }
@@ -678,18 +678,18 @@ if ($is_platform_admin && in_array($view, array('admin')) && $display != 'yourst
 		$parameters['view'] = 'admin';
 		$table->set_additional_parameters($parameters);
 		if ($is_western_name_order) {
-			$table -> set_header(0, get_lang('FirstName'), true);
-			$table -> set_header(1, get_lang('LastName'), true);
+			$table->set_header(0, get_lang('FirstName'), true);
+			$table->set_header(1, get_lang('LastName'), true);
 		} else {
-			$table -> set_header(0, get_lang('LastName'), true);
-			$table -> set_header(1, get_lang('FirstName'), true);
+			$table->set_header(0, get_lang('LastName'), true);
+			$table->set_header(1, get_lang('FirstName'), true);
 		}
-		$table -> set_header(2, get_lang('TimeSpentOnThePlatform'), false);
-		$table -> set_header(3, get_lang('LastConnexion'), false);
-		$table -> set_header(4, get_lang('NbStudents'), false);
-		$table -> set_header(5, get_lang('CountCours'), false);
-		$table -> set_header(6, get_lang('NumberOfSessions'), false);
-		$table -> set_header(7, get_lang('Sessions'), false);
+		$table->set_header(2, get_lang('TimeSpentOnThePlatform'), false);
+		$table->set_header(3, get_lang('LastConnexion'), false);
+		$table->set_header(4, get_lang('NbStudents'), false);
+		$table->set_header(5, get_lang('CountCours'), false);
+		$table->set_header(6, get_lang('NumberOfSessions'), false);
+		$table->set_header(7, get_lang('Sessions'), false);
 
 		if ($is_western_name_order) {
 			$csv_header[] = array (
@@ -830,13 +830,13 @@ if ($is_platform_admin && in_array($view, array('admin')) && $display != 'yourst
 		}
 
 		foreach ($all_datas as $row) {
-			$table -> addRow($row, 'align="right"');
+			$table->addRow($row, 'align="right"');
 		}
-		$table -> display();
+		$table->display();
 	}
 }
 
-// send the csv file if asked
+// Send the csv file if asked
 if ($export_csv) {
 	ob_end_clean();
 	Export :: export_table_csv($csv_content, 'reporting_index');
@@ -847,6 +847,7 @@ if ($export_csv) {
 if (!$export_csv) {
 	Display::display_footer();
 }
+
 /**
  * Get number of courses for sortable with pagination
  * @return int

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