Browse Source

Merge from 1.11.x

jmontoyaa 8 years ago
parent
commit
9d3aa0c0ac
37 changed files with 887 additions and 585 deletions
  1. 1 1
      main/admin/configure_inscription.php
  2. 67 36
      main/auth/external_login/ldap.inc.php
  3. 5 2
      main/auth/external_login/login.ldap.php
  4. 3 3
      main/cron/import_csv.php
  5. 125 86
      main/document/document.php
  6. 45 29
      main/exercise/exercise.class.php
  7. 70 35
      main/exercise/exercise_submit.php
  8. 30 29
      main/exercise/fill_blanks.class.php
  9. 43 32
      main/forum/forumfunction.inc.php
  10. 2 1
      main/forum/viewforumcategory.php
  11. 1 1
      main/gradebook/lib/GradebookUtils.php
  12. 23 0
      main/inc/ajax/document.ajax.php
  13. 1 3
      main/inc/ajax/exercise.ajax.php
  14. 33 0
      main/inc/ajax/message.ajax.php
  15. 3 0
      main/inc/ajax/online.ajax.php
  16. 0 1
      main/inc/global.inc.php
  17. 3 7
      main/inc/lib/MoodleImport.php
  18. 52 7
      main/inc/lib/api.lib.php
  19. 4 5
      main/inc/lib/banner.lib.php
  20. 86 87
      main/inc/lib/display.lib.php
  21. 132 113
      main/inc/lib/document.lib.php
  22. 12 14
      main/inc/lib/exercise.lib.php
  23. 1 1
      main/inc/lib/extra_field.lib.php
  24. 1 1
      main/inc/lib/internationalization.lib.php
  25. 6 3
      main/inc/lib/usermanager.lib.php
  26. 2 1
      main/inc/lib/userportal.lib.php
  27. 2 0
      main/install/configuration.dist.php
  28. 1 1
      main/lp/learnpathItem.class.php
  29. 14 4
      main/mySpace/myStudents.php
  30. 6 2
      plugin/google_maps/lang/en.php
  31. 6 2
      plugin/google_maps/lang/es.php
  32. 6 2
      plugin/google_maps/lang/fr.php
  33. 16 3
      plugin/google_maps/src/map_coordinates.php
  34. 70 68
      plugin/google_maps/view/map_coordinates.tpl
  35. 0 1
      src/Chamilo/CoreBundle/Entity/Session.php
  36. 11 1
      src/Chamilo/CoreBundle/Resources/views/default/layout/page_header.html.twig
  37. 4 3
      src/Chamilo/CourseBundle/Component/CourseCopy/CourseBuilder.php

+ 1 - 1
main/admin/configure_inscription.php

@@ -312,7 +312,7 @@ if (api_get_setting('allow_terms_conditions') == 'true') {
             null,
             get_lang('IHaveReadAndAgree').'&nbsp;<a href="inscription.php?legal" target="_blank">'.get_lang('TermsAndConditions').'</a>'
         );
-        $form->addRule('extra_legal_accept', get_lang('ThisFieldIsRequired'), 'required');
+        $form->addRule('legal_accept', get_lang('ThisFieldIsRequired'), 'required');
     } else {
         if (!empty($term_preview['content'])) {
             $preview = LegalManager::show_last_condition($term_preview);

+ 67 - 36
main/auth/external_login/ldap.inc.php

@@ -1,13 +1,14 @@
 <?php
-
 // External login module : LDAP
+
 /**
  * This files is included by newUser.ldap.php and login.ldap.php
  * It implements the functions nedded by both files
  * */
-//Includes the configuration file
 require_once dirname(__FILE__).'/../../inc/global.inc.php';
 
+$debug = false;
+
 /**
  * Returns a transcoded and trimmed string
  *
@@ -33,7 +34,7 @@ function extldap_purify_string($string)
  * */
 function extldap_connect()
 {
-    global $extldap_config;
+    global $extldap_config, $debug;
 
     if (!is_array($extldap_config['host'])) {
         $extldap_config['host'] = array($extldap_config['host']);
@@ -48,23 +49,29 @@ function extldap_connect()
         }
         if (!$ds) {
             $port = isset($extldap_config['port']) ? $extldap_config['port'] : 389;
-            error_log('EXTLDAP ERROR : cannot connect to '.$extldap_config['host'].':'.$port);
+            if ($debug) {
+                error_log(
+                    'EXTLDAP ERROR : cannot connect to '.$extldap_config['host'].':'.$port
+                );
+            }
         } else {
             break;
         }
     }
     if (!$ds) {
-        error_log('EXTLDAP ERROR : no valid server found');
+        if ($debug) {
+            error_log('EXTLDAP ERROR : no valid server found');
+        }
         return false;
     }
-    //Setting protocol version
+    // Setting protocol version
     if (isset($extldap_config['protocol_version'])) {
         if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $extldap_config['protocol_version'])) {
             ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 2);
         }
     }
 
-    //Setting protocol version
+    // Setting protocol version
     if (isset($extldap_config['referrals'])) {
         if (!ldap_set_option($ds, LDAP_OPT_REFERRALS, $extldap_config['referrals'])) {
             ldap_set_option($ds, LDAP_OPT_REFERRALS, $extldap_config['referrals']);
@@ -86,9 +93,9 @@ function extldap_connect()
  * */
 function extldap_authenticate($username, $password, $in_auth_with_no_password = false)
 {
-    global $extldap_config;
+    global $extldap_config, $debug;
 
-    if (empty($username) or empty($password)) {
+    if (empty($username) || empty($password)) {
         return false;
     }
 
@@ -97,46 +104,62 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
         return false;
     }
 
-    //Connection as admin to search dn of user
+    // Connection as admin to search dn of user
     $ldapbind = @ldap_bind($ds, $extldap_config['admin_dn'], $extldap_config['admin_password']);
     if ($ldapbind === false) {
-        error_log('EXTLDAP ERROR : cannot connect with admin login/password');
+        if ($debug) {
+            error_log(
+                'EXTLDAP ERROR : cannot connect with admin login/password'
+            );
+        }
         return false;
     }
     $user_search = extldap_get_user_search_string($username);
-    //Search distinguish name of user
+    // Search distinguish name of user
     $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
     if (!$sr) {
-        error_log('EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed");
+        if ($debug) {
+            error_log(
+                'EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed"
+            );
+        }
         return false;
     }
+
     $entries_count = ldap_count_entries($ds, $sr);
 
     if ($entries_count > 1) {
-        error_log(
-            'EXTLDAP ERROR : more than one entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
-        );
+        if ($debug) {
+            error_log(
+                'EXTLDAP ERROR : more than one entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
+            );
+        }
         return false;
     }
     if ($entries_count < 1) {
-        error_log(
-            'EXTLDAP ERROR :  No entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
-        );
+        if ($debug) {
+            error_log(
+                'EXTLDAP ERROR :  No entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
+            );
+        }
         return false;
     }
     $users = ldap_get_entries($ds, $sr);
-    $user  = $users[0];
+    $user = $users[0];
 
     // If we just want to have user info from LDAP and not to check password
     if ($in_auth_with_no_password) {
         return $user;
     }
-    //now we try to autenthicate the user in the ldap
+
+    // now we try to autenthicate the user in the ldap
     $ubind = @ldap_bind($ds, $user['dn'], $password);
     if ($ubind !== false) {
         return $user;
     } else {
-        error_log('EXTLDAP : Wrong password for '.$user['dn']);
+        if ($debug) {
+            error_log('EXTLDAP : Wrong password for '.$user['dn']);
+        }
         return false;
     }
 }
@@ -152,7 +175,7 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
  * */
 function extldap_get_chamilo_user($ldap_user, $cor = null)
 {
-    global $extldap_user_correspondance;
+    global $extldap_user_correspondance, $debug;
     if (is_null($cor)) {
         $cor = $extldap_user_correspondance;
     }
@@ -170,7 +193,11 @@ function extldap_get_chamilo_user($ldap_user, $cor = null)
                 if (function_exists($func)) {
                     $chamilo_user[$chamilo_field] = extldap_purify_string($func($ldap_user));
                 } else {
-                    error_log("EXTLDAP WARNING : You forgot to declare $func");
+                    if ($debug) {
+                        error_log(
+                            "EXTLDAP WARNING : You forgot to declare $func"
+                        );
+                    }
                 }
                 break;
             default:
@@ -182,7 +209,11 @@ function extldap_get_chamilo_user($ldap_user, $cor = null)
                 if (isset($ldap_user[$ldap_field][0])) {
                     $chamilo_user[$chamilo_field] = extldap_purify_string($ldap_user[$ldap_field][0]);
                 } else {
-                    //error_log('EXTLDAP WARNING : '.$ldap_field.'[0] field is not set in ldap array');
+                    if ($debug) {
+                        error_log(
+                            'EXTLDAP WARNING : '.$ldap_field.'[0] field is not set in ldap array'
+                        );
+                    }
                 }
                 break;
         }
@@ -196,14 +227,6 @@ function extldap_get_chamilo_user($ldap_user, $cor = null)
  * array returned by the ldap for the user
  * */
 
-/**
- * example function for email
- * */
-/*
-  function extldap_get_email($ldap_user){
-  return $ldap_user['cn'].$ldap['sn'].'@gmail.com';
-  }
- */
 function extldap_get_status($ldap_user)
 {
     return STUDENT;
@@ -242,7 +265,7 @@ function extldap_get_user_search_string($username)
  */
 function extldap_import_all_users()
 {
-    global $extldap_config;
+    global $extldap_config, $debug;
     //echo "Connecting...\n";
     $ds = extldap_connect();
     if (!$ds) {
@@ -253,7 +276,11 @@ function extldap_import_all_users()
     //Connection as admin to search dn of user
     $ldapbind = @ldap_bind($ds, $extldap_config['admin_dn'], $extldap_config['admin_password']);
     if ($ldapbind === false) {
-        error_log('EXTLDAP ERROR : cannot connect with admin login/password');
+        if ($debug) {
+            error_log(
+                'EXTLDAP ERROR : cannot connect with admin login/password'
+            );
+        }
         return false;
     }
     //browse ASCII values from a to z to avoid 1000 results limit of LDAP
@@ -269,7 +296,11 @@ function extldap_import_all_users()
             //Search distinguish name of user
             $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
             if (!$sr) {
-                error_log('EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed");
+                if ($debug) {
+                    error_log(
+                        'EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed"
+                    );
+                }
                 return false;
             }
             //echo "Getting entries\n";

+ 5 - 2
main/auth/external_login/login.ldap.php

@@ -42,6 +42,7 @@ use ChamiloSession as Session;
 
 require_once dirname(__FILE__) . '/ldap.inc.php';
 require_once dirname(__FILE__) . '/functions.inc.php';
+
 $debug = false;
 if ($debug) {
     error_log('Entering login.ldap.php');
@@ -58,7 +59,7 @@ if ($ldap_user !== false) {
         error_log("chamilo_user found user_id: {$uData['user_id']}");
     }
 
-    //Update user info
+    //U pdate user info
     if (isset($extldap_config['update_userinfo']) && $extldap_config['update_userinfo']) {
         external_update_user($chamilo_user);
         if ($debug) {
@@ -75,7 +76,9 @@ if ($ldap_user !== false) {
     $logging_in = true;
     Event::event_login($_user['user_id']);
 } else {
-    error_log('extldap_authenticate error');
+    if ($debug) {
+        error_log('extldap_authenticate error');
+    }
     $loginFailed = true;
     $uidReset = false;
     if (isset($_user) && isset($_user['user_id'])) {

+ 3 - 3
main/cron/import_csv.php

@@ -1457,15 +1457,15 @@ class ImportCsv
                     $date->sub($interval);
                     $coachBefore = $date->format('Y-m-d h:i');
 
-                    $date = new \DateTime($dateStart);
+                    $date = new \DateTime($dateEnd);
                     $interval = new DateInterval('P'.$this->daysCoachAccessAfterBeginning.'D');
                     $date->add($interval);
                     $coachAfter = $date->format('Y-m-d h:i');
 
-                    $dateStart = api_get_utc_datetime($dateStart);
+                    /*$dateStart = api_get_utc_datetime($dateStart);
                     $dateEnd = api_get_utc_datetime($dateEnd);
                     $coachBefore = api_get_utc_datetime($coachBefore);
-                    $coachAfter = api_get_utc_datetime($coachAfter);
+                    $coachAfter = api_get_utc_datetime($coachAfter);*/
 
                     if (empty($sessionId)) {
                         $result = SessionManager::create_session(

+ 125 - 86
main/document/document.php

@@ -91,7 +91,6 @@ $sys_course_path = api_get_path(SYS_COURSE_PATH);
 $base_work_dir = $sys_course_path.$course_dir;
 $http_www = api_get_path(WEB_COURSE_PATH).$courseInfo['directory'].'/document';
 $document_path = $base_work_dir;
-
 $currentUrl = api_get_self().'?'.api_get_cidreq();
 
 // Removing sessions
@@ -115,13 +114,14 @@ if ($capturePluginInstalled) {
     });
     </script>';
 }
-// Create directory certificates.
-DocumentManager::create_directory_certificate_in_course(api_get_course_id());
 
 if (empty($courseInfo)) {
     api_not_allowed(true);
 }
 
+// Create directory certificates.
+DocumentManager::create_directory_certificate_in_course($courseInfo);
+
 // Used for avoiding double-click.
 $dbl_click_id = 0;
 $selectcat = isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']) : null;
@@ -133,7 +133,7 @@ $userInfo = api_get_user_info();
 $sessionId = api_get_session_id();
 $course_code = api_get_course_id();
 $groupId = api_get_group_id();
-$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
+$isAllowedToEdit = api_is_allowed_to_edit(null, true);
 $group_member_with_upload_rights = false;
 
 // If the group id is set, we show them group documents
@@ -146,8 +146,19 @@ if (api_get_session_id() != 0) {
 }
 
 // Get group info
+$groupIid = 0;
+$groupMemberWithEditRights = false;
+
+// Setting group variables.
+if (!empty($groupId)) {
 $group_properties = GroupManager::get_group_properties($groupId);
 $groupIid = isset($group_properties['iid']) ? $group_properties['iid'] : 0;
+$isTutorGroup = GroupManager::is_tutor_of_group(
+    $userId,
+    $group_properties['iid'],
+    $courseId
+);
+$groupMemberWithEditRights = $isAllowedToEdit || $isTutorGroup;
 
 $groupMemberWithEditRights = $is_allowed_to_edit || GroupManager::is_tutor_of_group($userId, $group_properties['iid'], $courseId);
 
@@ -158,7 +169,7 @@ if (!empty($groupId)) {
 
     if ($group_properties['doc_state'] == 2) {
         // Documents are private
-        if ($is_allowed_to_edit || GroupManager::is_user_in_group($userId, $group_properties['iid'])) {
+        if ($isAllowedToEdit || GroupManager::is_user_in_group($userId, $group_properties['iid'])) {
             // Only courseadmin or group members (members + tutors) allowed
             $interbreadcrumb[] = array(
                 'url' => api_get_path(WEB_CODE_PATH).'group/group.php?'.api_get_cidreq(),
@@ -185,7 +196,7 @@ if (!empty($groupId)) {
         );
 
         // Allowed to upload?
-        if ($is_allowed_to_edit ||
+        if ($isAllowedToEdit ||
             GroupManager::is_subscribed($userId, $group_properties['iid']) ||
             GroupManager::is_tutor_of_group($userId, $group_properties['iid'], $courseId)
         ) {
@@ -206,13 +217,13 @@ $curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpat
 
 switch ($action) {
     case 'delete_item':
-        if ($is_allowed_to_edit ||
+        if ($isAllowedToEdit ||
             $group_member_with_upload_rights ||
             DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId) ||
             DocumentManager::is_my_shared_folder(api_get_user_id(), $moveTo, $sessionId)
         ) {
             if (isset($_GET['deleteid'])) {
-                if (!$is_allowed_to_edit) {
+                if (!$isAllowedToEdit) {
                     if (api_is_coach()) {
                         if (!DocumentManager::is_visible_by_id(
                             $_GET['deleteid'],
@@ -302,7 +313,7 @@ switch ($action) {
         // Launch event
         Event::event_download($document_data['url']);
         // Check visibility of document and paths
-        if (!($is_allowed_to_edit || $group_member_with_upload_rights)
+        if (!($isAllowedToEdit || $group_member_with_upload_rights)
             && !DocumentManager::is_visible_by_id($document_id, $courseInfo, $sessionId, api_get_user_id())) {
             api_not_allowed(true);
         }
@@ -317,7 +328,7 @@ switch ($action) {
         break;
     case 'downloadfolder':
         if (api_get_setting('students_download_folders') == 'true'
-            || api_is_allowed_to_edit()
+            || $isAllowedToEdit
             || api_is_platform_admin()
         ) {
             // Get the document data from the ID
@@ -343,7 +354,7 @@ switch ($action) {
             //filter when I am into shared folder, I can download only my shared folder
             if (DocumentManager::is_any_user_shared_folder($document_data['path'], $sessionId)) {
                 if (DocumentManager::is_my_shared_folder(api_get_user_id(), $document_data['path'], $sessionId)
-                    || api_is_allowed_to_edit()
+                    || $isAllowedToEdit
                     || api_is_platform_admin()) {
                     require 'downloadfolder.inc.php';
                 }
@@ -356,7 +367,7 @@ switch ($action) {
         }
         break;
     case 'export_to_pdf':
-        if (api_get_setting('students_export2pdf') == 'true' || api_is_allowed_to_edit() || api_is_platform_admin()) {
+        if (api_get_setting('students_export2pdf') == 'true' || $isAllowedToEdit || api_is_platform_admin()) {
             DocumentManager::export_to_pdf($document_id, $course_code);
         }
         break;
@@ -588,7 +599,7 @@ if (isset($document_id) && empty($action)) {
             }
             exit;
         } else {
-            if (!$visibility && !api_is_allowed_to_edit()) {
+            if (!$visibility && !$isAllowedToEdit) {
                 api_not_allowed();
             }
         }
@@ -776,9 +787,9 @@ if ($groupId != 0 && $curdirpath == '/') {
 
 // Check visibility of the current dir path. Don't show anything if not allowed
 //@todo check this validation for coaches
-//if (!$is_allowed_to_edit || api_is_coach()) { before
+//if (!$isAllowedToEdit || api_is_coach()) { before
 
-if (!$is_allowed_to_edit && api_is_coach()) {
+if (!$isAllowedToEdit && api_is_coach()) {
     if ($curdirpath != '/' && !(DocumentManager::is_visible($curdirpath, $courseInfo, $sessionId, 'folder'))) {
         api_not_allowed(true);
     }
@@ -921,7 +932,7 @@ $documentAndFolders = DocumentManager::get_all_document_data(
     $curdirpath,
     $groupIid,
     null,
-    $is_allowed_to_edit || $group_member_with_upload_rights,
+    $isAllowedToEdit || $group_member_with_upload_rights,
     false
 );
 
@@ -992,7 +1003,7 @@ $moveForm = '';
 
 /* 	MOVE FILE OR DIRECTORY */
 //Only teacher and all users into their group and each user into his/her shared folder
-if ($is_allowed_to_edit ||
+if ($isAllowedToEdit ||
     $group_member_with_upload_rights ||
     DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId) ||
     DocumentManager::is_my_shared_folder(api_get_user_id(), $moveTo, $sessionId)
@@ -1006,7 +1017,7 @@ if ($is_allowed_to_edit ||
             }
         }
 
-        if (!$is_allowed_to_edit) {
+        if (!$isAllowedToEdit) {
             if (DocumentManager::check_readonly($courseInfo, api_get_user_id(), $my_get_move)) {
                 api_not_allowed(true);
             }
@@ -1024,14 +1035,14 @@ if ($is_allowed_to_edit ||
             $folders = DocumentManager::get_all_document_folders(
                 $courseInfo,
                 $groupIid,
-                $is_allowed_to_edit || $group_member_with_upload_rights,
+                $isAllowedToEdit || $group_member_with_upload_rights,
                 false,
                 $curdirpath
             );
 
             // filter if is my shared folder. TODO: move this code to build_move_to_selector function
             if (DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId) &&
-                !$is_allowed_to_edit
+                !$isAllowedToEdit
             ) {
                 //only main user shared folder
                 $main_user_shared_folder_main = '/shared_folder/sf_user_'.api_get_user_id();
@@ -1064,7 +1075,7 @@ if ($is_allowed_to_edit ||
     }
 
     if (!empty($moveTo) && isset($_POST['move_file'])) {
-        if (!$is_allowed_to_edit) {
+        if (!$isAllowedToEdit) {
             if (DocumentManager::check_readonly($courseInfo, api_get_user_id(), $_POST['move_file'])) {
                 api_not_allowed(true);
             }
@@ -1155,7 +1166,7 @@ if ($is_allowed_to_edit ||
 
 /* 	DELETE FILE OR DIRECTORY */
 //Only teacher and all users into their group
-if ($is_allowed_to_edit ||
+if ($isAllowedToEdit ||
     $group_member_with_upload_rights ||
     DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)
 ) {
@@ -1223,7 +1234,7 @@ if ($is_allowed_to_edit ||
                         // Note: this is only executed once
                         if (!$readonlyAlreadyChecked) {
                             foreach ($files as $id) {
-                                if (!$is_allowed_to_edit) {
+                                if (!$isAllowedToEdit) {
                                     if (DocumentManager::check_readonly(
                                         $courseInfo,
                                         api_get_user_id(),
@@ -1268,11 +1279,11 @@ if ($is_allowed_to_edit ||
     }
 }
 
-$dirForm = null;
+$dirForm = '';
 
 /* 	CREATE DIRECTORY */
 //Only teacher and all users into their group and any user into his/her shared folder
-if ($is_allowed_to_edit ||
+if ($isAllowedToEdit ||
     $group_member_with_upload_rights ||
     DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)
 ) {
@@ -1347,7 +1358,7 @@ if ($is_allowed_to_edit ||
 }
 
 /* 	VISIBILITY COMMANDS */
-if ($is_allowed_to_edit) {
+if ($isAllowedToEdit) {
     if ((isset($_GET['set_invisible']) && !empty($_GET['set_invisible'])) ||
         (isset($_GET['set_visible']) && !empty($_GET['set_visible']))
     ) {
@@ -1360,7 +1371,7 @@ if ($is_allowed_to_edit) {
             $visibility_command = 'invisible';
         }
 
-        if (!$is_allowed_to_edit) {
+        if (!$isAllowedToEdit) {
             if (api_is_coach()) {
                 if (!DocumentManager::is_visible_by_id($update_id, $courseInfo, $sessionId, api_get_user_id())) {
                     api_not_allowed(true);
@@ -1397,18 +1408,16 @@ if ($is_allowed_to_edit) {
         exit;
     }
 }
-$templateForm = null;
+$templateForm = '';
 
 /* 	TEMPLATE ACTION */
 //Only teacher and all users into their group
-if ($is_allowed_to_edit ||
+if ($isAllowedToEdit ||
     $group_member_with_upload_rights ||
     DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)
 ) {
     if (isset($_GET['add_as_template']) && !isset($_POST['create_template'])) {
-
         $document_id_for_template = intval($_GET['add_as_template']);
-
         // Create the form that asks for the directory name
         $templateForm .= '
             <form name="set_document_as_new_template" class="form-horizontal" enctype="multipart/form-data" action="' . api_get_self() . '?add_as_template=' . $document_id_for_template . '" method="post">
@@ -1437,7 +1446,6 @@ if ($is_allowed_to_edit ||
             <hr>
         ';
     } elseif (isset($_GET['add_as_template']) && isset($_POST['create_template'])) {
-
         $document_id_for_template = intval($_GET['add_as_template']);
         $title = Security::remove_XSS($_POST['template_title']);
         $user_id = api_get_user_id();
@@ -1530,7 +1538,7 @@ if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
         $curdirpath,
         $groupIid,
         null,
-        $is_allowed_to_edit || $group_member_with_upload_rights,
+        $isAllowedToEdit || $group_member_with_upload_rights,
         true
     );
 } else {
@@ -1539,7 +1547,7 @@ if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
         $curdirpath,
         $groupIid,
         null,
-        $is_allowed_to_edit || $group_member_with_upload_rights,
+        $isAllowedToEdit || $group_member_with_upload_rights,
         false
     );
 }
@@ -1554,7 +1562,7 @@ if ($groupId != 0) {
         $folders = DocumentManager::get_all_document_folders(
             $courseInfo,
             $groupIid,
-            $is_allowed_to_edit || $group_member_with_upload_rights,
+            $isAllowedToEdit || $group_member_with_upload_rights,
             false,
             $curdirpath
         );
@@ -1563,7 +1571,7 @@ if ($groupId != 0) {
     $folders = DocumentManager::get_all_document_folders(
         $courseInfo,
         0,
-        $is_allowed_to_edit || $group_member_with_upload_rights,
+        $isAllowedToEdit || $group_member_with_upload_rights,
         false,
         $curdirpath
     );
@@ -1592,7 +1600,7 @@ if ($is_certificate_mode && $curdirpath != '/certificates') {
 
 $column_show = array();
 
-if ($is_allowed_to_edit ||
+if ($isAllowedToEdit ||
     $group_member_with_upload_rights ||
     DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)
 ) {
@@ -1699,7 +1707,7 @@ if ($image_present && !isset($_GET['keyword'])) {
     );
 }
 
-if (api_is_allowed_to_edit(null, true)) {
+if ($isAllowedToEdit) {
     $actionsLeft .= Display::url(
         Display::return_icon('percentage.png', get_lang('DocumentQuota'), '', ICON_SIZE_MEDIUM),
         api_get_path(WEB_CODE_PATH).'document/document_quota.php?'.api_get_cidreq()
@@ -1728,18 +1736,19 @@ $table_footer = '';
 $total_size = 0;
 $sortable_data = array();
 $row = array();
+
+$userIsSubscribed = CourseManager::is_user_subscribed_in_course(
+    api_get_user_id(),
+    $courseInfo['code']
+);
+
+
+$getSizeURL = api_get_path(WEB_AJAX_PATH).'document.ajax.php?a=get_dir_size&'.api_get_cidreq();
+
 if (isset($documentAndFolders) && is_array($documentAndFolders)) {
-    if ($groupId == 0 ||
-        GroupManager::user_has_access(
-            $userId,
-            $groupIid,
-            GroupManager::GROUP_TOOL_DOCUMENTS
-        )
-    ) {
+    if ($groupId == 0 || $userAccess) {
         $count = 1;
         $countedPaths = array();
-        $countedPaths = array();
-
         foreach ($documentAndFolders as $key => $document_data) {
             $row = array();
             $row['id'] = $document_data['id'];
@@ -1751,14 +1760,14 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
                 $courseInfo,
                 $sessionId,
                 api_get_user_id(),
-                false
+                false,
+                $userIsSubscribed
             );
 
             $invisibility_span_open = ($is_visible == 0) ? '<span class="muted">' : '';
             $invisibility_span_close = ($is_visible == 0) ? '</span>' : '';
 
-            // Size (or total size of a directory)
-            $size = $document_data['filetype'] == 'folder' ? get_total_folder_size($document_data['path'], $is_allowed_to_edit) : $document_data['size'];
+            $size = 1;
 
             // Get the title or the basename depending on what we're using
             if ($document_data['title'] != '') {
@@ -1769,7 +1778,7 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
 
             $row['name'] = $document_name;
             // Data for checkbox
-            if (($is_allowed_to_edit || $group_member_with_upload_rights) && count($documentAndFolders) > 1) {
+            if (($isAllowedToEdit || $group_member_with_upload_rights) && count($documentAndFolders) > 1) {
                 $row[] = $document_data['id'];
             }
 
@@ -1781,18 +1790,28 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
             $user_link = '';
             if (!empty($groupId)) {
                 if (!empty($document_data['insert_user_id'])) {
-                    $user_info = api_get_user_info($document_data['insert_user_id']);
+                    $userInfo = api_get_user_info(
+                        $document_data['insert_user_id'],
+                        false,
+                        false,
+                        false,
+                        false,
+                        false
+                    );
                     $user_link = '<div class="document_owner">'.
-                        get_lang('Owner').': '.UserManager::getUserProfileLink($user_info).'</div>';
+                        get_lang('Owner').': '.UserManager::getUserProfileLink($userInfo).'</div>';
                 }
             }
 
             // Icons (clickable)
             $row[] = DocumentManager::create_document_link(
                 $document_data,
+                $courseInfo,
                 true,
                 $count,
-                $is_visible
+                $is_visible,
+                $size,
+                $isAllowedToEdit
             );
 
             $path_info = pathinfo($document_data['path']);
@@ -1806,20 +1825,33 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
             // Validation when belongs to a session
             $session_img = api_get_session_image($document_data['session_id'], $_user['status']);
 
+            $link = DocumentManager::create_document_link(
+                $document_data,
+                $courseInfo,
+                false,
+                null,
+                $is_visible,
+                $size,
+                $isAllowedToEdit
+            );
+
             // Document title with link
-            $row[] = DocumentManager::create_document_link($document_data, false, null, $is_visible).
-                $session_img.'<br />'.$invisibility_span_open.
+            $row[] = $link.$session_img.'<br />'.$invisibility_span_open.
                 '<i>'.nl2br(htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset)).'</i>'.
                 $invisibility_span_close.
                 $user_link;
 
-            // Comments => display comment under the document name
-            $display_size = format_file_size($size);
+            if ($document_data['filetype'] == 'folder') {
+                $displaySize = '<span id="document_size_'.$document_data['id'].'" data-path= "'.$document_data['path'].'" class="document_size"></span>';
+            } else {
+                $displaySize = format_file_size($document_data['size']);
+            }
 
             $row[] = '<span style="display:none;">'.$size.'</span>'.
                 $invisibility_span_open.
-                $display_size.
+                $displaySize.
                 $invisibility_span_close;
+
             // Last edit date
             $last_edit_date = api_get_local_time($document_data['lastedit_date']);
             $display_date = date_to_str_ago($document_data['lastedit_date']).
@@ -1828,7 +1860,7 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
             $row[] = $invisibility_span_open.$display_date.$invisibility_span_close;
 
             // Admins get an edit column
-            if ($is_allowed_to_edit ||
+            if ($isAllowedToEdit ||
                 $groupMemberWithEditRights ||
                 DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId) ||
                 $document_data['insert_user_id'] == api_get_user_id()
@@ -1882,17 +1914,16 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
 
 if (!is_null($documentAndFolders)) {
     // Show download zipped folder icon
-    global $total_size;
     if (!$is_certificate_mode && $total_size != 0
         && (api_get_setting('students_download_folders') == 'true'
-        || api_is_allowed_to_edit()
+        || $isAllowedToEdit
         || api_is_platform_admin()
         )
     ) {
         //for student does not show icon into other shared folder, and does not show into main path (root)
         if (DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)
             && $curdirpath != '/'
-            || api_is_allowed_to_edit()
+            || $isAllowedToEdit
             || api_is_platform_admin()
         ) {
             $actionsLeft .= Display::url(
@@ -1926,8 +1957,7 @@ if (isset($_GET['createdir']) && isset($_POST['dirname']) && $_POST['dirname'] !
     $post_dir_name = $_POST['dirname'];
     $document_id = DocumentManager::get_document_id($courseInfo, $_POST['dirname']);
 }
-$selector = null;
-
+$selector = '';
 if (!$is_certificate_mode) {
     $selector = DocumentManager::build_directory_selector(
         $folders,
@@ -1937,7 +1967,7 @@ if (!$is_certificate_mode) {
     );
 }
 
-if (($is_allowed_to_edit || $group_member_with_upload_rights) &&
+if (($isAllowedToEdit || $group_member_with_upload_rights) &&
     count($documentAndFolders) > 1
 ) {
     $column_show[] = 1;
@@ -1948,7 +1978,7 @@ $column_show[] = 1;
 $column_show[] = 1;
 $column_show[] = 1;
 
-if ($is_allowed_to_edit
+if ($isAllowedToEdit
     || $group_member_with_upload_rights
     || DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)
 ) {
@@ -1971,8 +2001,8 @@ if (count($row) == 12) {
     $column_order[3] = 4;
 }
 
-$default_column = $is_allowed_to_edit ? 2 : 1;
-$tableName = $is_allowed_to_edit ? 'teacher_table' : 'student_table';
+$default_column = $isAllowedToEdit ? 2 : 1;
+$tableName = $isAllowedToEdit ? 'teacher_table' : 'student_table';
 
 $table = new SortableTableFromArrayConfig(
     $sortable_data,
@@ -1999,7 +2029,7 @@ $table->set_additional_parameters($query_vars);
 
 $column = 0;
 
-if (($is_allowed_to_edit || $group_member_with_upload_rights) && count($documentAndFolders) > 1) {
+if (($isAllowedToEdit || $group_member_with_upload_rights) && count($documentAndFolders) > 1) {
     $table->set_header($column++, '', false, array('style' => 'width:12px;'));
 }
 $table->set_header($column++, get_lang('Type'), true, array('style' => 'width:30px;'));
@@ -2007,7 +2037,7 @@ $table->set_header($column++, get_lang('Name'));
 $table->set_header($column++, get_lang('Size'), true, array('style' => 'width:50px;'));
 $table->set_header($column++, get_lang('Date'), true, array('style' => 'width:150px;'));
 // Admins get an edit column
-if ($is_allowed_to_edit
+if ($isAllowedToEdit
     || $group_member_with_upload_rights
     || DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId)) {
     $table->set_header($column++, get_lang('Actions'), false, array('class' => 'td_actions'));
@@ -2017,7 +2047,7 @@ if ($is_allowed_to_edit
 // TODO: Currently only delete action -> take only DELETE permission into account
 
 if (count($documentAndFolders) > 1) {
-    if ($is_allowed_to_edit || $groupMemberWithEditRights) {
+    if ($isAllowedToEdit || $groupMemberWithEditRights) {
         $form_actions = array();
         $form_action['set_invisible'] = get_lang('SetInvisible');
         $form_action['set_visible'] = get_lang('SetVisible');
@@ -2029,7 +2059,6 @@ if (count($documentAndFolders) > 1) {
 Display::display_header('', 'Doc');
 
 /* Introduction section (editable by course admins) */
-
 if (!empty($groupId)) {
     Display::display_introduction_section(TOOL_DOCUMENT.$groupId);
 } else {
@@ -2037,7 +2066,7 @@ if (!empty($groupId)) {
 }
 $toolbar = Display::toolbarAction(
     'toolbar-document',
-    array(0 => $actionsLeft, 1 => $actionsRight)
+    array($actionsLeft, $actionsRight)
 );
 
 echo $toolbar;
@@ -2047,22 +2076,32 @@ echo $dirForm;
 echo $selector;
 
 $table->display();
+$ajaxURL = api_get_path(WEB_AJAX_PATH).'document.ajax.php?a=get_document_quota&'.api_get_cidreq();
 
 if (count($documentAndFolders) > 1) {
-    if ($is_allowed_to_edit || $group_member_with_upload_rights) {
-        // Getting the course quota
-        $course_quota = DocumentManager::get_course_quota();
+    if ($isAllowedToEdit || $group_member_with_upload_rights) {
+        echo '<script>
+        $(document).ready(function() {
+            $.ajax({
+                url:"'.$ajaxURL.'",
+                success:function(data){
+                    $("#course_quota").html(data);
+                }
+            });
 
-        // Calculating the total space
-        $already_consumed_space_course = DocumentManager::documents_total_space(
-            api_get_course_int_id()
-        );
+            $(".document_size").each(function(i, obj) {
+                var path = obj.getAttribute("data-path");
 
-        // Displaying the quota
-        DocumentManager::display_simple_quota(
-            $course_quota,
-            $already_consumed_space_course
-        );
+                $.ajax({
+                    url:"'.$getSizeURL.'&path="+path,
+                    success:function(data){
+                        $(obj).html(data);
+                    }
+                });            
+            });    
+        });
+        </script>';
+        echo '<span id="course_quota"></span>';
     }
 }
 if (!empty($table_footer)) {

+ 45 - 29
main/exercise/exercise.class.php

@@ -3633,8 +3633,8 @@ class Exercise
                             $answer
                         );
 
-                        $switchableAnswerSet = $listCorrectAnswers["switchable"];
-                        $answerWeighting = $listCorrectAnswers["tabweighting"];
+                        $switchableAnswerSet = $listCorrectAnswers['switchable'];
+                        $answerWeighting = $listCorrectAnswers['tabweighting'];
                         // user choices is an array $choice
 
                         // get existing user data in n the BDD
@@ -3658,16 +3658,16 @@ class Exercise
                             // not switchable answer, must be in the same place than teacher order
                             for ($i = 0; $i < count($listCorrectAnswers['tabwords']); $i++) {
                                 $studentAnswer = isset($choice[$i]) ? trim($choice[$i]) : '';
+                                $correctAnswer = $listCorrectAnswers['tabwords'][$i];
 
                                 // This value is the user input, not escaped while correct answer is escaped by fckeditor
                                 // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618
-                                /*if (!$from_database) {
+                                if (!$from_database) {
                                     $studentAnswer = htmlentities(
                                         api_utf8_encode($studentAnswer)
                                     );
-                                }*/
+                                }
 
-                                $correctAnswer = $listCorrectAnswers['tabwords'][$i];
                                 $isAnswerCorrect = 0;
                                 if (FillBlanks::isGoodStudentAnswer($studentAnswer, $correctAnswer)) {
                                     // gives the related weighting to the student
@@ -5241,13 +5241,19 @@ class Exercise
     /**
      * Sends a notification when a user ends an examn
      *
-     * @param integer $exe_id
+     * @param array $question_list_answers
+     * @param string $origin
+     * @param int $exe_id
+     * @param float $score
+     * @param float $weight
+     * @return bool
      */
-    public function send_mail_notification_for_exam($question_list_answers, $origin, $exe_id)
+    public function send_mail_notification_for_exam($question_list_answers, $origin, $exe_id, $score, $weight)
     {
-        if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
-            return null;
+        if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1) {
+            return false;
         }
+
         // Email configuration settings
         $courseCode = api_get_course_id();
         $courseInfo = api_get_course_info($courseCode);
@@ -5267,26 +5273,36 @@ class Exercise
             . '&action=qualify';
         $user_info = api_get_user_info(api_get_user_id());
 
+        $scoreLabel = '';
+        if (api_get_configuration_value('send_score_in_exam_notification_mail_to_manager') == true) {
+            $scoreLabel = ExerciseLib::show_score($score, $weight, false, true);
+            $scoreLabel = "<tr>
+                            <td>".get_lang('Score')."</td>
+                            <td>&nbsp;$scoreLabel</td>
+                        </tr>";
+        }
+
         $msg = get_lang('ExerciseAttempted').'<br /><br />'
-                    .get_lang('AttemptDetails').' : <br /><br />'.
-                    '<table>'
-                        .'<tr>'
-                            .'<td><em>'.get_lang('CourseName').'</em></td>'
-                            .'<td>&nbsp;<b>#course#</b></td>'
-                        .'</tr>'
-                        .'<tr>'
-                            .'<td>'.get_lang('TestAttempted').'</td>'
-                            .'<td>&nbsp;#exercise#</td>'
-                        .'</tr>'
-                        .'<tr>'
-                            .'<td>'.get_lang('StudentName').'</td>'
-                            .'<td>&nbsp;#firstName# #lastName#</td>'
-                        .'</tr>'
-                        .'<tr>'
-                            .'<td>'.get_lang('StudentEmail').'</td>'
-                            .'<td>&nbsp;#email#</td>'
-                        .'</tr>'
-                    .'</table>';
+                    .get_lang('AttemptDetails').' : <br /><br />
+                    <table>
+                        <tr>
+                            <td><em>'.get_lang('CourseName').'</em></td>
+                            <td>&nbsp;<b>#course#</b></td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('TestAttempted').'</td>
+                            <td>&nbsp;#exercise#</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('StudentName').'</td>
+                            <td>&nbsp;#firstName# #lastName#</td>
+                        </tr>
+                        <tr>
+                            <td>'.get_lang('StudentEmail').'</td>
+                            <td>&nbsp;#email#</td>
+                        </tr>
+                        '.$scoreLabel.'
+                    </table>';
         $open_question_list = null;
 
         $msg = str_replace("#email#", $user_info['email'], $msg);
@@ -5333,7 +5349,7 @@ class Exercise
      *
      * @param integer $exe_id
      */
-    function send_notification_for_open_questions($question_list_answers, $origin, $exe_id)
+    public function send_notification_for_open_questions($question_list_answers, $origin, $exe_id)
     {
         if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
             return null;

+ 70 - 35
main/exercise/exercise_submit.php

@@ -143,6 +143,10 @@ if (!is_object($objExercise)) {
     exit;
 }
 
+// if the user has submitted the form
+$exercise_title = $objExercise->selectTitle();
+$exercise_sound = $objExercise->selectSound();
+
 // If reminder ends we jump to the exercise_reminder
 if ($objExercise->review_answers) {
     if ($remind_question_id == -1) {
@@ -160,7 +164,7 @@ $my_remind_list = array();
 
 $time_control = false;
 if ($objExercise->expired_time != 0) {
-	$time_control = true;
+    $time_control = true;
 }
 
 // Generating the time control key for the user
@@ -169,14 +173,14 @@ $current_expired_time_key = ExerciseLib::get_time_control_key($objExercise->id,
 $_SESSION['duration_time'][$current_expired_time_key] = $current_timestamp;
 
 if ($time_control) {
-	// Get the expired time of the current exercise in track_e_exercises
-	$total_seconds = $objExercise->expired_time*60;
+    // Get the expired time of the current exercise in track_e_exercises
+    $total_seconds = $objExercise->expired_time*60;
 }
 
 $show_clock = true;
 $user_id = api_get_user_id();
 if ($objExercise->selectAttempts() > 0) {
-	$attempt_html = '';
+    $attempt_html = '';
     $attempt_count = Event::get_attempt_count(
         $user_id,
         $exerciseId,
@@ -185,11 +189,10 @@ if ($objExercise->selectAttempts() > 0) {
         $learnpath_item_view_id
     );
 
-	if ($attempt_count >= $objExercise->selectAttempts()) {
-		$show_clock = false;
-		if (!api_is_allowed_to_edit(null,true)) {
+    if ($attempt_count >= $objExercise->selectAttempts()) {
+        $show_clock = false;
+        if (!api_is_allowed_to_edit(null, true)) {
             if ($objExercise->results_disabled == 0 && $origin != 'learnpath') {
-
                 // Showing latest attempt according with task BT#1628
                 $exercise_stat_info = Event::getExerciseResultsByUser(
                     $user_id,
@@ -217,42 +220,78 @@ if ($objExercise->selectAttempts() > 0) {
                     );
 
                     if (!empty($last_attempt_info['question_list'])) {
-                        foreach($last_attempt_info['question_list'] as $questions) {
+                        foreach ($last_attempt_info['question_list'] as $questions) {
                             foreach ($questions as $question_data) {
                                 $question_id = $question_data['question_id'];
-                                $marks       = $question_data['marks'];
+                                $marks = $question_data['marks'];
 
                                 $question_info = Question::read($question_id);
-                                $attempt_html .= Display::div($question_info->question, array('class'=>'question_title'));
-                                $attempt_html .= Display::div(get_lang('Score').' '.$marks, array('id'=>'question_question_titlescore'));
+                                $attempt_html .= Display::div(
+                                    $question_info->question,
+                                    array('class' => 'question_title')
+                                );
+                                $attempt_html .= Display::div(
+                                    get_lang('Score').' '.$marks,
+                                    array('id' => 'question_question_titlescore')
+                                );
                             }
                         }
                     }
-					$score =  ExerciseLib::show_score($last_attempt_info['exe_result'], $last_attempt_info['exe_weighting']);
-					$attempt_html .= Display::div(get_lang('YourTotalScore').' '.$score, array('id'=>'question_score'));
-				} else {
-					$attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
-				}
-			} else {
-				$attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
-			}
-		} else {
-			$attempt_html .= Display :: return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
-		}
+                    $score = ExerciseLib::show_score(
+                        $last_attempt_info['exe_result'],
+                        $last_attempt_info['exe_weighting']
+                    );
+                    $attempt_html .= Display::div(
+                        get_lang('YourTotalScore').' '.$score,
+                        array('id' => 'question_score')
+                    );
+                } else {
+                    $attempt_html .= Display::return_message(
+                        sprintf(
+                            get_lang('ReachedMaxAttempts'),
+                            $exercise_title,
+                            $objExercise->selectAttempts()
+                        ),
+                        'warning',
+                        false
+                    );
+                }
+            } else {
+                $attempt_html .= Display::return_message(
+                    sprintf(
+                        get_lang('ReachedMaxAttempts'),
+                        $exercise_title,
+                        $objExercise->selectAttempts()
+                    ),
+                    'warning',
+                    false
+                );
+            }
+        } else {
+            $attempt_html .= Display::return_message(
+                sprintf(
+                    get_lang('ReachedMaxAttempts'),
+                    $exercise_title,
+                    $objExercise->selectAttempts()
+                ),
+                'warning',
+                false
+            );
+        }
 
-		if ($origin == 'learnpath') {
-			Display :: display_reduced_header();
-		} else {
-			Display :: display_header(get_lang('Exercises'));
-		}
+        if ($origin == 'learnpath') {
+            Display :: display_reduced_header();
+        } else {
+            Display :: display_header(get_lang('Exercises'));
+        }
 
-		echo $attempt_html;
+        echo $attempt_html;
 
         if ($origin != 'learnpath') {
             Display:: display_footer();
         }
-		exit;
-	}
+        exit;
+    }
 }
 
 if ($debug) {
@@ -459,10 +498,6 @@ if ($time_control) { //Sends the exercise form when the expired time is finished
 	$htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
 }
 
-// if the user has submitted the form
-$exercise_title = $objExercise->selectTitle();
-$exercise_sound = $objExercise->selectSound();
-
 //in LP's is enabled the "remember question" feature?
 
 if (!isset($_SESSION['questionList'])) {

+ 30 - 29
main/exercise/fill_blanks.class.php

@@ -33,9 +33,7 @@ class FillBlanks extends Question
      */
     public function createAnswersForm($form)
     {
-        //$fillBlanksAllowedSeparator = self::getAllowedSeparator();
         $defaults = array();
-
         if (!empty($this->id)) {
             $objectAnswer = new Answer($this->id);
             $answer = $objectAnswer->selectAnswer(1);
@@ -64,7 +62,6 @@ class FillBlanks extends Question
                 $setWeightAndSize .= 'document.getElementById("weighting['.$i.']").value = "'.$weighting.'";';
             }
             foreach ($listAnswersInfo['tabinputsize'] as $i => $sizeOfInput) {
-                //var_dump($listAnswersInfo['tabwords']);
                 $setWeightAndSize .= 'document.getElementById("sizeofinput['.$i.']").value = "'.$sizeOfInput.'";';
                 $setWeightAndSize .= 'document.getElementById("samplesize['.$i.']").style.width = "'.$sizeOfInput.'px";';
             }
@@ -90,8 +87,7 @@ class FillBlanks extends Question
             });                        
             
             function updateBlanks()
-            {
-                
+            {                
                 var answer;                
                 if (firstTime) {
                     var field = document.getElementById("answer");
@@ -185,15 +181,15 @@ class FillBlanks extends Question
             window.onload = updateBlanks;
             
             String.prototype.hashCode = function() {
-  var hash = 0, i, chr, len;
-  if (this.length === 0) return hash;
-  for (i = 0, len = this.length; i < len; i++) {
-    chr   = this.charCodeAt(i);
-    hash  = ((hash << 5) - hash) + chr;
-    hash |= 0; // Convert to 32bit integer
-  }
-  return hash;
-};
+                var hash = 0, i, chr, len;
+                if (this.length === 0) return hash;
+                for (i = 0, len = this.length; i < len; i++) {
+                    chr   = this.charCodeAt(i);
+                    hash  = ((hash << 5) - hash) + chr;
+                    hash |= 0; // Convert to 32bit integer
+                }
+                return hash;
+            };
             
             function updateOrder(blanks) 
             {
@@ -510,7 +506,7 @@ class FillBlanks extends Question
         $displayForStudent,
         $inBlankNumber
     ) {
-        $result = "";
+        $result = '';
         $inTabTeacherSolution = $listAnswersInfo['tabwords'];
         $inTeacherSolution = $inTabTeacherSolution[$inBlankNumber];
         switch (self::getFillTheBlankAnswerType($inTeacherSolution)) {
@@ -563,7 +559,13 @@ class FillBlanks extends Question
     public static function getFillTheBlankMenuAnswers($correctAnswer, $displayForStudent)
     {
         // if $inDisplayForStudent, then shuffle the result array
-        $listChoises = api_preg_split("/\|/", $correctAnswer);
+        /*$items = explode('|', $correctAnswer);
+        if ($displayForStudent) {
+            shuffle($items);
+        }
+
+        return $items;*/
+         $listChoises = api_preg_split("/\|/", $correctAnswer);
         if ($displayForStudent) {
             shuffle($listChoises);
         }
@@ -736,7 +738,7 @@ class FillBlanks extends Question
             array_walk(
                 $listWords[0],
                 function (&$value, $key, $tabBlankChar) {
-                    $trimChars = "";
+                    $trimChars = '';
                     for ($i=0; $i < count($tabBlankChar); $i++) {
                         $trimChars .= $tabBlankChar[$i];
                     }
@@ -826,22 +828,22 @@ class FillBlanks extends Question
         // student may have not answered the bracket id, in this case, is result of the answer is empty
         // we got the less recent attempt first
         $sql = 'SELECT * FROM '.$tblTrackEAttempt.' tea
-               LEFT JOIN '.$tblTrackEExercise.' tee
-               ON tee.exe_id = tea.exe_id
-               AND tea.c_id = '.$courseId.'
-               AND exe_exo_id = '.$testId.'    
+                LEFT JOIN '.$tblTrackEExercise.' tee
+                ON 
+                    tee.exe_id = tea.exe_id AND 
+                    tea.c_id = '.$courseId.' AND 
+                    exe_exo_id = '.$testId.'    
                WHERE 
-                tee.c_id = '.$courseId.' AND 
-                question_id = '.$questionId.' AND 
-                tea.user_id IN ('.implode(',', $studentsIdList).')  AND 
-                tea.tms >= "'.$startDate.'" AND 
-                tea.tms <= "'.$endDate.'"
+                    tee.c_id = '.$courseId.' AND 
+                    question_id = '.$questionId.' AND 
+                    tea.user_id IN ('.implode(',', $studentsIdList).')  AND 
+                    tea.tms >= "'.$startDate.'" AND 
+                    tea.tms <= "'.$endDate.'"
                ORDER BY user_id, tea.exe_id;
         ';
 
         $res = Database::query($sql);
         $tabUserResult = array();
-        $bracketNumber = 0;
         // foreach attempts for all students starting with his older attempt
         while ($data = Database::fetch_array($res)) {
             $tabAnswer = FillBlanks::getAnswerInfo($data['answer'], true);
@@ -891,7 +893,7 @@ class FillBlanks extends Question
 
     /**
      * Return the number of student that give at leat an answer in the fill the blank test
-     * @param $resultList
+     * @param array $resultList
      * @return int
      */
     public static function getNbResultFillBlankAll($resultList)
@@ -1013,7 +1015,6 @@ class FillBlanks extends Question
         return $result;
     }
 
-
     /**
      * This function must be the same than the js one getSeparatorFromNumber above
      * @return array

+ 43 - 32
main/forum/forumfunction.inc.php

@@ -1669,7 +1669,10 @@ function get_last_post_by_thread($course_id, $thread_id, $forum_id, $show_visibl
 
     $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
     $sql = "SELECT * FROM $table_posts
-            WHERE c_id = $course_id AND thread_id = $thread_id AND forum_id = $forum_id";
+            WHERE 
+                c_id = $course_id AND 
+                thread_id = $thread_id AND 
+                forum_id = $forum_id";
 
     if ($show_visible == false) {
         $sql .= " AND visible = 1 ";
@@ -3283,14 +3286,14 @@ function getThreadScoreHistory($user_id, $thread_id, $opt)
     $course_id = api_get_course_int_id();
 
     if ($opt == 'false') {
-        $sql = "SELECT * FROM ".$table_threads_qualify_log."
+        $sql = "SELECT * FROM $table_threads_qualify_log
                 WHERE
                     c_id = $course_id AND
                     thread_id='".Database::escape_string($thread_id)."' AND
                     user_id='".Database::escape_string($user_id)."'
                 ORDER BY qualify_time";
     } else {
-        $sql = "SELECT * FROM ".$table_threads_qualify_log."
+        $sql = "SELECT * FROM $table_threads_qualify_log
                 WHERE
                     c_id = $course_id AND
                     thread_id='".Database::escape_string($thread_id)."' AND
@@ -3954,48 +3957,46 @@ function forum_not_allowed_here()
  */
 function get_whats_new()
 {
-    $_user = api_get_user_info();
-    $_course = api_get_course_info();
+    $userId = api_get_user_id();
+    $course_id = api_get_course_int_id();
+
+    if (empty($course_id) || empty($userId)) {
+        return false;
+    }
 
     $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
     $tracking_last_tool_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
 
-    // Note: This has to be replaced by the tool constant later.
-    // But temporarily bb_forum is used since this is the only thing that is in the tracking currently.
-    //$tool = TOOL_FORUM;
-    $tool = TOOL_FORUM; //
-    // to do: Remove this. For testing purposes only.
-    //Session::erase('last_forum_access');
-    //Session::erase('whatsnew_post_info');
-
-    $course_id = api_get_course_int_id();
+    $tool = TOOL_FORUM;
     $lastForumAccess = Session::read('last_forum_access');
 
     if (!$lastForumAccess) {
-        $sql = "SELECT * FROM ".$tracking_last_tool_access."
+        $sql = "SELECT * FROM $tracking_last_tool_access
                 WHERE
-                    access_user_id='".Database::escape_string($_user['user_id'])."' AND
-                    c_id ='".$course_id."' AND
-                    access_tool='".Database::escape_string($tool)."'";
+                    access_user_id = $userId AND
+                    c_id = $course_id AND
+                    access_tool = '".Database::escape_string($tool)."'";
         $result = Database::query($sql);
         $row = Database::fetch_array($result);
-        $_SESSION['last_forum_access'] = $row['access_date'];
+        Session::write('last_forum_access', $row['access_date']);
+        $lastForumAccess = $row['access_date'];
     }
 
     $whatsNew = Session::read('whatsnew_post_info');
 
     if (!$whatsNew) {
         if ($lastForumAccess != '') {
-            $whatsnew_post_info = array();
+            $postInfo = array();
             $sql = "SELECT * FROM $table_posts
                     WHERE
                         c_id = $course_id AND
-                        post_date >'".Database::escape_string($_SESSION['last_forum_access'])."'"; // note: check the performance of this query.
+                        visible = 1 AND                        
+                        post_date > '".Database::escape_string($lastForumAccess)."'";
             $result = Database::query($sql);
             while ($row = Database::fetch_array($result)) {
-                $whatsnew_post_info[$row['forum_id']][$row['thread_id']][$row['post_id']] = $row['post_date'];
+                $postInfo[$row['forum_id']][$row['thread_id']][$row['post_id']] = $row['post_date'];
             }
-            $_SESSION['whatsnew_post_info'] = $whatsnew_post_info;
+            Session::write('whatsnew_post_info', $postInfo);
         }
     }
 }
@@ -5372,11 +5373,19 @@ function count_number_of_post_in_thread($thread_id)
     if (empty($course_id)) {
         return 0;
     }
-    $sql = "SELECT * FROM $table_posts
-            WHERE c_id = $course_id AND thread_id='".intval($thread_id)."' ";
+    $sql = "SELECT count(*) count FROM $table_posts
+            WHERE 
+                c_id = $course_id AND 
+                thread_id='".intval($thread_id)."' ";
     $result = Database::query($sql);
 
-    return count(Database::store_result($result));
+    $count = 0;
+    if (Database::num_rows($result) > 0) {
+        $row = Database::fetch_array($result);
+        $count = $row['count'];
+    }
+
+    return $count;
 }
 
 /**
@@ -5408,7 +5417,7 @@ function count_number_of_post_for_user_thread($thread_id, $user_id)
 /**
  * This function counts the number of user register in course
  * @param   int $course_id Course ID
- *
+ * @deprecated use CourseManager::get_users_count_in_course
  * @return  int the number of user register in course
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version octubre 2008, dokeos 1.8
@@ -5437,7 +5446,8 @@ function count_number_of_user_in_course($course_id)
 function get_statistical_information($thread_id, $user_id, $course_id)
 {
     $result = array();
-    $result['user_course'] = count_number_of_user_in_course($course_id);
+    $courseInfo = api_get_course_info_by_id($course_id);
+    $result['user_course'] = CourseManager::get_users_count_in_course($courseInfo['code']);
     $result['post'] = count_number_of_post_in_thread($thread_id);
     $result['user_post'] = count_number_of_post_for_user_thread($thread_id, $user_id);
 
@@ -5450,7 +5460,7 @@ function get_statistical_information($thread_id, $user_id, $course_id)
  * @param   int $thread_id
  * @param   int $user_id
  *
- * @return  int the number of post inside a thread
+ * @return  array posts inside a thread
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version oct 2008, dokeos 1.8
  */
@@ -5481,8 +5491,8 @@ function get_thread_user_post($course_code, $thread_id, $user_id)
         $row['status'] = '1';
         $post_list[] = $row;
         $sql = "SELECT * FROM $table_posts posts
-                LEFT JOIN  $table_users users
-                    ON posts.poster_id=users.user_id
+                LEFT JOIN $table_users users
+                ON (posts.poster_id=users.user_id)
                 WHERE
                     posts.c_id = $course_id AND
                     posts.thread_id='$thread_id'
@@ -5509,7 +5519,8 @@ function get_name_thread_by_id($thread_id)
 {
     $t_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
     $course_id = api_get_course_int_id();
-    $sql = "SELECT thread_title FROM ".$t_forum_thread."
+    $sql = "SELECT thread_title 
+            FROM $t_forum_thread
             WHERE c_id = $course_id AND thread_id = '".intval($thread_id)."' ";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);

+ 2 - 1
main/forum/viewforumcategory.php

@@ -22,7 +22,6 @@
  * @package chamilo.forum
  */
 
-// Including the global initialization file.
 require_once __DIR__.'/../inc/global.inc.php';
 
 $htmlHeadXtra[] = '<script>
@@ -44,6 +43,8 @@ api_protect_course_script(true);
 // Including additional library scripts.
 $nameTools = get_lang('ToolForum');
 
+$_user = api_get_user_info();
+
 // Including necessary files
 require 'forumconfig.inc.php';
 require_once 'forumfunction.inc.php';

+ 1 - 1
main/gradebook/lib/GradebookUtils.php

@@ -750,7 +750,7 @@ class GradebookUtils
         $new_content_html = str_replace(SYS_CODE_PATH . 'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
 
         $dom = new DOMDocument();
-        $dom->loadHTML($new_content_html);
+        @$dom->loadHTML($new_content_html);
 
         //add print header
         if (!$hide_print_button) {

+ 23 - 0
main/inc/ajax/document.ajax.php

@@ -8,6 +8,29 @@ require_once __DIR__.'/../global.inc.php';
 
 $action = $_REQUEST['a'];
 switch ($action) {
+    case 'get_dir_size':
+        api_protect_course_script(true);
+        $path = isset($_GET['path']) ? $_GET['path'] : '';
+        $isAllowedToEdit = api_is_allowed_to_edit();
+        $size = get_total_folder_size($path, $isAllowedToEdit);
+        echo format_file_size($size);
+        break;
+    case 'get_document_quota':
+        // Getting the course quota
+        $course_quota = DocumentManager::get_course_quota();
+
+        // Calculating the total space
+        $already_consumed_space_course = DocumentManager::documents_total_space(
+            api_get_course_int_id()
+        );
+
+        // Displaying the quota
+        echo DocumentManager::display_simple_quota(
+            $course_quota,
+            $already_consumed_space_course
+        );
+
+        break;
     case 'upload_file':
         api_protect_course_script(true);
         // User access same as upload.php

+ 1 - 3
main/inc/ajax/exercise.ajax.php

@@ -340,7 +340,6 @@ switch ($action) {
             unset($objQuestionTmp);
 
             // Looping the question list
-
             foreach ($question_list as $my_question_id) {
                 if ($debug) {
                     error_log("Saving question_id = $my_question_id ");
@@ -350,8 +349,7 @@ switch ($action) {
                     continue;
                 }
 
-                $my_choice = isset($choice[$my_question_id]) ?
-                    $choice[$my_question_id] : null;
+                $my_choice = isset($choice[$my_question_id]) ? $choice[$my_question_id] : null;
 
                 if ($debug) {
                     error_log("my_choice = ".print_r($my_choice, 1)."");

+ 33 - 0
main/inc/ajax/message.ajax.php

@@ -12,6 +12,39 @@ require_once __DIR__.'/../global.inc.php';
 $action = $_GET['a'];
 
 switch ($action) {
+    case 'get_count_message':
+        $userId = api_get_user_id();
+        $total_invitations = 0;
+        $group_pending_invitations = 0;
+
+        // Setting notifications
+        $count_unread_message = 0;
+        if (api_get_setting('allow_message_tool') == 'true') {
+            // get count unread message and total invitations
+            $count_unread_message = MessageManager::get_number_of_messages(true);
+        }
+
+        if (api_get_setting('allow_social_tool') == 'true') {
+            $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(
+                $userId
+            );
+            $usergroup = new UserGroup();
+            $group_pending_invitations = $usergroup->get_groups_by_user(
+                $userId,
+                GROUP_USER_PERMISSION_PENDING_INVITATION,
+                false
+            );
+            if (!empty($group_pending_invitations)) {
+                $group_pending_invitations = count($group_pending_invitations);
+            } else {
+                $group_pending_invitations = 0;
+            }
+            $total_invitations = intval($number_of_new_messages_of_friend) + $group_pending_invitations + intval($count_unread_message);
+        }
+        $total_invitations = !empty($total_invitations) ? Display::badge($total_invitations) : '';
+
+        echo $total_invitations;
+        break;
     case 'send_message':
         $subject = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : null;
         $messageContent = isset($_REQUEST['content']) ? trim($_REQUEST['content']) : null;

+ 3 - 0
main/inc/ajax/online.ajax.php

@@ -6,6 +6,9 @@ require_once __DIR__.'/../global.inc.php';
 $action = $_GET['a'];
 
 switch ($action) {
+    case 'get_users_online':
+        echo returnNotificationMenu();
+        break;
     case 'load_online_user':
         $images_to_show = MAX_ONLINE_USERS;
         $page = intval($_REQUEST['online_page_nr']);

+ 0 - 1
main/inc/global.inc.php

@@ -597,4 +597,3 @@ if (empty($default_quota)) {
 define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
 // Forcing PclZip library to use a custom temporary folder.
 define('PCLZIP_TEMPORARY_DIR', api_get_path(SYS_ARCHIVE_PATH));
-

+ 3 - 7
main/inc/lib/MoodleImport.php

@@ -217,9 +217,7 @@ class MoodleImport
                                         );
 
                                         if ($importedFiles) {
-                                            foreach ($importedFiles as $old => $new) {
-                                                $questionText = str_replace($old, $new, $questionText);
-                                            }
+                                            $this->fixPathInText($importedFiles, $questionText);
                                         }
 
                                         $questionInstance->updateDescription($questionText);
@@ -749,10 +747,8 @@ class MoodleImport
                 // sets the total weighting of the question
                 $questionInstance->updateWeighting($questionWeighting);
                 $questionInstance->save();
-                // saves the answers into the data base
-
+                // saves the answers into the database
                 $this->fixPathInText($importedFiles, $placeholder);
-
                 $objAnswer->createAnswer($placeholder, 0, '', 0, 1);
                 $objAnswer->save();
 
@@ -948,7 +944,7 @@ class MoodleImport
                     $optionsValues[$slot]['weight'] = 1;
                     $optionsValues[$slot]['size'] = '200';
 
-                    $currentAnswers = $correctAnswer.$othersAnswers;
+                    $currentAnswers = htmlentities($correctAnswer.$othersAnswers);
                     $currentAnswers = '['.substr($currentAnswers, 0, -1).'] ';
                     $answer['questiontext'] = str_replace(
                         '@@PLUGINFILE@@',

+ 52 - 7
main/inc/lib/api.lib.php

@@ -5172,13 +5172,21 @@ function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $directio
  */
 function api_get_access_url($id, $returnDefault = true)
 {
-    $id = intval($id);
-    // Calling the Database:: library dont work this is handmade.
-    $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
-    $sql = "SELECT url, description, active, created_by, tms
-            FROM $table_access_url WHERE id = '$id' ";
-    $res = Database::query($sql);
-    $result = @Database::fetch_array($res);
+    static $staticResult;
+
+    if (isset($staticResult[$id])) {
+        $result = $staticResult[$id];
+    } else {
+        $id = intval($id);
+        // Calling the Database:: library dont work this is handmade.
+        $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql = "SELECT url, description, active, created_by, tms
+                FROM $table_access_url WHERE id = '$id' ";
+        $res = Database::query($sql);
+        $result = @Database::fetch_array($res);
+        $staticResult[$id] = $result;
+    }
+
     // If the result url is 'http://localhost/' (the default) and the root_web
     // (=current url) is different, and the $id is = 1 (which might mean
     // api_get_current_access_url_id() returned 1 by default), then return the
@@ -6072,6 +6080,12 @@ function api_browser_support($format = '')
     $a_versiontemp = explode('.', $browser->getVersion());
     $current_majorver = $a_versiontemp[0];
 
+    static $result;
+
+    if (isset($result[$format])) {
+        return $result[$format];
+    }
+
     // Native svg support
     if ($format == 'svg') {
         if (($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
@@ -6080,22 +6094,28 @@ function api_browser_support($format = '')
             ($current_browser == 'Chrome' && $current_majorver >= 1) ||
             ($current_browser == 'Opera' && $current_majorver >= 9)
         ) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'pdf') {
         //native pdf support
         if ($current_browser == 'Chrome' && $current_majorver >= 6) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'tif' || $format == 'tiff') {
         //native tif support
         if ($current_browser == 'Safari' && $current_majorver >= 5) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'ogg' || $format == 'ogx' || $format == 'ogv' || $format == 'oga') {
@@ -6103,43 +6123,55 @@ function api_browser_support($format = '')
         if (($current_browser == 'Firefox' && $current_majorver >= 3) ||
             ($current_browser == 'Chrome' && $current_majorver >= 3) ||
             ($current_browser == 'Opera' && $current_majorver >= 9)) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'mpg' || $format == 'mpeg') {
         //native mpg support
         if (($current_browser == 'Safari' && $current_majorver >= 5)) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'mp4') {
         //native mp4 support (TODO: Android, iPhone)
         if ($current_browser == 'Android' || $current_browser == 'iPhone') {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'mov') {
         //native mov support( TODO:check iPhone)
         if ($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone') {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'avi') {
         //native avi support
         if ($current_browser == 'Safari' && $current_majorver >= 5) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'wmv') {
         //native wmv support
         if ($current_browser == 'Firefox' && $current_majorver >= 4) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'webm') {
@@ -6150,8 +6182,10 @@ function api_browser_support($format = '')
             ($current_browser == 'Chrome' && $current_majorver >= 9) ||
             $current_browser == 'Android'
         ) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'wav') {
@@ -6164,29 +6198,37 @@ function api_browser_support($format = '')
             $current_browser == 'Android' ||
             $current_browser == 'iPhone'
         ) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'mid' || $format == 'kar') {
         //native midi support (TODO:check Android)
         if ($current_browser == 'Opera' && $current_majorver >= 9 || $current_browser == 'Android') {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'wma') {
         //native wma support
         if ($current_browser == 'Firefox' && $current_majorver >= 4) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'au') {
         //native au support
         if ($current_browser == 'Safari' && $current_majorver >= 5) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == 'mp3') {
@@ -6198,14 +6240,17 @@ function api_browser_support($format = '')
             $current_browser == 'iPhone' ||
             $current_browser == 'Firefox'
         ) {
+            $result[$format] = true;
             return true;
         } else {
+            $result[$format] = false;
             return false;
         }
     } elseif ($format == "check_browser") {
         $array_check_browser = array($current_browser, $current_majorver);
         return $array_check_browser;
     } else {
+        $result[$format] = false;
         return false;
     }
 }

+ 4 - 5
main/inc/lib/banner.lib.php

@@ -211,11 +211,10 @@ function returnNotificationMenu()
         // Display the who's online of the platform
         if ($number &&
             (api_get_setting('showonline', 'world') == 'true' && !$user_id) ||
-                (api_get_setting('showonline', 'users') == 'true' && $user_id)
-           )
-        {
-                $html .= '<li><a href="'.api_get_path(WEB_PATH).'whoisonline.php" target="_self" title="'.get_lang('UsersOnline').'" >'.
-                            Display::return_icon('user.png', get_lang('UsersOnline'), array(), ICON_SIZE_TINY).' '.$number.'</a></li>';
+            (api_get_setting('showonline', 'users') == 'true' && $user_id)
+        ) {
+            $html .= '<li><a href="'.api_get_path(WEB_PATH).'whoisonline.php" target="_self" title="'.get_lang('UsersOnline').'" >'.
+                        Display::return_icon('user.png', get_lang('UsersOnline'), array(), ICON_SIZE_TINY).' '.$number.'</a></li>';
         }
 
         // Display the who's online for the course

+ 86 - 87
main/inc/lib/display.lib.php

@@ -1501,108 +1501,105 @@ class Display
             $sessionId,
             true,
             false,
-            'tet.session_id'
+            'session_id'
         );
 
-        // Get the last edits of all tools of this course.
-        $sql = "SELECT
-                    tet.*,
-                    tet.lastedit_date last_date,
-                    tet.tool tool,
-                    tet.ref ref,
-                    tet.lastedit_type type,
-                    tet.to_group_id group_id,
-                    ctt.image image,
-                    ctt.link link
-                FROM $tool_edit_table tet
-                INNER JOIN $course_tool_table ctt
-                ON tet.c_id = ctt.c_id
-                WHERE
-                    tet.c_id = $course_id AND
-                    tet.lastedit_date > '$oldestTrackDate' ".
-                    // Special hack for work tool, which is called student_publication in c_tool and work in c_item_property :-/ BT#7104
-                    " AND (ctt.name = tet.tool OR (ctt.name = 'student_publication' AND tet.tool = 'work'))
-                    AND ctt.visibility = '1'
-                    AND tet.lastedit_user_id != $user_id $sessionCondition
-                 ORDER BY tet.lastedit_date";
-
-        $res = Database::query($sql);
-        // Get the group_id's with user membership.
+        $hideTools = [TOOL_NOTEBOOK, TOOL_CHAT];
+        // Get current tools in course
+        $sql = "SELECT name, link, image 
+                FROM $course_tool_table 
+                WHERE 
+                    c_id = $course_id AND 
+                    visibility = '1' AND
+                    name NOT IN ('".implode("','", $hideTools)."')
+                ";
+        $result = Database::query($sql);
+        $tools = Database::store_result($result);
+
         $group_ids = GroupManager::get_group_ids($course_info['real_id'], $user_id);
         $group_ids[] = 0; //add group 'everyone'
         $notifications = array();
-        // Filter all last edits of all tools of the course
-        while ($res && ($item_property = Database::fetch_array($res, 'ASSOC'))) {
-            // First thing to check is if the user never entered the tool
-            // or if his last visit was earlier than the last modification.
-            if ((!isset($lastTrackInCourseDate[$item_property['tool']])
-                 || $lastTrackInCourseDate[$item_property['tool']] < $item_property['lastedit_date'])
-                // Drop the tool elements that are part of a group that the
-                // user is not part of.
-                && ((in_array($item_property['to_group_id'], $group_ids)
-                // Drop the dropbox, notebook and chat tools (we don't care)
-                && (
-                        //$item_property['tool'] != TOOL_DROPBOX &&
-                        $item_property['tool'] != TOOL_NOTEBOOK &&
-                        $item_property['tool'] != TOOL_CHAT)
-                   )
-                )
-                // Take only what's visible or "invisible but where the user is a teacher" or where the visibility is unset.
-                && ($item_property['visibility'] == '1'
-                    || ($status == '1' && $item_property['visibility'] == '0')
-                    || !isset($item_property['visibility']))
-            ) {
-                // Also drop announcements and events that are not for the user or his group.
-                if ((
-                        $item_property['tool'] == TOOL_ANNOUNCEMENT ||
-                        $item_property['tool'] == TOOL_CALENDAR_EVENT
-                    ) &&
-                    (
-                        ($item_property['to_user_id'] != $user_id) &&
-                        (!isset($item_property['to_group_id']) || !in_array($item_property['to_group_id'], $group_ids)))
-                ) {
-                   continue;
+        if ($tools) {
+            foreach ($tools as $tool) {
+                $toolName = $tool['name'];
+                // Fix to get student publications
+                if ($toolName == 'student_publication') {
+                    $toolName = 'work';
                 }
-
-                // If it's a survey, make sure the user's invited. Otherwise drop it.
-                if ($item_property['tool'] == TOOL_SURVEY) {
-                    $survey_info = SurveyManager::get_survey($item_property['ref'], 0, $course_code);
-                    if (!empty($survey_info)) {
-                        $invited_users = SurveyUtil::get_invited_users(
-                            $survey_info['code'],
-                            $course_code
-                        );
-                        if (!in_array($user_id, $invited_users['course_users'])) {
-                            continue;
-                        }
-                    }
+                $sql = "SELECT * FROM $tool_edit_table 
+                        WHERE
+                            c_id = $course_id AND
+                            tool = '$toolName' AND
+                            lastedit_type NOT LIKE '%Deleted%' AND
+                            lastedit_type NOT LIKE '%deleted%' AND
+                            lastedit_type NOT LIKE '%DocumentInvisible%' AND
+                            lastedit_date > '$oldestTrackDate' AND 
+                            lastedit_user_id != $user_id $sessionCondition AND 
+                            visibility != 2 AND
+                            (to_user_id IN ('$user_id', '0') OR to_user_id IS NULL) AND
+                            (to_group_id IN ('".implode("','",$group_ids)."') OR to_group_id IS NULL)       
+                        ORDER BY lastedit_date DESC
+                        LIMIT 1";
+
+                $result = Database::query($sql);
+                $latestChange = Database::fetch_array($result);
+                if ($latestChange) {
+                    $latestChange['link'] = $tool['link'];
+                    $latestChange['image'] = $tool['image'];
+                    $latestChange['tool'] = $tool['name'];
+                    $notifications[$toolName] = $latestChange;
                 }
+            }
+        }
 
-                // If it's a learning path, ensure it is currently visible to the user
-                if ($item_property['tool'] == TOOL_LEARNPATH) {
-                    if (!learnpath::is_lp_visible_for_student($item_property['ref'], $user_id, $course_code)) {
+        // Show all tool icons where there is something new.
+        $return = '&nbsp;';
+        foreach ($notifications as $notification) {
+            $toolName = $notification['tool'];
+            if (!
+                (
+                    $notification['visibility'] == '1'  ||
+                    ($status == '1' && $notification['visibility'] == '0') ||
+                    !isset($notification['visibility'])
+                )
+            ) {
+                continue;
+            }
+
+            if ($toolName == TOOL_SURVEY) {
+                $survey_info = SurveyManager::get_survey($notification['ref'], 0, $course_code);
+                if (!empty($survey_info)) {
+                    $invited_users = SurveyUtil::get_invited_users(
+                        $survey_info['code'],
+                        $course_code
+                    );
+                    if (!in_array($user_id, $invited_users['course_users'])) {
                         continue;
                     }
                 }
+            }
 
-                if ($item_property['tool'] == TOOL_DROPBOX) {
-                    $item_property['link'] = 'dropbox/dropbox_download.php?id='.$item_property['ref'];
+            if ($notification['tool'] == TOOL_LEARNPATH) {
+                if (!learnpath::is_lp_visible_for_student($notification['ref'], $user_id, $course_code)) {
+                    continue;
                 }
+            }
 
-                if ($item_property['tool'] == 'work' &&
-                    $item_property['type'] == 'DirectoryCreated'
-                ) {
-                    $item_property['lastedit_type'] = 'WorkAdded';
-                }
-                $notifications[$item_property['tool']] = $item_property;
+            if ($notification['tool'] == TOOL_DROPBOX) {
+                $notification['link'] = 'dropbox/dropbox_download.php?id='.$notification['ref'];
             }
-        }
 
-        // Show all tool icons where there is something new.
-        $return = '&nbsp;';
-        foreach($notifications as $notification) {
-            $lastDate = date('d/m/Y H:i', convert_sql_date($notification['lastedit_date']));
+            if ($notification['tool'] == 'work' &&
+                $notification['lastedit_type'] == 'DirectoryCreated'
+            ) {
+                $notification['lastedit_type'] = 'WorkAdded';
+            }
+
+            $lastDate = api_get_local_time($notification['lastedit_date']);
             $type = $notification['lastedit_type'];
+            if ($type == 'CalendareventVisible') {
+                $type = 'Visible';
+            }
             $label = get_lang('TitleNotification').": ".get_lang($type)." ($lastDate)";
 
             if (strpos($notification['link'], '?') === false) {
@@ -1610,9 +1607,11 @@ class Display
             } else {
                 $notification['link'] = $notification['link'].'&notification=1';
             }
-            $imagen = substr($notification['image'], 0, -4).'.png';
+
+            $image = substr($notification['image'], 0, -4).'.png';
+
             $return .= Display::url(
-                Display::return_icon($imagen, $label),
+                Display::return_icon($image, $label),
                 api_get_path(WEB_CODE_PATH).
                 $notification['link'].'&cidReq='.$course_code.
                 '&ref='.$notification['ref'].

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

@@ -1654,7 +1654,8 @@ class DocumentManager
         $course_info,
         $session_id,
         $user_id,
-        $admins_can_see_everything = true
+        $admins_can_see_everything = true,
+        $userIsSubscribed = null
     ) {
         $user_in_course = false;
 
@@ -1671,12 +1672,18 @@ class DocumentManager
 
         //2. Course and Session visibility are handle in local.inc.php/global.inc.php
         //3. Checking if user exist in course/session
-
         if ($session_id == 0) {
-            if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code']) || api_is_platform_admin()
-            ) {
+            if (is_null($userIsSubscribed)) {
+                $userIsSubscribed = CourseManager::is_user_subscribed_in_course(
+                    $user_id,
+                    $course_info['code']
+                );
+            }
+
+            if ($userIsSubscribed === true || api_is_platform_admin()) {
                 $user_in_course = true;
             }
+
             // Check if course is open then we can consider that the student is registered to the course
             if (isset($course_info) &&
                 in_array(
@@ -1704,12 +1711,15 @@ class DocumentManager
         }
 
         // 4. Checking document visibility (i'm repeating the code in order to be more clear when reading ) - jm
-
         if ($user_in_course) {
-
             // 4.1 Checking document visibility for a Course
             if ($session_id == 0) {
-                $item_info = api_get_item_property_info($course_info['real_id'], 'document', $doc_id, 0);
+                $item_info = api_get_item_property_info(
+                    $course_info['real_id'],
+                    'document',
+                    $doc_id,
+                    0
+                );
 
                 if (isset($item_info['visibility'])) {
                     // True for admins if document exists
@@ -1761,7 +1771,7 @@ class DocumentManager
 
     /**
      * Allow attach a certificate to a course
-     * @param int $course_id
+     * @param string $course_id
      * @param int $document_id
      * @param int $session_id
      * @return void
@@ -1782,13 +1792,13 @@ class DocumentManager
             $sql_session = '';
         }
         $sql = 'UPDATE ' . $tbl_category . ' SET document_id="' . intval($document_id) . '"
-                WHERE c_id ="' . Database::escape_string($course_id) . '" ' . $sql_session;
+                WHERE course_code="' . Database::escape_string($course_id) . '" ' . $sql_session;
         Database::query($sql);
     }
 
     /**
      * get the document id of default certificate
-     * @param int $course_id
+     * @param string $course_id
      * @param int $session_id
      *
      * @return int The default certificate id
@@ -1809,7 +1819,7 @@ class DocumentManager
             $sql_session = '';
         }
         $sql = 'SELECT document_id FROM ' . $tbl_category . '
-                WHERE c_id ="' . Database::escape_string($course_id) . '" ' . $sql_session;
+                WHERE course_code="' . Database::escape_string($course_id) . '" ' . $sql_session;
 
         $rs = Database::query($sql);
         $num = Database::num_rows($rs);
@@ -1837,7 +1847,7 @@ class DocumentManager
         $course_id = $course_info['real_id'];
 
         $document_id = self::get_default_certificate_id(
-            $course_id,
+            $course_code,
             $sessionId
         );
 
@@ -1917,7 +1927,7 @@ class DocumentManager
         $teacher_last_name = $teacher_info['lastname'];
 
         // info gradebook certificate
-        $info_grade_certificate = UserManager::getInfoGradeBookCertificate($course_info['real_id'], $user_id);
+        $info_grade_certificate = UserManager::get_info_gradebook_certificate($course_id, $user_id);
 
         $date_certificate = $info_grade_certificate['created_at'];
         $date_long_certificate = '';
@@ -1996,7 +2006,7 @@ class DocumentManager
 
     /**
      * Remove default certificate
-     * @param int $course_id
+     * @param string $course_id The course code
      * @param int $default_certificate_id The document id of the default certificate
      * @return void
      */
@@ -2020,7 +2030,7 @@ class DocumentManager
 
             $sql = 'UPDATE ' . $tbl_category . ' SET document_id=null
                     WHERE
-                        c_id = "' . Database::escape_string($course_id) . '" AND
+                        course_code = "' . Database::escape_string($course_id) . '" AND
                         document_id="' . $default_certificate_id . '" ' . $sql_session;
             Database::query($sql);
         }
@@ -2028,12 +2038,11 @@ class DocumentManager
 
     /**
      * Create directory certificate
-     * @param string $courseCode
+     * @param array $courseInfo
      * @return void
      */
-    public static function create_directory_certificate_in_course($courseCode)
+    public static function create_directory_certificate_in_course($courseInfo)
     {
-        $courseInfo = api_get_course_info($courseCode);
         if (!empty($courseInfo)) {
             $to_group_id = 0;
             $to_user_id = null;
@@ -2098,7 +2107,8 @@ class DocumentManager
     {
         $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
         $course_id = api_get_course_int_id();
-        $sql = "SELECT id FROM $tbl_document WHERE c_id = $course_id AND path='/certificates' ";
+        $sql = "SELECT id FROM $tbl_document 
+                WHERE c_id = $course_id AND path='/certificates' ";
         $rs = Database::query($sql);
         $row = Database::fetch_array($rs);
         return $row['id'];
@@ -3163,7 +3173,8 @@ class DocumentManager
         $percentage = round($percentage, 1);
         $message = get_lang('YouAreCurrentlyUsingXOfYourX');
         $message = sprintf($message, $already_consumed_space_m, $percentage . '%', $course_quota_m . ' ');
-        echo Display::div($message, array('id' => 'document_quota'));
+
+        return Display::div($message, array('id' => 'document_quota'));
     }
 
     /**
@@ -3194,7 +3205,7 @@ class DocumentManager
      */
     public static function generate_jplayer_jquery($params = array())
     {
-        $js_path = api_get_path(WEB_LIBRARY_JS_PATH);
+        $js_path = api_get_path(WEB_LIBRARY_PATH) . 'javascript/';
 
         $js = '
             $("#jquery_jplayer_' . $params['count'] . '").jPlayer({
@@ -3229,7 +3240,6 @@ class DocumentManager
     public static function generate_media_preview($i, $type = 'simple')
     {
         $i = intval($i);
-
         $extra_controls = $progress = '';
         if ($type == 'advanced') {
             $extra_controls = ' <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
@@ -4434,7 +4444,7 @@ class DocumentManager
      */
     public static function readNanogongFile($file)
     {
-        $nanoGongJarFile = api_get_path(WEB_LIBRARY_JS_PATH).'nanogong/nanogong.jar';
+        $nanoGongJarFile = api_get_path(WEB_LIBRARY_PATH).'nanogong/nanogong.jar';
         $html = '<applet id="applet" archive="'.$nanoGongJarFile.'" code="gong.NanoGong" width="160" height="95">';
         $html .= '<param name="SoundFileURL" value="'.$file.'" />';
         $html .= '<param name="ShowSaveButton" value="false" />';
@@ -4755,7 +4765,7 @@ class DocumentManager
         }
 
         if ($fromBaseCourse) {
-            $defaultCertificateId = self::get_default_certificate_id($courseData['real_id'], 0);
+            $defaultCertificateId = self::get_default_certificate_id($courseData['code'], 0);
 
             if (!empty($defaultCertificateId)) {
                 // We have a certificate from the course base
@@ -4809,12 +4819,12 @@ class DocumentManager
         );
 
         $defaultCertificateId = self::get_default_certificate_id(
-            $courseData['real_id'],
+            $courseData['code'],
             $sessionId
         );
 
         if (!isset($defaultCertificateId)) {
-            self::attach_gradebook_certificate($courseData['real_id'], $documentId, $sessionId);
+            self::attach_gradebook_certificate($courseData['code'], $documentId, $sessionId);
         }
     }
 
@@ -5113,7 +5123,8 @@ class DocumentManager
             }
             $folder_sql = implode("','", $escaped_folders);
 
-            $sql = "SELECT * FROM $doc_table
+            $sql = "SELECT path, title 
+                    FROM $doc_table
                     WHERE 
                         filetype = 'folder' AND 
                         c_id = $course_id AND 
@@ -5193,22 +5204,30 @@ class DocumentManager
      * Create a html hyperlink depending on if it's a folder or a file
      *
      * @param array $document_data
+     * @param array $course_info
      * @param int $show_as_icon - if it is true, only a clickable icon will be shown
      * @param int $visibility (1/0)
      * @param int $counter
+     * @param int $size
+     * @param bool $isAllowedToEdit
      *
      * @return string url
      */
     public static function create_document_link(
         $document_data,
+        $course_info,
         $show_as_icon = false,
         $counter = null,
-        $visibility
+        $visibility,
+        $size = 0,
+        $isAllowedToEdit = false
     ) {
         global $dbl_click_id;
-        $course_info = api_get_course_info();
+
+        $current_session_id = api_get_session_id();
+        $courseParams = api_get_cidreq();
         $www = api_get_path(WEB_COURSE_PATH) . $course_info['path'] . '/document';
-        $webOdflist = DocumentManager::get_web_odf_extension_list();
+        $webODFList = DocumentManager::get_web_odf_extension_list();
 
         // Get the title or the basename depending on what we're using
         if ($document_data['title'] != '') {
@@ -5218,9 +5237,7 @@ class DocumentManager
         }
 
         $filetype = $document_data['filetype'];
-        $size = $filetype == 'folder' ? get_total_folder_size($document_data['path'], api_is_allowed_to_edit(null, true)) : $document_data['size'];
         $path = $document_data['path'];
-
         $url_path = urlencode($document_data['path']);
 
         // Add class="invisible" on invisible files
@@ -5231,7 +5248,7 @@ class DocumentManager
 
         if (!$show_as_icon) {
             // Build download link (icon)
-            $forcedownload_link = ($filetype == 'folder') ? api_get_self() . '?' . api_get_cidreq() . '&action=downloadfolder&id=' . $document_data['id'] : api_get_self() . '?' . api_get_cidreq() . '&amp;action=download&amp;id=' . $document_data['id'];
+            $forcedownload_link = ($filetype == 'folder') ? api_get_self() . '?' . $courseParams . '&action=downloadfolder&id=' . $document_data['id'] : api_get_self() . '?' . $courseParams . '&amp;action=download&amp;id=' . $document_data['id'];
             // Folder download or file download?
             $forcedownload_icon = ($filetype == 'folder') ? 'save_pack.png' : 'save.png';
             // Prevent multiple clicks on zipped folder download
@@ -5250,18 +5267,18 @@ class DocumentManager
             $is_browser_viewable_file = self::is_browser_viewable($ext);
 
             if ($is_browser_viewable_file) {
-                if ($ext == 'pdf' || in_array($ext, $webOdflist)) {
-                    $url = api_get_self() . '?' . api_get_cidreq() . '&amp;action=download&amp;id=' . $document_data['id'];
+                if ($ext == 'pdf' || in_array($ext, $webODFList)) {
+                    $url = api_get_self() . '?' . $courseParams . '&amp;action=download&amp;id=' . $document_data['id'];
                 } else {
-                    $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
+                    $url = 'showinframes.php?' . $courseParams . '&id=' . $document_data['id'];
                 }
             } else {
                 // url-encode for problematic characters (we may not call them dangerous characters...)
-                $path = str_replace('%2F', '/', $url_path) . '?' . api_get_cidreq();
+                $path = str_replace('%2F', '/', $url_path) . '?' . $courseParams;
                 $url = $www . $path;
             }
         } else {
-            $url = api_get_self() . '?' . api_get_cidreq() . '&id=' . $document_data['id'];
+            $url = api_get_self() . '?' . $courseParams . '&id=' . $document_data['id'];
         }
 
         // The little download icon
@@ -5291,16 +5308,14 @@ class DocumentManager
             $tooltip_title_alt = get_lang('DefaultCourseImages');
         }
 
-        $current_session_id = api_get_session_id();
         $copy_to_myfiles = $open_in_new_window_link = null;
-
         $curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : null;
         $send_to = null;
         $checkExtension = $path;
 
         if (!$show_as_icon) {
             if ($filetype == 'folder') {
-                if (api_is_allowed_to_edit() ||
+                if ($isAllowedToEdit ||
                     api_is_platform_admin() ||
                     api_get_setting('students_download_folders') == 'true'
                 ) {
@@ -5308,13 +5323,13 @@ class DocumentManager
                     if (DocumentManager::is_shared_folder($curdirpath, $current_session_id)) {
                         if (preg_match('/shared_folder\/sf_user_' . api_get_user_id() . '$/', urldecode($forcedownload_link)) ||
                             preg_match('/shared_folder_session_' . $current_session_id . '\/sf_user_' . api_get_user_id() . '$/', urldecode($forcedownload_link)) ||
-                            api_is_allowed_to_edit() || api_is_platform_admin()
+                            $isAllowedToEdit || api_is_platform_admin()
                         ) {
                             $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>';
                         }
                     } elseif (!preg_match('/shared_folder/', urldecode($forcedownload_link)) ||
-                        api_is_allowed_to_edit() ||
+                        $isAllowedToEdit ||
                         api_is_platform_admin()
                     ) {
                         $force_download_html = ($size == 0) ? '' : '<a href="' . $forcedownload_link . '" style="float:right"' . $prevent_multiple_click . '>' .
@@ -5330,9 +5345,8 @@ class DocumentManager
             if (api_get_setting('allow_my_files') === 'true' &&
                 api_get_setting('users_copy_files') === 'true'
             ) {
-                $copy_myfiles_link = ($filetype == 'file') ? api_get_self() . '?' . api_get_cidreq() . '&action=copytomyfiles&id=' . $document_data['id'] : api_get_self() . '?' . api_get_cidreq();
+                $copy_myfiles_link = ($filetype == 'file') ? api_get_self() . '?' . $courseParams . '&action=copytomyfiles&id=' . $document_data['id'] : api_get_self() . '?' . $courseParams;
                 if ($filetype == 'file') {
-
                     $copy_to_myfiles = '<a href="' . $copy_myfiles_link . '" style="float:right"' . $prevent_multiple_click . '>' .
                         Display::return_icon('briefcase.png', get_lang('CopyToMyFiles'), array(), ICON_SIZE_SMALL) . '&nbsp;&nbsp;</a>';
 
@@ -5344,17 +5358,17 @@ class DocumentManager
 
             $pdf_icon = '';
             $extension = pathinfo($path, PATHINFO_EXTENSION);
-            if (!api_is_allowed_to_edit() &&
+            if (!$isAllowedToEdit &&
                 api_get_setting('students_export2pdf') == 'true' &&
                 $filetype == 'file' &&
                 in_array($extension, array('html', 'htm'))
             ) {
-                $pdf_icon = ' <a style="float:right".' . $prevent_multiple_click . ' href="' . api_get_self() . '?' . api_get_cidreq() . '&action=export_to_pdf&id=' . $document_data['id'] . '">' .
+                $pdf_icon = ' <a style="float:right".' . $prevent_multiple_click . ' href="' . api_get_self() . '?' . $courseParams . '&action=export_to_pdf&id=' . $document_data['id'] . '">' .
                     Display::return_icon('pdf.png', get_lang('Export2PDF'), array(), ICON_SIZE_SMALL) . '</a> ';
             }
 
             if ($is_browser_viewable_file) {
-                $open_in_new_window_link = '<a href="' . $www . str_replace('%2F', '/', $url_path) . '?' . api_get_cidreq() . '" style="float:right"' . $prevent_multiple_click . ' target="_blank">' .
+                $open_in_new_window_link = '<a href="' . $www . str_replace('%2F', '/', $url_path) . '?' . $courseParams . '" style="float:right"' . $prevent_multiple_click . ' target="_blank">' .
                     Display::return_icon('open_in_new_window.png', get_lang('OpenInANewWindow'), array(), ICON_SIZE_SMALL) . '&nbsp;&nbsp;</a>';
             }
 
@@ -5379,7 +5393,7 @@ class DocumentManager
                     preg_match('/svg$/i', urldecode($checkExtension))
                 ) {
                     // Simpler version of showinframesmin.php with no headers
-                    $url = 'show_content.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
+                    $url = 'show_content.php?' . $courseParams . '&id=' . $document_data['id'];
                     $class = 'ajax';
                     if ($visibility == false) {
                         $class = "ajax text-muted";
@@ -5399,12 +5413,12 @@ class DocumentManager
                 } else {
                     // For a "PDF Download" of the file.
                     $pdfPreview = null;
-                    if ($ext != 'pdf' && !in_array($ext, $webOdflist)) {
-                        $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
+                    if ($ext != 'pdf' && !in_array($ext, $webODFList)) {
+                        $url = 'showinframes.php?' . $courseParams . '&id=' . $document_data['id'];
                     } else {
                         $pdfPreview = Display::url(
                             Display::return_icon('preview.gif', get_lang('Preview')),
-                            api_get_path(WEB_CODE_PATH).'document/showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'],
+                            api_get_path(WEB_CODE_PATH).'document/showinframes.php?' . $courseParams . '&id=' . $document_data['id'],
                             array('style' => 'float:right')
                         );
                     }
@@ -5441,18 +5455,18 @@ class DocumentManager
                         preg_match('/bmp$/i', urldecode($checkExtension)) ||
                         preg_match('/svg$/i', urldecode($checkExtension))
                     ) {
-                        $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
+                        $url = 'showinframes.php?' . $courseParams . '&id=' . $document_data['id'];
                         return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
-                        DocumentManager::build_document_icon_tag($filetype, $path) .
+                        DocumentManager::build_document_icon_tag($filetype, $path, $isAllowedToEdit) .
                         Display::return_icon('shared.png', get_lang('ResourceShared'), array()) . '</a>';
                     } else {
                         return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
-                        DocumentManager::build_document_icon_tag($filetype, $path) .
+                        DocumentManager::build_document_icon_tag($filetype, $path, $isAllowedToEdit) .
                         Display::return_icon('shared.png', get_lang('ResourceShared'), array()) . '</a>';
                     }
                 } else {
                     return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" target="' . $target . '"' . $visibility_class . ' style="float:left">' .
-                    DocumentManager::build_document_icon_tag($filetype, $path) .
+                    DocumentManager::build_document_icon_tag($filetype, $path, $isAllowedToEdit) .
                     Display::return_icon('shared.png', get_lang('ResourceShared'), array()) . '</a>';
                 }
             } else {
@@ -5476,16 +5490,16 @@ class DocumentManager
                         preg_match('/bmp$/i', urldecode($checkExtension)) ||
                         preg_match('/svg$/i', urldecode($checkExtension))
                     ) {
-                        $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id']; //without preview
+                        $url = 'showinframes.php?' . $courseParams . '&id=' . $document_data['id']; //without preview
                         return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
-                        DocumentManager::build_document_icon_tag($filetype, $path) . '</a>';
+                        DocumentManager::build_document_icon_tag($filetype, $path, $isAllowedToEdit) . '</a>';
                     } else {
                         return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
-                        DocumentManager::build_document_icon_tag($filetype, $path) . '</a>';
+                        DocumentManager::build_document_icon_tag($filetype, $path, $isAllowedToEdit) . '</a>';
                     }
                 } else {
                     return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" target="' . $target . '"' . $visibility_class . ' style="float:left">' .
-                    DocumentManager::build_document_icon_tag($filetype, $path) . '</a>';
+                    DocumentManager::build_document_icon_tag($filetype, $path, $isAllowedToEdit) . '</a>';
                 }
             }
         }
@@ -5496,87 +5510,89 @@ class DocumentManager
      *
      * @param string $type (file/folder)
      * @param string $path
+     * @param bool $isAllowedToEdit
      * @return string img html tag
      */
-    public static function build_document_icon_tag($type, $path)
+    public static function build_document_icon_tag($type, $path, $isAllowedToEdit = null)
     {
         $basename = basename($path);
         $current_session_id = api_get_session_id();
-        $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
+        if (is_null($isAllowedToEdit)) {
+            $isAllowedToEdit = api_is_allowed_to_edit(null, true);
+        }
         $user_image = false;
         if ($type == 'file') {
             $icon = choose_image($basename);
-
             $basename = substr(strrchr($basename, '.'), 1);
         } else {
             if ($path == '/shared_folder') {
                 $icon = 'folder_users.png';
-                if ($is_allowed_to_edit) {
+                if ($isAllowedToEdit) {
                     $basename = get_lang('HelpUsersFolder');
                 } else {
                     $basename = get_lang('UserFolders');
                 }
             } elseif (strstr($basename, 'sf_user_')) {
-                $userinfo = api_get_user_info(substr($basename, 8));
-                $icon = $userinfo['avatar_small'];
-
-                $basename = get_lang('UserFolder') . ' ' . $userinfo['complete_name'];
+                $userInfo = api_get_user_info(substr($basename, 8));
+                $icon = $userInfo['avatar_small'];
+                $basename = get_lang('UserFolder') . ' ' . $userInfo['complete_name'];
                 $user_image = true;
             } elseif (strstr($path, 'shared_folder_session_')) {
-                if ($is_allowed_to_edit) {
-                    $basename = '***(' . api_get_session_name($current_session_id) . ')*** ' . get_lang('HelpUsersFolder');
+                $sessionName = api_get_session_name($current_session_id);
+                if ($isAllowedToEdit) {
+                    $basename = '***(' . $sessionName . ')*** ' . get_lang('HelpUsersFolder');
                 } else {
-                    $basename = get_lang('UserFolders') . ' (' . api_get_session_name($current_session_id) . ')';
+                    $basename = get_lang('UserFolders') . ' (' . $sessionName . ')';
                 }
                 $icon = 'folder_users.png';
             } else {
-                $icon = 'folder_document.png';
+                $icon = 'folder_document.gif';
 
                 if ($path == '/audio') {
                     $icon = 'folder_audio.gif';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpDefaultDirDocuments');
                     } else {
                         $basename = get_lang('Audio');
                     }
                 } elseif ($path == '/flash') {
                     $icon = 'folder_flash.gif';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpDefaultDirDocuments');
                     } else {
                         $basename = get_lang('Flash');
                     }
                 } elseif ($path == '/images') {
                     $icon = 'folder_images.gif';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpDefaultDirDocuments');
                     } else {
                         $basename = get_lang('Images');
                     }
                 } elseif ($path == '/video') {
                     $icon = 'folder_video.gif';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpDefaultDirDocuments');
                     } else {
                         $basename = get_lang('Video');
                     }
                 } elseif ($path == '/images/gallery') {
                     $icon = 'folder_gallery.gif';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpDefaultDirDocuments');
                     } else {
                         $basename = get_lang('Gallery');
                     }
                 } elseif ($path == '/chat_files') {
                     $icon = 'folder_chat.png';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpFolderChat');
                     } else {
                         $basename = get_lang('ChatFiles');
                     }
                 } elseif ($path == '/learning_path') {
                     $icon = 'folder_learningpath.gif';
-                    if (api_is_allowed_to_edit()) {
+                    if ($isAllowedToEdit) {
                         $basename = get_lang('HelpFolderLearningPaths');
                     } else {
                         $basename = get_lang('LearningPaths');
@@ -5584,9 +5600,11 @@ class DocumentManager
                 }
             }
         }
+
         if ($user_image) {
             return Display::img($icon, $basename, array(), false);
         }
+
         return Display::return_icon($icon, $basename, array(), ICON_SIZE_MEDIUM);
     }
 
@@ -5603,6 +5621,7 @@ class DocumentManager
     public static function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0, $visibility)
     {
         $sessionId = api_get_session_id();
+        $courseParams = api_get_cidreq();
         $web_odf_extension_list = DocumentManager::get_web_odf_extension_list();
         $document_id = $document_data['id'];
         $type = $document_data['filetype'];
@@ -5657,16 +5676,16 @@ class DocumentManager
         if ($is_read_only /* or ($session_id!=api_get_session_id()) */) {
             if (api_is_course_admin() || api_is_platform_admin()) {
                 if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
-                    $modify_icons = '<a href="edit_draw.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
+                    $modify_icons = '<a href="edit_draw.php?' . $courseParams . '&id=' . $document_id . '">' .
                         Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                 } elseif (in_array($extension, $web_odf_extension_list)  && api_get_setting('enabled_support_odf') === true) {
-                    $modify_icons = '<a href="edit_odf.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
+                    $modify_icons = '<a href="edit_odf.php?' . $courseParams . '&id=' . $document_id . '">' .
                         Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                 } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
-                    $modify_icons = '<a href="edit_paint.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
+                    $modify_icons = '<a href="edit_paint.php?' . $courseParams . '&id=' . $document_id . '">' .
                         Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                 } else {
-                    $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&id=' . $document_id. '">' .
+                    $modify_icons = '<a href="edit_document.php?' . $courseParams . '&id=' . $document_id. '">' .
                         Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                 }
             } else {
@@ -5683,21 +5702,21 @@ class DocumentManager
                 $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
             } elseif ($is_certificate_mode ) {
                 // gradebook category doesn't seem to be taken into account
-                $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '&curdirpath=/certificates">' . Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
+                $modify_icons = '<a href="edit_document.php?' . $courseParams . '&amp;id=' . $document_id . '&curdirpath=/certificates">' . Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
             } else {
-                if (api_get_session_id()) {
-                    if ($document_data['session_id'] == api_get_session_id()) {
+                if ($sessionId) {
+                    if ($document_data['session_id'] == $sessionId) {
                         if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
-                            $modify_icons = '<a href="edit_draw.php?' . api_get_cidreq() . '&amp;id=' . $document_id  . '">' .
+                            $modify_icons = '<a href="edit_draw.php?' . $courseParams . '&amp;id=' . $document_id  . '">' .
                                 Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                         } elseif (in_array($extension, $web_odf_extension_list)  && api_get_setting('enabled_support_odf') === true) {
-                            $modify_icons = '<a href="edit_odf.php?' . api_get_cidreq() . '&id=' . $document_id  . '">' .
+                            $modify_icons = '<a href="edit_odf.php?' . $courseParams . '&id=' . $document_id  . '">' .
                                 Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                         } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
-                            $modify_icons = '<a href="edit_paint.php?' . api_get_cidreq() . '&id=' . $document_id  . '">' .
+                            $modify_icons = '<a href="edit_paint.php?' . $courseParams . '&id=' . $document_id  . '">' .
                                 Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                         } else {
-                            $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&amp;id=' . $document_id  . '">' .
+                            $modify_icons = '<a href="edit_document.php?' . $courseParams . '&amp;id=' . $document_id  . '">' .
                                 Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                         }
                     } else {
@@ -5705,16 +5724,16 @@ class DocumentManager
                     }
                 } else {
                     if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
-                        $modify_icons = '<a href="edit_draw.php?' . api_get_cidreq() . '&amp;id=' . $document_id  . '">' .
+                        $modify_icons = '<a href="edit_draw.php?' . $courseParams . '&amp;id=' . $document_id  . '">' .
                             Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                     } elseif (in_array($extension, $web_odf_extension_list)  && api_get_setting('enabled_support_odf') === true) {
-                        $modify_icons = '<a href="edit_odf.php?' . api_get_cidreq() . '&id=' . $document_id  . '">' .
+                        $modify_icons = '<a href="edit_odf.php?' . $courseParams . '&id=' . $document_id  . '">' .
                             Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                     } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
-                        $modify_icons = '<a href="edit_paint.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '">' .
+                        $modify_icons = '<a href="edit_paint.php?' . $courseParams . '&amp;id=' . $document_id . '">' .
                             Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                     } else {
-                        $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&amp;id=' . $document_id  . '">' .
+                        $modify_icons = '<a href="edit_document.php?' . $courseParams . '&amp;id=' . $document_id  . '">' .
                             Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
                     }
                 }
@@ -5724,15 +5743,15 @@ class DocumentManager
             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>';
             } else {
-                if (api_get_session_id()) {
-                    if ($document_data['session_id'] == api_get_session_id()) {
-                        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;move=' . $document_id .  '">' .
+                if ($sessionId) {
+                    if ($document_data['session_id'] == $sessionId) {
+                        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;id=' . $parent_id . '&amp;move=' . $document_id .  '">' .
                             Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
                     } else {
                         $modify_icons .= '&nbsp;' . Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
                     }
                 } else {
-                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;move=' . $document_id .  '">' .
+                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;id=' . $parent_id . '&amp;move=' . $document_id .  '">' .
                         Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
                 }
             }
@@ -5747,7 +5766,7 @@ class DocumentManager
                     } else {
                         $tip_visibility = get_lang('Hide');
                     }
-                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;' . $visibility_command . '=' . $id . '&amp;' . $sort_params . '">' .
+                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;id=' . $parent_id . '&amp;' . $visibility_command . '=' . $id . '&amp;' . $sort_params . '">' .
                         Display::return_icon($visibility_icon . '.png', $tip_visibility, '', ICON_SIZE_SMALL) . '</a>';
                 }
             }
@@ -5760,24 +5779,24 @@ class DocumentManager
 
                 if (isset($_GET['curdirpath']) &&
                     $_GET['curdirpath'] == '/certificates' &&
-                    DocumentManager::get_default_certificate_id(api_get_course_int_id()) == $id
+                    DocumentManager::get_default_certificate_id(api_get_course_id()) == $id
                 ) {
-                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id.'&amp;' . $sort_params . 'delete_certificate_id=' . $id . '" onclick="return confirmation(\'' . $titleToShow . '\');">' .
+                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id.'&amp;' . $sort_params . 'delete_certificate_id=' . $id . '" onclick="return confirmation(\'' . $titleToShow . '\');">' .
                         Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
                 } else {
                     if ($is_certificate_mode) {
-                        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid=' . $document_id  . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow . '\');">' .
+                        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid=' . $document_id  . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow . '\');">' .
                             Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
                     } else {
-                        if (api_get_session_id()) {
-                            if ($document_data['session_id'] == api_get_session_id()) {
-                                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id  . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow . '\');">'.
+                        if ($sessionId) {
+                            if ($document_data['session_id'] == $sessionId) {
+                                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id  . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow . '\');">'.
                                     Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
                             } else {
                                 $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'), array(), ICON_SIZE_SMALL);
                             }
                         } else {
-                            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow. '\');">' .
+                            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow. '\');">' .
                                 Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
                         }
                     }
@@ -5806,12 +5825,12 @@ class DocumentManager
         if ($type == 'file' && ($extension == 'html' || $extension == 'htm')) {
             if ($is_template == 0) {
                 if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] != '/certificates') || !isset($_GET['curdirpath'])) {
-                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&amp;add_as_template=' . $id .  '&amp;' . $sort_params . '">' .
+                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&amp;add_as_template=' . $id .  '&amp;' . $sort_params . '">' .
                         Display::return_icon('wizard.png', get_lang('AddAsTemplate'), array(), ICON_SIZE_SMALL) . '</a>';
                 }
                 if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates') {//allow attach certificate to course
                     $visibility_icon_certificate = 'nocertificate';
-                    if (DocumentManager::get_default_certificate_id(api_get_course_int_id()) == $id) {
+                    if (DocumentManager::get_default_certificate_id(api_get_course_id()) == $id) {
                         $visibility_icon_certificate = 'certificate';
                         $certificate = get_lang('DefaultCertificate');
                         $preview = get_lang('PreviewCertificate');
@@ -5821,20 +5840,20 @@ class DocumentManager
                         $certificate = get_lang('NoDefaultCertificate');
                     }
                     if (isset($_GET['selectcat'])) {
-                        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&amp;selectcat=' . intval($_GET['selectcat']) . '&amp;set_certificate=' . $id . '&amp;' . $sort_params . '">';
+                        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&amp;selectcat=' . intval($_GET['selectcat']) . '&amp;set_certificate=' . $id . '&amp;' . $sort_params . '">';
                         $modify_icons .= Display::return_icon($visibility_icon_certificate.'.png', $certificate);
                         $modify_icons .= '</a>';
                         if ($is_preview) {
-                            $modify_icons .= '&nbsp;<a target="_blank"  href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&amp;set_preview=' . $id . '&amp;' . $sort_params . '" >' .
+                            $modify_icons .= '&nbsp;<a target="_blank"  href="' . api_get_self() . '?' . $courseParams . '&amp;curdirpath=' . $curdirpath . '&amp;set_preview=' . $id . '&amp;' . $sort_params . '" >' .
                                 Display::return_icon('preview_view.png', $preview, '', ICON_SIZE_SMALL) . '</a>';
                         }
                     }
                 }
             } else {
-                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&curdirpath=' . $curdirpath . '&amp;remove_as_template=' . $id. '&amp;' . $sort_params . '">' .
+                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&curdirpath=' . $curdirpath . '&amp;remove_as_template=' . $id. '&amp;' . $sort_params . '">' .
                     Display::return_icon('wizard_na.png', get_lang('RemoveAsTemplate'), '', ICON_SIZE_SMALL) . '</a>';
             }
-            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&action=export_to_pdf&id=' . $id . '">' .
+            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . $courseParams . '&action=export_to_pdf&id=' . $id . '">' .
                 Display::return_icon('pdf.png', get_lang('Export2PDF'), array(), ICON_SIZE_SMALL) . '</a>';
         }
 
@@ -6093,8 +6112,8 @@ class DocumentManager
         if (!($result = in_array($file_extension, $allowed_extensions))) { // Assignment + a logical check.
             return false;
         }
-        //check native support (Explorer, Opera, Firefox, Chrome, Safari)
 
+        //check native support (Explorer, Opera, Firefox, Chrome, Safari)
         if ($file_extension == "pdf") {
             return api_browser_support('pdf');
         } elseif ($file_extension == "mp3") {

+ 12 - 14
main/inc/lib/exercise.lib.php

@@ -3771,19 +3771,18 @@ HOTSPOT;
                 );
             }
 
-            // Send notification ..
-            if (!api_is_allowed_to_edit(null, true) && !api_is_excluded_user_type()
+            // Send notification
+            if (!api_is_allowed_to_edit(null, true) &&
+                !api_is_excluded_user_type()
             ) {
-                if (api_get_course_setting(
-                        'email_alert_manager_on_new_quiz'
-                    ) == 1
-                ) {
-                    $objExercise->send_mail_notification_for_exam(
-                        $question_list_answers,
-                        $origin,
-                        $exe_id
-                    );
-                }
+                $objExercise->send_mail_notification_for_exam(
+                    $question_list_answers,
+                    $origin,
+                    $exe_id,
+                    $total_score,
+                    $total_weight
+                );
+
                 $objExercise->send_notification_for_open_questions(
                     $question_list_answers,
                     $origin,
@@ -3810,8 +3809,7 @@ HOTSPOT;
         $score,
         $weight,
         $check_pass_percentage = false
-    )
-    {
+    ) {
         $ribbon = '<div class="title-score">';
         if ($check_pass_percentage) {
             $is_success = self::is_success_exercise_result(

+ 1 - 1
main/inc/lib/extra_field.lib.php

@@ -1755,7 +1755,7 @@ EOF;
                                                 }
 
                                             } else {
-                                                alert("Geocode ' . get_lang('Error') . ': " + status);
+                                                alert("Geocode ' . get_lang('Error') . ': ' . get_lang("AddressField") . ' ' . get_lang("NotFound") . '");
                                             }
                                         });
                                     }

+ 1 - 1
main/inc/lib/internationalization.lib.php

@@ -1577,7 +1577,7 @@ function api_detect_encoding($string, $language = null) {
  * Checks a string for UTF-8 validity.
  *
  */
-function api_is_valid_utf8(&$string)
+function api_is_valid_utf8($string)
 {
     return Utf8::isUtf8($string);
 }

+ 6 - 3
main/inc/lib/usermanager.lib.php

@@ -446,14 +446,17 @@ class UserManager
                 );
                 $email_admin = api_get_setting('emailAdministrator');
 
+                $url = api_get_path(WEB_PATH);
                 if (api_is_multiple_url_enabled()) {
                     $access_url_id = api_get_current_access_url_id();
                     if ($access_url_id != -1) {
-                        $url = api_get_access_url($access_url_id);
+                        $urlInfo = api_get_access_url($access_url_id);
+                        if ($urlInfo) {
+                            $url = $urlInfo['url'];
+                        }
                     }
-                } else {
-                    $url = api_get_path(WEB_PATH);
                 }
+
                 $tplContent = new Template(null, false, false, false, false, false);
                 // variables for the default template
                 $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName)));

+ 2 - 1
main/inc/lib/userportal.lib.php

@@ -665,7 +665,8 @@ class IndexManager
 
             if (api_get_setting('allow_social_tool') == 'true') {
                 $total_invitations = Display::badge($total_invitations);
-                $profile_content .= '<li class="invitations-social"><a href="'.api_get_path(WEB_PATH).'main/social/invitations.php">'.Display::return_icon('invitations.png',get_lang('PendingInvitations'),null,ICON_SIZE_SMALL).get_lang('PendingInvitations').$total_invitations.'</a></li>';
+                $profile_content .= '<li class="invitations-social"><a href="'.api_get_path(WEB_PATH).'main/social/invitations.php">'.
+                    Display::return_icon('invitations.png',get_lang('PendingInvitations'),null,ICON_SIZE_SMALL).get_lang('PendingInvitations').$total_invitations.'</a></li>';
             }
 
             if (isset($_configuration['allow_my_files_link_in_homepage']) && $_configuration['allow_my_files_link_in_homepage']) {

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

@@ -261,4 +261,6 @@ $_configuration['system_stable'] = NEW_VERSION_STABLE;
 //$_configuration['user_portal_load_notification_by_ajax'] = false;
 // When exporting a LP, all files and folders in the same path of an html will be exported too.
 //$_configuration['add_all_files_in_lp_export'] = false;
+// Send exercise student score to manager in email notification
+//$_configuration['send_score_in_exam_notification_mail_to_manager'] = false;
 

+ 1 - 1
main/lp/learnpathItem.class.php

@@ -1703,7 +1703,7 @@ class learnpathItem
             if ($debug > 2) {
                 error_log('learnpathItem::get_status(): checking db', 0);
             }
-            if (!empty($this->db_item_view_id)) {
+            if (!empty($this->db_item_view_id) && !empty($course_id)) {
                 $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
                 $sql = "SELECT status FROM $table
                         WHERE

+ 14 - 4
main/mySpace/myStudents.php

@@ -12,7 +12,7 @@ api_block_anonymous_users();
 $export = isset($_GET['export']) ? $_GET['export'] : false;
 $sessionId = isset($_GET['id_session']) ? intval($_GET['id_session']) : 0;
 $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '';
-$course_code = isset($_GET['course']) ? Security :: remove_XSS($_GET['course']) : null;
+$course_code = isset($_GET['course']) ? Security :: remove_XSS($_GET['course']) : '';
 $courseInfo = api_get_course_info($course_code);
 $student_id = intval($_GET['student']);
 
@@ -25,15 +25,25 @@ if (
     !api_is_platform_admin()
 ) {
     if (empty($sessionId)) {
-        if (!$is_courseAdmin) {
+        $isTeacher = false;
+        // Check if is current teacher if set
+        if (!empty($courseInfo)) {
+            $isTeacher = CourseManager::is_course_teacher(
+                api_get_user_id(),
+                $courseInfo['code']
+            );
+        }
+
+        if (!api_is_course_admin() && $isTeacher == false) {
+            if (!empty($courseInfo)) {
             // Check if the user is tutor of the course
             $userCourseStatus = CourseManager::get_tutor_in_course_status(
                 api_get_user_id(),
-                api_get_course_int_id()
+                    $courseInfo['real_id']
             );
 
             if ($userCourseStatus != 1) {
-                $allowedToTrackUser = false;
+                $allowedToTrackUser = false;            
             }
         }
     } else {

+ 6 - 2
plugin/google_maps/lang/en.php

@@ -2,8 +2,12 @@
 
 $strings['plugin_title'] = "Google Maps";
 $strings['plugin_comment'] = "Enable the functionality to show google maps";
-$strings['extra_field_name_help'] = "Ingrese aquí el nombre del campo extra de usuario del cual quiere obtener las localizaciones, siga el siguiente link para ver el mapa : <a href='". api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php'>" . api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php</a>";
+$strings['extra_field_name_help'] = "Enter one or many extra user fields name separated by a comma (,) from which you want to obtain the locations, you can get up to 5 geolocation fields (the rest will be ignored) which will be marked with the following icons respectively:
+<br><br>
+<img src='//maps.google.com/mapfiles/ms/icons/red-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/green-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/blue-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/yellow-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/purple-dot.png'>
+<br><br>
+Follow the link below to see the map : <a href='". api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php'>" . api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php</a>";
 $strings['enable_api'] = "Enable API";
 $strings['api_key'] = "Api Key";
 $strings['extra_field_name'] = "Extra field name";
-$strings['UsersCoordinatesMap'] = "Users Coordinates Map";
+$strings['UsersCoordinatesMap'] = "Users location Map";

+ 6 - 2
plugin/google_maps/lang/es.php

@@ -2,8 +2,12 @@
 
 $strings['plugin_title'] = "Google Maps";
 $strings['plugin_comment'] = "Enable the functionality to show google maps";
-$strings['extra_field_name_help'] = "Ingrese aquí el nombre del campo extra de usuario del cual quiere obtener las localizaciones, siga el siguiente link para ver el mapa : <a href='". api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php'>" . api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php</a>";
+$strings['extra_field_name_help'] = "Ingrese aquí el nombre del campo o los campos extra de usuario separados por una coma (,) del cual quiere obtener las localizaciones, puede obtener hasta 5 campos de geolocalización (el resto serán ignorados) los cuales se marcarán con los siguientes iconos respectivamente:
+<br><br>
+<img src='//maps.google.com/mapfiles/ms/icons/red-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/green-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/blue-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/yellow-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/purple-dot.png'>
+<br><br>
+siga el siguiente link para ver el mapa : <a href='". api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php'>" . api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php</a>";
 $strings['enable_api'] = "Activar API";
 $strings['api_key'] = "Api Key";
 $strings['extra_field_name'] = "Nombre del campo extra";
-$strings['UsersCoordinatesMap'] = "Mapa de Coordenadas de Usuarios";
+$strings['UsersCoordinatesMap'] = "Mapa de localización de Usuarios";

+ 6 - 2
plugin/google_maps/lang/fr.php

@@ -2,8 +2,12 @@
 
 $strings['plugin_title'] = "Google Maps";
 $strings['plugin_comment'] = "Active la fonctionnalité pour afficher Google Maps";
-$strings['extra_field_name_help'] = "Ingrese aquí el nombre del campo extra de usuario del cual quiere obtener las localizaciones, siga el siguiente link para ver el mapa : <a href='". api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php'>" . api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php</a>";
+$strings['extra_field_name_help'] = "Entrez ici le ou les nom(s) des champs extra d'utilisateur séparés par une virgule (,) desquels on souhaite obtenir la géolocalisation, vous pouvez définir jusqu'à 5 champs pour la géolocalisation (le reste est ignoré). Ils seront associés dans l'ordre avec les icônes suivantes :
+<br><br>
+<img src='//maps.google.com/mapfiles/ms/icons/red-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/green-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/blue-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/yellow-dot.png'> <img src='//maps.google.com/mapfiles/ms/icons/purple-dot.png'>
+<br><br>
+Suivez le lien pour voir la carte : <a href='". api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php'>" . api_get_path(WEB_PLUGIN_PATH) . "google_maps/src/map_coordinates.php</a>";
 $strings['enable_api'] = "Enable API";
 $strings['api_key'] = "Api Key";
 $strings['extra_field_name'] = "Nom de champ supplémentaire";
-$strings['UsersCoordinatesMap'] = "Carte des coordonnées des utilisateurs";
+$strings['UsersCoordinatesMap'] = "Carte des emplacements des utilisateurs";

+ 16 - 3
plugin/google_maps/src/map_coordinates.php

@@ -37,15 +37,28 @@ foreach ($extraFieldName as $field) {
 
 $extraFieldValues = [];
 
-foreach ($extraFieldNames as $fieldName) {
-    $extraFieldRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldValues');
-    $extraFieldValues[] = $extraFieldRepo->findBy(['field' => $fieldName->getId()]);
+foreach ($extraFieldNames as $index => $fieldName) {
+    if ($fieldName) {
+        $extraFieldRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldValues');
+        $extraFieldValues[] = $extraFieldRepo->findBy(['field' => $fieldName->getId()]);
+    }
 }
 
 $templateName = $plugin->get_lang('UsersCoordinatesMap');
 
 $tpl = new Template($templateName);
 
+$formattedExtraFieldValues = [];
+
+foreach ($extraFieldValues as $index => $extra) {
+    foreach ($extra as $yandex => $field) {
+        $thisUserExtraField = api_get_user_info($field->getItemId());
+        $formattedExtraFieldValues[$index][$yandex]['address'] = $field->getValue();
+        $formattedExtraFieldValues[$index][$yandex]['user_complete_name'] = $thisUserExtraField['complete_name'];
+    }
+}
+
+$tpl->assign('extra_field_values_formatted', $formattedExtraFieldValues);
 $tpl->assign('extra_field_values', $extraFieldValues);
 
 $content = $tpl->fetch('google_maps/view/map_coordinates.tpl');

+ 70 - 68
plugin/google_maps/view/map_coordinates.tpl

@@ -6,64 +6,8 @@
         initMap();
     });
 
-    function addMaker(lat, lng, map, bounds, userInfo, index) {
-        if (index > 5) {
-            return;
-        }
-
-        var location = new google.maps.LatLng(lat, lng);
-
-        var infoWindow = new google.maps.InfoWindow();
-
-        var geocoder = geocoder = new google.maps.Geocoder();
-
-        var marker = new google.maps.Marker({
-            map: map,
-            position: location,
-            label: userInfo.complete_name
-        });
-
-        switch (index) {
-            case '1':
-                marker.setIcon('//maps.google.com/mapfiles/ms/icons/red-dot.png');
-                break;
-            case '2':
-                marker.setIcon('//maps.google.com/mapfiles/ms/icons/green-dot.png');
-                break;
-            case '3':
-                marker.setIcon('//maps.google.com/mapfiles/ms/icons/blue-dot.png');
-                break;
-            case '4':
-                marker.setIcon('//maps.google.com/mapfiles/ms/icons/yellow-dot.png');
-                break;
-            case '5':
-                marker.setIcon('//maps.google.com/mapfiles/ms/icons/purple-dot.png');
-                break;
-        }
-
-        var address = "";
-
-        geocoder.geocode({ 'latLng': location }, function (results) {
-
-            if (results) {
-                address = results[1].formatted_address;
-            } else {
-                address = '{{ 'Unknown' | get_lang }}';
-            }
-
-            var infoWinContent = "<b>" + userInfo.complete_name + "</b> - " + address;
-
-            marker.addListener('click', function() {
-                infoWindow.setContent(infoWinContent);
-                infoWindow.open(map, marker);
-            });
-        });
-
-        bounds.extend(marker.position);
-        map.fitBounds(bounds);
-    }
-
     function initMap() {
+
         var center = new google.maps.LatLng(-3.480523, 7.866211);
 
         var bounds = new google.maps.LatLngBounds();
@@ -79,25 +23,83 @@
             mapTypeId: google.maps.MapTypeId.ROADMAP
         });
 
-        {% for extra in extra_field_values %}
+        var extraFields = {{ extra_field_values_formatted|json_encode }};
 
-            var index = '{{ loop.index }}';
+        for (var i = 0; i < extraFields.length; i++) {
 
-            {% for field in extra %}
+            var index = i + 1;
 
-                var latLng = '{{ field.value }}';
-                latLng = latLng.split(',');
+            for (var y = 0; y < extraFields[i].length; y++) {
 
-                var lat = latLng[0];
-                var lng = latLng[1];
+                var address = extraFields[i][y]['address'];
+                var userCompleteName = extraFields[i][y]['user_complete_name'];
 
-                {% set userInfo = field.itemId | user_info %}
+                addMaker(address, map, bounds, userCompleteName, index);
+            }
+        }
+    }
 
-                addMaker(lat, lng, map, bounds, {{ userInfo|json_encode }}, index);
+    function addMaker(address, map, bounds, userCompleteName, index) {
 
-            {% endfor %}
+        if (index > 5) {
+            return;
+        }
+
+        var infoWindow = new google.maps.InfoWindow();
 
-        {% endfor %}
+        var geocoder = geocoder = new google.maps.Geocoder();
 
+        var formattedAddress = '';
+
+        geocoder.geocode({ 'address': address }, function (results, status) {
+
+            if (status === google.maps.GeocoderStatus.OK) {
+
+                if (results) {
+                    formattedAddress = results[0].formatted_address;
+                } else {
+                    formattedAddress = '{{ 'Unknown' | get_lang }}';
+                }
+
+                var marker = new google.maps.Marker({
+                    map: map,
+                    position: results[0].geometry.location,
+                    label: userCompleteName
+                });
+
+                switch (index) {
+                    case 1:
+                        marker.setIcon('//maps.google.com/mapfiles/ms/icons/red-dot.png');
+                        break;
+                    case 2:
+                        marker.setIcon('//maps.google.com/mapfiles/ms/icons/green-dot.png');
+                        break;
+                    case 3:
+                        marker.setIcon('//maps.google.com/mapfiles/ms/icons/blue-dot.png');
+                        break;
+                    case 4:
+                        marker.setIcon('//maps.google.com/mapfiles/ms/icons/yellow-dot.png');
+                        break;
+                    case 5:
+                        marker.setIcon('//maps.google.com/mapfiles/ms/icons/purple-dot.png');
+                        break;
+                }
+
+                var infoWinContent = "<b>" + userCompleteName + "</b> - " + formattedAddress;
+
+                marker.addListener('click', function() {
+                    infoWindow.setContent(infoWinContent);
+                    infoWindow.open(map, marker);
+                });
+
+                bounds.extend(marker.position);
+                map.fitBounds(bounds);
+
+            } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
+                setTimeout(function() {
+                    addMaker(address, map, bounds, userCompleteName, index);
+                }, 350);
+            }
+        });
     }
 </script>

+ 0 - 1
src/Chamilo/CoreBundle/Entity/Session.php

@@ -896,7 +896,6 @@ class Session
         $now = new \Datetime('now');
 
         if ($now > $this->getAccessStartDate()) {
-
             return true;
         }
 

+ 11 - 1
src/Chamilo/CoreBundle/Resources/views/default/layout/page_header.html.twig

@@ -36,9 +36,19 @@
                         {{ plugin_header_right }}
                     </div>
                     {% endif %}
+                     <script>
+                       $(document).ready(function() {
+                            $.ajax({
+                                type: "GET",
+                                url: "{{ _p.web_main }}inc/ajax/online.ajax.php?a=get_users_online",
+                                success: function(data) {
+                                    $("#notifications").append(data);
+                                }
+                            });
+                        });
+                       </script>
                     <div class="section-notifications">
                         <ul id="notifications" class="nav nav-pills pull-right">
-                            {{ notification_menu }}
                         </ul>
                     </div>
                     {{ accessibility }}

+ 4 - 3
src/Chamilo/CourseBundle/Component/CourseCopy/CourseBuilder.php

@@ -708,7 +708,8 @@ class CourseBuilder
         // 2nd union gets the orphan questions from question that were deleted in a exercise.
 
         $sql = " (
-                    SELECT question_id, q.* FROM $table_que q INNER JOIN $table_rel r
+                    SELECT question_id, q.* FROM $table_que q 
+                    INNER JOIN $table_rel r
                     ON (q.c_id = r.c_id AND q.id = r.question_id)
                     INNER JOIN $table_qui ex
                     ON (ex.id = r.exercice_id AND ex.c_id = r.c_id )
@@ -716,8 +717,8 @@ class CourseBuilder
                  )
                  UNION
                  (
-                    SELECT question_id, q.* FROM $table_que q left
-                    OUTER JOIN $table_rel r
+                    SELECT question_id, q.* FROM $table_que q 
+                    left OUTER JOIN $table_rel r
                     ON (q.c_id = r.c_id AND q.id = r.question_id)
                     WHERE q.c_id = $courseId AND r.question_id is null
                  )