Browse Source

Merge from 1.9.x

Julio Montoya 12 years ago
parent
commit
62fde6ffe0
100 changed files with 2268 additions and 2241 deletions
  1. 11 3
      main/admin/access_url_edit_users_to_url.php
  2. 1 1
      main/admin/configure_homepage.php
  3. 9 3
      main/admin/course_edit.php
  4. 16 9
      main/admin/course_list.php
  5. 1 1
      main/admin/course_request_edit.php
  6. 1 1
      main/admin/group_add.php
  7. 1 1
      main/admin/group_edit.php
  8. 4 4
      main/admin/settings.lib.php
  9. 2 2
      main/admin/settings.php
  10. 6 4
      main/admin/user_edit.php
  11. 0 2
      main/admin/usergroups.php
  12. 10 6
      main/announcements/announcements.inc.php
  13. 10 0
      main/announcements/resources/js/main.js
  14. 0 296
      main/announcements/resources/js/main.min.js
  15. 1 2
      main/attendance/attendance_sheet.php
  16. 82 80
      main/auth/external_login/facebook.inc.php
  17. 14 14
      main/auth/external_login/facebook.init.php
  18. 121 120
      main/auth/external_login/functions.inc.php
  19. 140 146
      main/auth/external_login/ldap.inc.php
  20. 10 4
      main/auth/external_login/login.ldap.php
  21. 27 26
      main/auth/external_login/newUser.ldap.php
  22. 28 28
      main/auth/external_login/newUser.php
  23. 18 18
      main/auth/external_login/updateUser.php
  24. 7 4
      main/auth/profile.php
  25. 28 27
      main/auth/sso/sso.class.php
  26. 13 7
      main/calendar/agenda.lib.php
  27. 35 10
      main/coursecopy/classes/CourseBuilder.class.php
  28. 41 19
      main/coursecopy/classes/CourseRecycler.class.php
  29. 127 105
      main/coursecopy/classes/CourseRestorer.class.php
  30. 22 16
      main/coursecopy/classes/CourseSelectForm.class.php
  31. 47 27
      main/css/base.css
  32. 320 384
      main/css/responsive.css
  33. BIN
      main/css/student.png
  34. BIN
      main/css/teacher.png
  35. 46 44
      main/document/document.php
  36. 22 15
      main/document/download.php
  37. 51 61
      main/dropbox/dropbox_class.inc.php
  38. 12 19
      main/dropbox/dropbox_functions.inc.php
  39. 7 3
      main/dropbox/dropbox_init.inc.php
  40. 0 32
      main/dropbox/dropbox_submit.php
  41. 12 18
      main/dropbox/index.php
  42. 52 0
      main/dropbox/recover_dropbox_files.php
  43. 4 14
      main/exercice/admin.php
  44. 4 4
      main/exercice/answer_admin.inc.php
  45. 12 34
      main/exercice/exercice.php
  46. 55 6
      main/exercice/exercise.class.php
  47. 74 34
      main/exercice/exercise.lib.php
  48. 2 1
      main/exercice/exercise_admin.php
  49. 17 12
      main/exercice/exercise_report.php
  50. 5 6
      main/exercice/exercise_result.php
  51. 40 13
      main/exercice/exercise_show.php
  52. 2 5
      main/exercice/exercise_submit.php
  53. 2 2
      main/exercice/global_multiple_answer.class.php
  54. 1 1
      main/exercice/hotpotatoes_exercise_report.php
  55. 14 18
      main/exercice/hotspot_answers.as.php
  56. 3 7
      main/exercice/matching.class.php
  57. 2 2
      main/exercice/multiple_answer.class.php
  58. 4 6
      main/exercice/multiple_answer_combination.class.php
  59. 5 10
      main/exercice/multiple_answer_true_false.class.php
  60. 21 29
      main/exercice/question.class.php
  61. 2 19
      main/exercice/question_admin.inc.php
  62. 6 11
      main/exercice/question_list_admin.inc.php
  63. 4 3
      main/exercice/question_pool.php
  64. 3 3
      main/exercice/savescores.php
  65. 20 6
      main/exercice/stats.php
  66. 52 0
      main/exercice/testcategory.class.php
  67. 4 4
      main/exercice/unique_answer.class.php
  68. 40 40
      main/exercice/unique_answer_no_option.class.php
  69. 30 31
      main/exercice/upload_exercise.php
  70. 1 1
      main/forum/viewthread.php
  71. 4 2
      main/forum/viewthread_threaded.inc.php
  72. 1 6
      main/gradebook/gradebook_edit_cat.php
  73. 23 12
      main/gradebook/lib/fe/catform.class.php
  74. 34 169
      main/group/group.php
  75. 6 6
      main/group/group_category.php
  76. 31 32
      main/group/group_creation.php
  77. 16 8
      main/group/group_edit.php
  78. BIN
      main/img/icons/22/exit_na.png
  79. 29 9
      main/inc/ajax/exercise.ajax.php
  80. 1 2
      main/inc/global.inc.php
  81. 49 12
      main/inc/lib/banner.lib.php
  82. 4 4
      main/inc/lib/course_home.lib.php
  83. 1 1
      main/inc/lib/database.lib.php
  84. 12 2
      main/inc/lib/display.lib.php
  85. 3 5
      main/inc/lib/document.lib.php
  86. 6 1
      main/inc/lib/fckeditor/fckeditor.php
  87. 8 7
      main/inc/lib/fckeditor/toolbars/default/test_category.php
  88. 1 1
      main/inc/lib/fckeditor/toolbars/default/test_description.php
  89. 1 1
      main/inc/lib/fckeditor/toolbars/extended/forum.php
  90. 1 1
      main/inc/lib/fckeditor/toolbars/extended/forum_student.php
  91. 3 4
      main/inc/lib/fckeditor/toolbars/extended/test_proposed_answer.php
  92. 1 1
      main/inc/lib/fckeditor/toolbars/extended/test_question_description.php
  93. 170 39
      main/inc/lib/groupmanager.lib.php
  94. 5 1
      main/inc/lib/javascript/jquery.frameready.js
  95. 14 8
      main/inc/lib/link.lib.php
  96. 26 11
      main/inc/lib/main_api.lib.php
  97. 1 1
      main/inc/lib/plugin.class.php
  98. 1 1
      main/inc/lib/social.lib.php
  99. 27 2
      main/inc/lib/template.lib.php
  100. 5 8
      main/inc/lib/tracking.lib.php

+ 11 - 3
main/admin/access_url_edit_users_to_url.php

@@ -237,10 +237,18 @@ if(!empty($errorMsg)) {
 ?>
 
 <table border="0" cellpadding="5" cellspacing="0" width="100%">
-
-<!-- Users -->
 <tr>
-  <td align="center"><b><?php echo get_lang('UserListInPlatform') ?> :</b>
+    <td>
+    <h3>
+    <?php 
+            $total_users = count($nosessionUsersList) +  count($sessionUsersList); 
+            echo get_lang('TotalAvailableUsers').' '.$total_users;
+    ?>
+    </h3>
+    </td>
+</tr>
+<tr>
+  <td align="center"><b><?php echo get_lang('UserListInPlatform') ?> : <?php echo count($nosessionUsersList); ?></b>
   </td>
   <td></td>
   <td align="center"><b><?php echo get_lang('UserListIn').' '.$url_selected; ?> :</b></td>

+ 1 - 1
main/admin/configure_homepage.php

@@ -697,7 +697,7 @@ switch ($action) {
             $form->addElement('select', 'insert_where', get_lang('InsertThisLink') , $options);
 		}        
 		
-		$target_blank_checkbox = & $form->addElement('checkbox', 'target_blank', null, get_lang('OpenInNewWindow'), 1);
+		$target_blank_checkbox = $form->addElement('checkbox', 'target_blank', null, get_lang('OpenInNewWindow'), 1);
                 
         if ($action == 'insert_tabs' || $action == 'edit_tabs') {
             $form->addElement('checkbox', 'add_in_tab', null, get_lang('AddInMenu'), 1);                

+ 9 - 3
main/admin/course_edit.php

@@ -90,8 +90,13 @@ $form->addElement('hidden','code',$course_code);
 $form->add_textfield('title', get_lang('Title'), true, array ('class' => 'span6'));
 $form->applyFilter('title','html_filter');
 $form->applyFilter('title','trim');
-// code
-$form->add_textfield('visual_code', array(get_lang('CourseCode'), get_lang('OnlyLettersAndNumbers')), true, array('class' => 'span4'));
+
+// Code
+$element = $form->addElement('text', 'real_code', array(get_lang('CourseCode'), get_lang('ThisValueCantBeChanged')));
+$element->freeze();
+
+// visual code
+$form->add_textfield('visual_code', array(get_lang('VisualCode'), get_lang('OnlyLettersAndNumbers'), get_lang('ThisValueIsUsedInTheCourseURL')), true, array('class' => 'span4'));
 
 $form->applyFilter('visual_code','strtoupper');
 $form->applyFilter('visual_code','html_filter');
@@ -152,7 +157,6 @@ $group[]= $form->createElement('radio', 'visibility', null, get_lang('Private'),
 $group[]= $form->createElement('radio', 'visibility', null, get_lang('CourseVisibilityClosed'), COURSE_VISIBILITY_CLOSED);
 $form->addGroup($group,'', get_lang('CourseAccess'), '<br />');
 
-
 $group = array();
 $group[]= $form->createElement('radio', 'subscribe', get_lang('Subscription'), get_lang('Allowed'), 1);
 $group[]= $form->createElement('radio', 'subscribe', null, get_lang('Denied'), 0);
@@ -188,6 +192,8 @@ $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'),
 $course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) /1024/1024, 1);
 $course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
 
+$course['real_code'] = $course['code'];
+
 $form->setDefaults($course);
 
 // Validate form

+ 16 - 9
main/admin/course_list.php

@@ -61,10 +61,19 @@ function get_number_of_courses() {
  * Get course data to display
  */
 function get_course_data($from, $number_of_items, $column, $direction) {
-    $course_table       = Database :: get_main_table(TABLE_MAIN_COURSE);    
+    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);    
     
-    $sql = "SELECT code AS col0, title AS col1, visual_code AS col2, course_language AS col3, category_code AS col4, subscribe AS col5, unsubscribe AS col6, 
-            code AS col7, visibility AS col8, directory as col9 
+    $sql = "SELECT  code AS col0, 
+                    title AS col1, 
+                    code AS col2, 
+                    course_language AS col3, 
+                    category_code AS col4, 
+                    subscribe AS col5, 
+                    unsubscribe AS col6, 
+                    code AS col7, 
+                    visibility AS col8, 
+                    directory as col9,
+                    visual_code                    
     		FROM $course_table";
     global $_configuration;
     
@@ -97,14 +106,12 @@ function get_course_data($from, $number_of_items, $column, $direction) {
 
     $res = Database::query($sql);
     $courses = array ();
-    while ($course = Database::fetch_row($res)) {
+    while ($course = Database::fetch_array($res)) {        
         // Place colour icons in front of courses.		
-        $course[1] = get_course_visibility_icon($course[8]).'<a href="'.api_get_path(WEB_COURSE_PATH).$course[9].'/index.php">'.$course[1].'</a>';
+        $course[1] = get_course_visibility_icon($course[8]).'<a href="'.api_get_path(WEB_COURSE_PATH).$course[9].'/index.php">'.$course[1].'</a> '.Display::label($course['visual_code'], 'info');
         $course[5] = $course[5] == SUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No');
         $course[6] = $course[6] == UNSUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No');
-
-        $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]);
-        
+        $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]);        
         $courses[] = $course_rem;
     }
     return $courses;
@@ -183,7 +190,7 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $categories = array();
     $categories_select = $form->addElement('select', 'keyword_category', get_lang('CourseFaculty'), $categories);
     CourseManager::select_and_sort_categories($categories_select);
-    $el = & $form->addElement('select_language', 'keyword_language', get_lang('CourseLanguage'));
+    $el = $form->addElement('select_language', 'keyword_language', get_lang('CourseLanguage'));
     $el->addOption(get_lang('All'), '%');
     $form->addElement('radio', 'keyword_visibility', get_lang("CourseAccess"), get_lang('OpenToTheWorld'), COURSE_VISIBILITY_OPEN_WORLD);
     $form->addElement('radio', 'keyword_visibility', null, get_lang('OpenToThePlatform'), COURSE_VISIBILITY_OPEN_PLATFORM);

+ 1 - 1
main/admin/course_request_edit.php

@@ -64,7 +64,7 @@ if ($course_validation_feature) {
         $form->addRule('wanted_code', get_lang('ThisFieldIsRequired'), 'required');
 
         // The teacher.
-        $titular = & $form->add_textfield('tutor_name', get_lang('Professor'), null, array('size' => '60', 'disabled' => 'disabled'));
+        $titular = $form->add_textfield('tutor_name', get_lang('Professor'), null, array('size' => '60', 'disabled' => 'disabled'));
         //$form->applyFilter('tutor_name', 'html_filter');
 
         // Description of the requested course.

+ 1 - 1
main/admin/group_add.php

@@ -94,7 +94,7 @@ if( $form->validate()) {
 	if ($check) {
 		$values = $form->exportValues();
 
-		$picture_element = & $form->getElement('picture');
+		$picture_element = $form->getElement('picture');
 		$picture 		= $picture_element->getValue();
 		$picture_uri 	= '';
 		$name 			= $values['name'];

+ 1 - 1
main/admin/group_edit.php

@@ -96,7 +96,7 @@ $form->setDefaults($group_data);
 if ( $form->validate()) {
 	$group = $form->exportValues();
 
-	$picture_element = & $form->getElement('picture');
+	$picture_element = $form->getElement('picture');
 	$picture = $picture_element->getValue();
 
 	$picture_uri = $group_data['picture_uri'];

+ 4 - 4
main/admin/settings.lib.php

@@ -237,7 +237,7 @@ function handle_stylesheets() {
         if (!is_writable(api_get_path(SYS_CODE_PATH).'css/')) {
             Display::display_error_message(api_get_path(SYS_CODE_PATH).'css/'.get_lang('IsNotWritable'));
         } else {
-            if ($_GET['showuploadform'] == 'true') {
+            if (!empty($_GET['showuploadform']) && $_GET['showuploadform'] == 'true') {
                 echo '<div id="newstylesheetform">';
             } else {
                 echo '<div id="newstylesheetform" style="display: none;">';
@@ -1067,11 +1067,11 @@ function generate_settings_form($settings, $settings_by_access_list) {
         
     $form = new FormValidator('settings', 'post', 'settings.php?category='.Security::remove_XSS($_GET['category']));
     
-    $form->addElement('hidden', 'search_field', Security::remove_XSS($_GET['search_field']));
+    $form->addElement('hidden', 'search_field', (!empty($_GET['search_field'])?Security::remove_XSS($_GET['search_field']):null));
     
     $url_id = api_get_current_access_url_id();
     
-    if ( $_configuration['multiple_access_urls'] && api_is_global_platform_admin() && $url_id == 1) {
+    if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) {
         $group = array();    
         $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
         $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));    
@@ -1086,7 +1086,7 @@ function generate_settings_form($settings, $settings_by_access_list) {
     foreach ($settings as $row) {      
     	if (in_array($row['variable'], array_keys($settings_to_avoid))) { continue; } 
         
-        if ( $_configuration['multiple_access_urls']) {
+        if (!empty($_configuration['multiple_access_urls'])) {
             if (api_is_global_platform_admin()) {                
                 if ($row['access_url_locked'] == 0) {
                     if ($url_id == 1) {

+ 2 - 2
main/admin/settings.php

@@ -82,7 +82,7 @@ $form_search = new FormValidator('search_settings', 'get', api_get_self() , null
 $form_search->addElement('text', 'search_field');
 $form_search->addElement('hidden', 'category', 'search_setting');
 $form_search->addElement('style_submit_button', 'submit_button', get_lang('Search'), 'value="submit_button", class="search"');         
-$form_search->setDefaults(array('search_field' => $_REQUEST['search_field']));
+$form_search->setDefaults(array('search_field' => (isset($_REQUEST['search_field'])?$_REQUEST['search_field']:null)));
 
 $form_search_html = $form_search->return_form();
 
@@ -504,4 +504,4 @@ if (!empty($_GET['category'])) {
 }
 
 /* FOOTER */
-Display :: display_footer();
+Display :: display_footer();

+ 6 - 4
main/admin/user_edit.php

@@ -134,7 +134,9 @@ $form->applyFilter('official_code', 'trim');
 // Email
 $form->addElement('text', 'email', get_lang('Email'), array('size' => '40'));
 $form->addRule('email', get_lang('EmailWrong'), 'email');
-$form->addRule('email', get_lang('EmailWrong'), 'required');
+if (api_get_setting('registration', 'email') == 'true') {
+    $form->addRule('email', get_lang('EmailWrong'), 'required');
+}
 
 if (api_get_setting('login_is_email') == 'true') {
     $form->addRule('email', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
@@ -253,8 +255,8 @@ if (!$user_data['platform_admin']) {
 	// Expiration Date
 	$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 	$group = array ();
-	$group[] = & $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-	$group[] = & $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
+	$group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
+	$group[] = $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 	$form->addGroup($group, 'max_member_group', null, '', false);
 
 	// Active account or inactive account
@@ -307,7 +309,7 @@ if ( $form->validate()) {
 	if ($user['status'] == DRH && $is_user_subscribed_in_course) {
 		$error_drh = true;
 	} else {
-		$picture_element = & $form->getElement('picture');
+		$picture_element = $form->getElement('picture');
 		$picture = $picture_element->getValue();
 
 		$picture_uri = $user_data['picture_uri'];

+ 0 - 2
main/admin/usergroups.php

@@ -62,8 +62,6 @@ $column_model   = array(
 $extra_params['autowidth'] = 'true';
 //height auto
 $extra_params['height'] = 'auto';
-$extra_params['rowList'] = array(50, 100, 500, 1000, 2000, 5000);
-
 
 //With this function we can add actions to the jgrid
 $action_links = 'function action_formatter (cellvalue, options, rowObject) {

+ 10 - 6
main/announcements/announcements.inc.php

@@ -610,8 +610,10 @@ class AnnouncementManager {
             foreach ($group_list as $this_group) {
                 if (is_array($to_already_selected)) {
                     if (!in_array("GROUP:" . $this_group['id'], $to_already_selected)) { // $to_already_selected is the array containing the groups (and users) that are already selected
-                        echo "<option value=\"GROUP:" . $this_group['id'] . "\">",
-                        "G: ", $this_group['name'], " - " . $this_group['userNb'] . " " . get_lang('Users') .
+                        $user_label = ($this_group['userNb'] > 0) ? get_lang('Users') : get_lang('LowerCaseUser') ;
+                        $user_disabled = ($this_group['userNb'] > 0) ? "" : "disabled=disabled" ;
+                        echo "<option $user_disabled value=\"GROUP:" . $this_group['id'] . "\">",
+                        "G: ", $this_group['name'], " - " . $this_group['userNb'] . " " . $user_label .
                         "</option>";
                     }
                 }
@@ -754,9 +756,9 @@ class AnnouncementManager {
     public static function get_course_groups() {
         $session_id = api_get_session_id();
         if ($session_id != 0) {
-            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), $session_id);
+            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), $session_id, 1);
         } else {
-            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), 0);
+            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), 0, 1);
         }
         return $new_group_list;
     }
@@ -828,13 +830,15 @@ class AnnouncementManager {
      */
     public static function to_javascript() {
         $www = api_get_path(WEB_PATH);
+        /*
+         * Do not allow this kind of behaviour. js minifieds should be manage by the template class or assetic or whatever see #4757 for more info
         if (api_get_setting('server_type') == 'test') {
             $src = $www . 'main/announcements/resources/js/main.js';
         } else {
             $src = $www . 'main/announcements/resources/js/main.min.js';
-        }
+        }*/        
+        $src = $www . 'main/announcements/resources/js/main.js';        
         $result = Javascript::tag($src);
-
         $root = Chamilo::url();
         $code = "var www = '$root';\n";
         $code .= Javascript::get_lang('FieldRequired', 'Send2All', 'AddAnAttachment', 'Everybody');

+ 10 - 0
main/announcements/resources/js/main.js

@@ -155,11 +155,14 @@ function move(fbox, tbox) {
     var arrFbox = [];
     var arrTbox = [];
     var arrLookup = [];
+    var arrFboxIsDisabled = []; // if this from checkbox after move is disabled or not
+    var arrTboxIsDisabled = []; // if this to checkbox after move is disabled or not
 
     var i;
     for (i = 0; i < tbox.options.length; i++) {
         arrLookup[tbox.options[i].text] = tbox.options[i].value;
         arrTbox[i] = tbox.options[i].text;
+        arrTboxIsDisabled[i] = tbox.options[i].disabled;
     }
 
     var fLength = 0;
@@ -177,6 +180,7 @@ function move(fbox, tbox) {
         else 
         {
             arrFbox[fLength] = fbox.options[i].text;
+            arrFboxIsDisabled[fLength] = fbox.options[i].disabled;
             fLength++;
         }
     }
@@ -229,6 +233,9 @@ function move(fbox, tbox) {
         var no = new Option();
         no.value = arrLookup[arrFbox[c]];
         no.text = arrFbox[c];
+        if (arrFboxIsDisabled[c]) {
+            no.disabled = "disabled";
+        }
         fbox[c] = no;
     }
     for (c = 0; c < arrTbox.length; c++) 
@@ -236,6 +243,9 @@ function move(fbox, tbox) {
         var no = new Option();
         no.value = arrLookup[arrTbox[c]];
         no.text = arrTbox[c];
+        if (arrTboxIsDisabled[c]) {
+            no.disabled = "disabled";
+        }        
         tbox[c] = no;
     }
 }

+ 0 - 296
main/announcements/resources/js/main.min.js

@@ -1,296 +0,0 @@
-
-$(document).ready(function () {
-    $("#emailTitle").focus();
-});
-
-$(function() {
-    $('.resizable').resizable();
-    $('.resizable-vertical').resizable({
-        handles: "n, s"
-    });
-});
-
-var Announcement = {};
-
-Announcement.sort = function(c_id, ids, f){
-    var url = www + '/main/inc/ajax/announcement.ajax.php';
-    var data = {c_id: c_id, ids: ids, action: 'sort'};
-    $.post(url, data, f);
-};
-
-Announcement.hide = function(c_id, id, token, f)
-{
-    var url = www + '/main/inc/ajax/announcement.ajax.php';
-    var data = {c_id: c_id, id: id, action: 'hide', sec_token: token};
-    $.post(url, data, f, 'json');
-};
-
-Announcement.show = function(c_id, id, token, f)
-{
-    var url = www + '/main/inc/ajax/announcement.ajax.php';
-    var data = {c_id: c_id, id: id, action: 'show', sec_token: token};
-    $.post(url, data, f, 'json');
-};
-
-Announcement.del = function(c_id, id, token, f)
-{
-    var url = www + '/main/inc/ajax/announcement.ajax.php';
-    var data = {c_id: c_id, id: id, action: 'delete', sec_token: token};
-    $.post(url, data, f, 'json');
-};
-
-Announcement.delete_by_course = function(c_id, token, f)
-{
-    var url = www + '/main/inc/ajax/announcement.ajax.php';
-    var data = {c_id: c_id, action: 'delete_by_course', sec_token: token};
-    $.post(url, data, f, 'json');
-};
-
-Announcement.delete_all = function(c_id, ids, token, f)
-{
-    var url = www + '/main/inc/ajax/announcement.ajax.php';
-    var data = {c_id: c_id, action: 'delete_all', sec_token: token};
-    $.post(url, data, f, 'json');
-};
-
-
-
-function move_selected_option(from, to){
-    var selected = $("option:selected", from)
-    selected.each(function(index, option)
-    {
-        option = $(option);
-        option.detach();
-        $(to).append(option);
-    });
-}
-
-function update_hidden_field(name){
-    
-    var select = $('#' + name + '_selected');
-    var options = $("option", select)
-    //update hidden field
-    var keys = [];
-    options.each(function(index, option)
-    {
-        option = $(option);
-        keys.push(option.val());
-    });
-    keys = keys.join(',');
-    
-    var hidden = $('#' + name);
-    hidden.val(keys);
-}
-
-
-function toggle_list_selector(name)
-{
-    var list = $('#' + name + '_list');
-    var overview = $('#' + name + '_overview');
-    if(list.css('display') == 'none'){
-        list.show();
-        overview.hide();
-    }
-    else
-    {
-        list.hide();
-        overview.show();
-    }
-    
-    var select = $('#' + name + '_selected');
-    
-    //update overview
-    var content = [];
-    var options = $("option", select)
-    options.each(function(index, option)
-    {
-        option = $(option);
-        content.push(option.text());
-    });
-    
-    content = content.join(', ');
-    content = (content == '') ? lang.Everybody : content;
-    overview.text(content);
-}
-
-
-function toggle_sendto()
-{
-    var list = $('#recipient_list');
-    var overview = $('#recipient_overview');
-    if(list.css('display') == 'none'){
-        list.show();
-        overview.hide();
-    }
-    else
-    {
-        list.hide();
-        overview.show();
-    }
-    
-    var selected = $('#selectedform');
-    var content = list_box_content(selected[0])
-    content = (content == '') ? lang.Everybody : content;
-    overview.text(content);
-}
-
-function list_box_content(box)
-{
-    if(box.options.length == 0)
-    {
-        return '';
-    }
-    var values = [];
-    var i;
-    for (i = 0; i < box.options.length; i++) {
-        values[i] = box.options[i].text;
-    }
-    return values.join(', ');
-}
-
-// Begin javascript menu swapper
-
-function move(fbox, tbox) {
-    "use strict";
-    var arrFbox = [];
-    var arrTbox = [];
-    var arrLookup = [];
-
-    var i;
-    for (i = 0; i < tbox.options.length; i++) {
-        arrLookup[tbox.options[i].text] = tbox.options[i].value;
-        arrTbox[i] = tbox.options[i].text;
-    }
-
-    var fLength = 0;
-    var tLength = arrTbox.length;
-
-    for (i = 0; i < fbox.options.length; i++)
-    {
-        arrLookup[fbox.options[i].text] = fbox.options[i].value;
-
-        if (fbox.options[i].selected && fbox.options[i].value != "")
-        {
-            arrTbox[tLength] = fbox.options[i].text;
-            tLength++;
-        } 
-        else 
-        {
-            arrFbox[fLength] = fbox.options[i].text;
-            fLength++;
-        }
-    }
-    
-    arrFbox.sort();
-    arrTbox.sort();
-    
-    var arrFboxGroup = [];
-    var arrFboxUser = [];
-    var prefix_x;
-    
-    var x;
-    for (x = 0; x < arrFbox.length; x++) {
-        prefix_x = arrFbox[x].substring(0, 2);
-        if (prefix_x == 'G:') {
-            arrFboxGroup.push(arrFbox[x]);
-        } else {
-            arrFboxUser.push(arrFbox[x]);
-        }
-    }
-    
-    arrFboxGroup.sort();
-    arrFboxUser.sort();
-    arrFbox = arrFboxGroup.concat(arrFboxUser);
-    
-    var arrTboxGroup = [];
-    var arrTboxUser = [];
-    var prefix_y;
-    
-    var y;
-    for (y = 0; y < arrTbox.length; y++) {
-        prefix_y = arrTbox[y].substring(0, 2);
-        if (prefix_y == 'G:') {
-            arrTboxGroup.push(arrTbox[y]);
-        } else {
-            arrTboxUser.push(arrTbox[y]);
-        }
-    }
-    
-    arrTboxGroup.sort();
-    arrTboxUser.sort();
-    arrTbox = arrTboxGroup.concat(arrTboxUser);
-    
-    fbox.length = 0;
-    tbox.length = 0;
-    
-    var c;
-    for (c = 0; c < arrFbox.length; c++) 
-    {
-        var no = new Option();
-        no.value = arrLookup[arrFbox[c]];
-        no.text = arrFbox[c];
-        fbox[c] = no;
-    }
-    for (c = 0; c < arrTbox.length; c++) 
-    {
-        var no = new Option();
-        no.value = arrLookup[arrTbox[c]];
-        no.text = arrTbox[c];
-        tbox[c] = no;
-    }
-}
-
-function validate() 
-{
-    "use strict";
-    var f = document.new_calendar_item;
-    f.submit();
-    return true;
-}
-
-
-function selectAll(cbList, bSelect, showwarning) {
-    "use strict";
-    
-    if (document.getElementById('emailTitle').value == '') {
-        document.getElementById('msg_error').innerHTML = lang.FieldRequired;
-        document.getElementById('msg_error').style.display = 'block';
-        document.getElementById('emailTitle').focus();
-    } else {
-        //if (cbList.length < 1) {
-        //if (!confirm(lang.Send2All)) {
-        //	return false;
-        //}
-        //}
-        var i;
-        for (i = 0; i < cbList.length; i++)
-        {
-            cbList[i].selected = cbList[i].checked = bSelect;
-        }
-        document.f1.submit();
-    }
-}
-
-function reverseAll(cbList) 
-{
-    "use strict";
-    var i;
-    for (i = 0; i < cbList.length; i++) 
-    {
-        cbList[i].checked = !(cbList[i].checked);
-        cbList[i].selected = !(cbList[i].selected);
-    }
-}
-
-
-function plus_attachment() {
-    "use strict";
-    if (document.getElementById('options').style.display == 'none') {
-        document.getElementById('options').style.display = 'block';
-        document.getElementById('plus').innerHTML = '&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;' + lang.AddAnAttachment;
-    } else {
-        document.getElementById('options').style.display = 'none';
-        document.getElementById('plus').innerHTML = '&nbsp;<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;' + lang.AddAnAttachment;
-    }
-}
-// End

+ 1 - 2
main/attendance/attendance_sheet.php

@@ -94,8 +94,7 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
           original_url = $("#pdf_export").attr('href');
        }
        new_url =  original_url + "&filter=" +filter
-       $("#pdf_export").attr('href', new_url);
-       //console.log(new_url);
+       $("#pdf_export").attr('href', new_url);       
     });
     
     function UpdateTableHeaders() {

+ 82 - 80
main/auth/external_login/facebook.inc.php

@@ -1,4 +1,5 @@
 <?php
+
 /**
  * Licence: GPL 
  * Please contact CBlue regarding any licences issues.
@@ -9,96 +10,97 @@
  *
  * This files provides the facebook_connect()  and facebook_get_url functions
  * Please edit the facebook.conf.php file to adapt it to your fb application parameter
- **/
-require_once dirname(__FILE__).'/../../inc/global.inc.php';
-require_once dirname(__FILE__).'/facebook.init.php';
-require_once dirname(__FILE__).'/facebook-php-sdk/src/facebook.php';
-require_once dirname(__FILE__).'/functions.inc.php';
+ * */
+require_once dirname(__FILE__) . '/../../inc/global.inc.php';
+require_once dirname(__FILE__) . '/facebook.init.php';
+require_once dirname(__FILE__) . '/facebook-php-sdk/src/facebook.php';
+require_once dirname(__FILE__) . '/functions.inc.php';
 
-/** 
-  * This function connect to facebook and retrieves the user info
-  * If user does not exist in chamilo, it creates it and logs in
-  * If user already exists, it updates his info
-**/
-function facebook_connect() { 
-	global $facebook;
-	// See if there is a user from a cookie
-	$user = $facebook->getUser();
-	if ($user) {
-		try {
-			//Gets facebook user info
-			$fu = $facebook->api('/me');
-			$username = $fu['username'];
-			if (api_get_setting('login_is_email') == 'true' || empty($fu['username'])) {
-			    $username = change_to_valid_chamilo_login($fu['email']);
-			}
-			//Checks if user already exists in chamilo
-			$u = array(
-					'firstname' => $fu['first_name'],
-					'lastname' => $fu['last_name'],
-					'status' => STUDENT,
-					'email' => $fu['email'],
-					'username' => $username,
-					'language' => 'french',
-					'password' => DEFAULT_PASSWORD,
-					'auth_source' => 'facebook',
-					//'courses' => $user_info['courses'],
-					//'profile_link' => $user_info['profile_link'],
-					//'worldwide_bu' => $user_info['worlwide_bu'],
-					//'manager' => $user_info['manager'],
-					'extra' => array()
-					);
-			$cu = api_get_user_info_from_username($username);
-			$chamilo_uinfo = api_get_user_info_from_username($username);
-			if ( $chamilo_uinfo  === false) {
-				//we have to create the user
-				$chamilo_uid = external_add_user($u);
-				if ($chamilo_uid !==false) {
-					$_user['user_id'] = $chamilo_uid;
-					$_user['uidReset'] = true;  
-					$_SESSION['_user'] = $_user;
-					header('Location:'.api_get_path(WEB_PATH));
-					exit();
-				} else {
-					return false;
-				}
-			} else {//User already exists, update info and login
-				$chamilo_uid = $chamilo_uinfo['user_id'];
-				$u['user_id'] = $chamilo_uid;
-				external_update_user($u);
-				$_user['user_id'] = $chamilo_uid;
-				$_user['uidReset'] = true;  
-				$_SESSION['_user'] = $_user;
-				header('Location:'.api_get_path(WEB_PATH));
-				exit();
-			}
-		} catch (FacebookApiException $e) {
-			echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
-			$user = null;
-		}
-	}
+/**
+ * This function connect to facebook and retrieves the user info
+ * If user does not exist in chamilo, it creates it and logs in
+ * If user already exists, it updates his info
+ * */
+function facebook_connect() {
+    global $facebook;
+    // See if there is a user from a cookie
+    $user = $facebook->getUser();
+    if ($user) {
+        try {
+            //Gets facebook user info
+            $fu = $facebook->api('/me');
+            $username = $fu['username'];
+            if (api_get_setting('login_is_email') == 'true' || empty($fu['username'])) {
+                $username = change_to_valid_chamilo_login($fu['email']);
+            }
+            //Checks if user already exists in chamilo
+            $u = array(
+                'firstname' => $fu['first_name'],
+                'lastname' => $fu['last_name'],
+                'status' => STUDENT,
+                'email' => $fu['email'],
+                'username' => $username,
+                'language' => 'french',
+                'password' => DEFAULT_PASSWORD,
+                'auth_source' => 'facebook',
+                //'courses' => $user_info['courses'],
+                //'profile_link' => $user_info['profile_link'],
+                //'worldwide_bu' => $user_info['worlwide_bu'],
+                //'manager' => $user_info['manager'],
+                'extra' => array()
+            );
+            $cu = api_get_user_info_from_username($username);
+            $chamilo_uinfo = api_get_user_info_from_username($username);
+            if ($chamilo_uinfo === false) {
+                //we have to create the user
+                $chamilo_uid = external_add_user($u);
+                if ($chamilo_uid !== false) {
+                    $_user['user_id'] = $chamilo_uid;
+                    $_user['uidReset'] = true;
+                    $_SESSION['_user'] = $_user;
+                    header('Location:' . api_get_path(WEB_PATH));
+                    exit();
+                } else {
+                    return false;
+                }
+            } else {//User already exists, update info and login
+                $chamilo_uid = $chamilo_uinfo['user_id'];
+                $u['user_id'] = $chamilo_uid;
+                external_update_user($u);
+                $_user['user_id'] = $chamilo_uid;
+                $_user['uidReset'] = true;
+                $_SESSION['_user'] = $_user;
+                header('Location:' . api_get_path(WEB_PATH));
+                exit();
+            }
+        } catch (FacebookApiException $e) {
+            echo '<pre>' . htmlspecialchars(print_r($e, true)) . '</pre>';
+            $user = null;
+        }
+    }
 }
 
 /**
-* Get facebook login url for the platform
-**/
-function facebook_get_login_url(){
-	global $facebook, $facebook_config;
+ * Get facebook login url for the platform
+ * */
+function facebook_get_login_url() {
+    global $facebook, $facebook_config;
 
-	$login_url = $facebook->getLoginUrl(
-			array(
-				'scope'	=> 'email,publish_stream',
-				'redirect_uri' => $facebook_config['return_url']
-				)
-			); 
-	return $login_url;
+    $login_url = $facebook->getLoginUrl(
+            array(
+                'scope' => 'email,publish_stream',
+                'redirect_uri' => $facebook_config['return_url']
+            )
+    );
+    return $login_url;
 }
 
 /**
  * @input : a string
  * @return : a string containing valid chamilo login characters
  * Chamilo login only use characters lettres, des chiffres et les signes _ . -
-**/
+ * */
 function change_to_valid_chamilo_login($in_txt) {
-    return preg_replace("/[^a-zA-Z1-9_\-.]/", "_", $in_txt);exit;
+    return preg_replace("/[^a-zA-Z1-9_\-.]/", "_", $in_txt);
+    exit;
 }

+ 14 - 14
main/auth/external_login/facebook.init.php

@@ -1,4 +1,5 @@
-<?php 
+<?php
+
 /**
  * Licence: GPL
  * Please contact CBlue regarding any licences issues.
@@ -9,24 +10,23 @@
  *
  * Configuration file 
  * Please edit this file to match with your FACEBOOK settings
- **/
-
-/** 
+ * */
+/**
  * Facebook application setting
- **/
-require_once dirname(__FILE__).'/facebook-php-sdk/src/facebook.php';
+ * */
+require_once dirname(__FILE__) . '/facebook-php-sdk/src/facebook.php';
 
-global $facebook_config; 
+global $facebook_config;
 
 //Loads the portal facebook settings
-$conf = dirname(__FILE__).'../../inc/conf/auth.conf.php';
+$conf = dirname(__FILE__) . '../../inc/conf/auth.conf.php';
 
-/** 
+/**
  * See facebook section of the auth.conf.php file
-*/
+ */
 global $facebook;
 $facebook = new Facebook(array(
-			'appId'  => $facebook_config['appId'],
-			'secret' => $facebook_config['secret']
-			));
-require_once dirname(__FILE__).'/facebook.inc.php';
+            'appId' => $facebook_config['appId'],
+            'secret' => $facebook_config['secret']
+        ));
+require_once dirname(__FILE__) . '/facebook.inc.php';

+ 121 - 120
main/auth/external_login/functions.inc.php

@@ -1,9 +1,10 @@
 <?php
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+
+require_once api_get_path(LIBRARY_PATH) . 'usermanager.lib.php';
+require_once api_get_path(LIBRARY_PATH) . 'course.lib.php';
+
 //define('USERINFO_TABLE', 'danone_userinfo');
 //define('DEFAULT_PASSWORD', 'danonelearning');
-
 //TODO : Please implements this function for this module to work.
 /**
  * Gets user info from external source 
@@ -17,116 +18,117 @@ require_once api_get_path(LIBRARY_PATH).'course.lib.php';
  *       login
  *       password
  *   or false if no data
- **/
-function external_get_user_info($login, $password){
-  //Those are the mandatory fields for user creation.
-  //See external_add_user function for all the fields you can have.
-  $table = USERINFO_TABLE;
-  $sql = "SELECT * from $table where username='".Database::escape_string($login)."'";
-  $result = Database::query($sql);
+ * */
+function external_get_user_info($login, $password) {
+    //Those are the mandatory fields for user creation.
+    //See external_add_user function for all the fields you can have.
+    $table = USERINFO_TABLE;
+    $sql = "SELECT * from $table where username='" . Database::escape_string($login) . "'";
+    $result = Database::query($sql);
 
-  if (Database::num_rows($result) == 0 ) { //false password
-    return false;
-  }
-  $user_info = Database::fetch_assoc($result);
-  // User status
-  $admin = false;
-  switch($user_info['status']){
-  case 'admin': 
-    $status = COURSEMANAGER;
-    $admin = true;
-    break;
-  case 'teacher':
-    $status = COURSEMANAGER;
-    break;
-  case 'user':
-    $status = STUDENT;
-    break;
-  default:
-    $status = STUDENT;
-  }
-  // Language
-  switch($user_info['language']){
-  case 'FR' :
-    $language = 'french';
-    break;
-  case 'EN' :
-    $language = 'english';
-    break;
-  default : 
-    $language = 'english';
-    break;
-  }
-  //Can Send Message ?
-  $can_send_message = ($user_info['can_send_message'] == 1) ? 'yes' : 'no';
+    if (Database::num_rows($result) == 0) { //false password
+        return false;
+    }
+    $user_info = Database::fetch_assoc($result);
+    // User status
+    $admin = false;
+    switch ($user_info['status']) {
+        case 'admin':
+            $status = COURSEMANAGER;
+            $admin = true;
+            break;
+        case 'teacher':
+            $status = COURSEMANAGER;
+            break;
+        case 'user':
+            $status = STUDENT;
+            break;
+        default:
+            $status = STUDENT;
+    }
+    // Language
+    switch ($user_info['language']) {
+        case 'FR' :
+            $language = 'french';
+            break;
+        case 'EN' :
+            $language = 'english';
+            break;
+        default :
+            $language = 'english';
+            break;
+    }
+    //Can Send Message ?
+    $can_send_message = ($user_info['can_send_message'] == 1) ? 'yes' : 'no';
 
 
-  $u = array(
-    'firstname' => $user_info['firstname'],
-    'lastname' => $user_info['lastname'],
-    'status' => $status,
-    'admin' => $admin,
-    'email' => $user_info['email'],
-    'username' => $user_info['username'],
-    'language' => $language,
-    'password' => DEFAULT_PASSWORD,
-    'courses' => $user_info['courses'],
-    'profile_link' => $user_info['profile_link'],
-    'worldwide_bu' => $user_info['worlwide_bu'],
-    'manager' => $user_info['manager'],
-    'extra' => array(
-      'position_title' => $user_info['position_title'],
-      'country' => $user_info['country'],
-      'job_family' => $user_info['job_family'],
-      'country_bu' => $user_info['country_bu'],
-      'worldwide_bu' => $user_info['worldwide_bu'],
-      'profile_link' => $user_info['profile_link'],
-      'can_send_message' => $can_send_message,
-      'update_type' => 'external_logininfo')
+    $u = array(
+        'firstname' => $user_info['firstname'],
+        'lastname' => $user_info['lastname'],
+        'status' => $status,
+        'admin' => $admin,
+        'email' => $user_info['email'],
+        'username' => $user_info['username'],
+        'language' => $language,
+        'password' => DEFAULT_PASSWORD,
+        'courses' => $user_info['courses'],
+        'profile_link' => $user_info['profile_link'],
+        'worldwide_bu' => $user_info['worlwide_bu'],
+        'manager' => $user_info['manager'],
+        'extra' => array(
+            'position_title' => $user_info['position_title'],
+            'country' => $user_info['country'],
+            'job_family' => $user_info['job_family'],
+            'country_bu' => $user_info['country_bu'],
+            'worldwide_bu' => $user_info['worldwide_bu'],
+            'profile_link' => $user_info['profile_link'],
+            'can_send_message' => $can_send_message,
+            'update_type' => 'external_logininfo')
     );
 
-  return $u; //Please return false if user does not exist
-  //return false;
+    return $u; //Please return false if user does not exist
+    //return false;
 }
 
 /**
  * Return an array with all user info
  * @param associative array with at least thes fields setted :
-        firstname, lastname, status, email, login, password
+  firstname, lastname, status, email, login, password
  * @return mixed   new user id - if the new user creation succeeds, false otherwise
- **/
-function external_add_user($u){
-  //Setting default
-  if (empty($u['password']) )
-    $u['password'] = null;
-  if (empty($u['status']) )
-    $u['status'] = 5;
-  if (! isset($u['official_code']) )
-    $u['official_code'] = '';
-  if (! isset($u['language']) )
-    $u['language'] = '';
-  if (! isset($u['phone']) )
-    $u['phone'] = '';
-  if (! isset($u['picture_uri']) )
-    $u['picture_uri'] = '';
-  if (! isset($u['auth_source']) )
-    $u['auth_source'] = PLATFORM_AUTH_SOURCE;
-  if (! isset($u['expiration_date']) )
-    $u['expiration_date'] = '0000-00-00 00:00:00';
-  if (! isset($u['active']) )
-    $u['active'] = 1;
-  if (! isset($u['hr_dept_id']) )
-    $u['hr_dept_id'] = 0; //id of responsible HR
-  if (! isset($u['extra']) )
-    $u['extra'] = null;
-  if (! isset($u['encrypt_method']) )
-    $u['encrypt_method'] = '';
-  
-  $chamilo_uid = UserManager::create_user($u['firstname'], $u['lastname'],$u['status'], $u['email'], $u['username'], $u['password'], $u['official_code'], $u['language'], $u['phone'],$u['picture_uri'], $u['auth_source'], $u['expiration_date'], $u['active'], $u['hr_dept_id'], $u['extra'], $u['encrypt_method']);
-  return $chamilo_uid;
+ * */
+function external_add_user($u) {
+    //Setting default
+    if (empty($u['password']))
+        $u['password'] = null;
+    if (empty($u['status']))
+        $u['status'] = 5;
+    if (!isset($u['official_code']))
+        $u['official_code'] = '';
+    if (!isset($u['language']))
+        $u['language'] = '';
+    if (!isset($u['phone']))
+        $u['phone'] = '';
+    if (!isset($u['picture_uri']))
+        $u['picture_uri'] = '';
+    if (!isset($u['auth_source']))
+        $u['auth_source'] = PLATFORM_AUTH_SOURCE;
+    if (!isset($u['expiration_date']))
+        $u['expiration_date'] = '0000-00-00 00:00:00';
+    if (!isset($u['active']))
+        $u['active'] = 1;
+    if (!isset($u['hr_dept_id']))
+        $u['hr_dept_id'] = 0; //id of responsible HR
+    if (!isset($u['extra']))
+        $u['extra'] = null;
+    if (!isset($u['encrypt_method']))
+        $u['encrypt_method'] = '';
+
+    $chamilo_uid = UserManager::create_user($u['firstname'], $u['lastname'], $u['status'], $u['email'], $u['username'], $u['password'], $u['official_code'], $u['language'], $u['phone'], $u['picture_uri'], $u['auth_source'], $u['expiration_date'], $u['active'], $u['hr_dept_id'], $u['extra'], $u['encrypt_method']);
+    return $chamilo_uid;
 }
+
 /**
-* Update the user in chamilo database. It upgrade only info that is present in the 
+ * Update the user in chamilo database. It upgrade only info that is present in the 
  * new_user array
  *
  * @param $new_user associative array with the value to upgrade
@@ -151,28 +153,27 @@ function external_add_user($u){
  *      - admin : boolean 
  * @return boolean
  * @author ndiechburg <noel@cblue.be>
- **/
-function external_update_user($new_user){
-  $old_user = UserManager::get_user_info_by_id($new_user['user_id']);
-  $u = array_merge($old_user, $new_user);
-  $updated = UserManager::update_user($u['user_id'], $u['firstname'], $u['lastname'], $u['username'], null, $u['auth_source'], $u['email'], $u['status'], $u['official_code'], $u['phone'], $u['picture_uri'], $u['expiration_date'], $u['active'], $u['creator_id'], $u['hr_dept_id'], $u['extra'], $u['language'],'');
-  if(isset($u['courses']) && !empty($u['courses'])){
-    $autoSubscribe = explode('|', $u['courses']);
-    foreach ($autoSubscribe as $code) {
-      if (CourseManager::course_exists($code)) { 
-        CourseManager::subscribe_user($u['user_id'], $code);
-      }
+ * */
+function external_update_user($new_user) {
+    $old_user = UserManager::get_user_info_by_id($new_user['user_id']);
+    $u = array_merge($old_user, $new_user);
+    $updated = UserManager::update_user($u['user_id'], $u['firstname'], $u['lastname'], $u['username'], null, $u['auth_source'], $u['email'], $u['status'], $u['official_code'], $u['phone'], $u['picture_uri'], $u['expiration_date'], $u['active'], $u['creator_id'], $u['hr_dept_id'], $u['extra'], $u['language'], '');
+    if (isset($u['courses']) && !empty($u['courses'])) {
+        $autoSubscribe = explode('|', $u['courses']);
+        foreach ($autoSubscribe as $code) {
+            if (CourseManager::course_exists($code)) {
+                CourseManager::subscribe_user($u['user_id'], $code);
+            }
+        }
     }
-  }
-  // Is User Admin ?
-  //TODO decomments and check that user_is is not already in admin table
-  /*
-  if (isset($u['admin']) && $u['admin']){
-  
-    $table = Database::get_main_table(TABLE_MAIN_ADMIN);
-    $res = Database::query("SELECT * from $table WHERE user_id = ".$u['user_id']);
-  }*/
+    // Is User Admin ?
+    //TODO decomments and check that user_is is not already in admin table
+    /*
+      if (isset($u['admin']) && $u['admin']){
 
+      $table = Database::get_main_table(TABLE_MAIN_ADMIN);
+      $res = Database::query("SELECT * from $table WHERE user_id = ".$u['user_id']);
+      } */
 }
 
 ?>

+ 140 - 146
main/auth/external_login/ldap.inc.php

@@ -1,12 +1,13 @@
-<?php // External login module : LDAP 
+<?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';
-require_once dirname(__FILE__).'/../../inc/conf/auth.conf.php';
+require_once dirname(__FILE__) . '/../../inc/global.inc.php';
+require_once dirname(__FILE__) . '/../../inc/conf/auth.conf.php';
 
 /**
  * Returns a transcoded and trimmed string
@@ -14,15 +15,14 @@ require_once dirname(__FILE__).'/../../inc/conf/auth.conf.php';
  * @param string 
  * @return string 
  * @author ndiechburg <noel@cblue.be>
- **/
+ * */
 function extldap_purify_string($string) {
-  global $extldap_config;
-  if(isset($extldap_config['encoding'])) {
-    return trim(api_to_system_encoding($string, $extldap_config['encoding']));
-  }
-  else {
-    return trim($string);
-  }
+    global $extldap_config;
+    if (isset($extldap_config['encoding'])) {
+        return trim(api_to_system_encoding($string, $extldap_config['encoding']));
+    } else {
+        return trim($string);
+    }
 }
 
 /**
@@ -30,46 +30,45 @@ function extldap_purify_string($string) {
  *
  * @return resource ldap link identifier or false
  * @author ndiechburg <noel@cblue.be>
- **/
-function extldap_connect()
-{
-  global $extldap_config;
-
-  if (!is_array($extldap_config['host']))
-    $extldap_config['host'] = array($extldap_config['host']);
-
-  foreach($extldap_config['host'] as $host) {
-    //Trying to connect
-    if (isset($extldap_config['port'])) {
-      $ds = ldap_connect($host,$extldap_config['port']);
-    } else {
-      $ds = ldap_connect($host);
+ * */
+function extldap_connect() {
+    global $extldap_config;
+
+    if (!is_array($extldap_config['host']))
+        $extldap_config['host'] = array($extldap_config['host']);
+
+    foreach ($extldap_config['host'] as $host) {
+        //Trying to connect
+        if (isset($extldap_config['port'])) {
+            $ds = ldap_connect($host, $extldap_config['port']);
+        } else {
+            $ds = ldap_connect($host);
+        }
+        if (!$ds) {
+            $port = isset($extldap_config['port']) ? $ldap_config['port'] : 389;
+            error_log('EXTLDAP ERROR : cannot connect to ' . $extldap_config['host'] . ':' . $port);
+        } else
+            break;
     }
     if (!$ds) {
-      $port = isset($extldap_config['port']) ? $ldap_config['port'] : 389;
-      error_log('EXTLDAP ERROR : cannot connect to '.$extldap_config['host'].':'. $port);
-    } else
-      break;
-  }
-  if (!$ds) { 
-    error_log('EXTLDAP ERROR : no valid server found');
-    return false;
-  }
-  //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);
+        error_log('EXTLDAP ERROR : no valid server found');
+        return false;
+    }
+    //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
-  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']);
+    //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']);
+        }
     }
-  }
-  
-  return $ds;
+
+    return $ds;
 }
 
 /**
@@ -80,59 +79,57 @@ function extldap_connect()
  * Modified by hubert.borderiou@grenet.fr 
  * Add possibility to get user info from LDAP without check password (if CAS auth and LDAP profil update)
  * 
- **/
-function extldap_authenticate($username, $password, $in_auth_with_no_password=false)
-{
-  global $extldap_config;
+ * */
+function extldap_authenticate($username, $password, $in_auth_with_no_password = false) {
+    global $extldap_config;
 
-  if (empty($username) or empty($password)){
-    return false;
-  }
+    if (empty($username) or empty($password)) {
+        return false;
+    }
 
-  $ds = extldap_connect();
-  if (!$ds) {
-    return false;
-  }
+    $ds = extldap_connect();
+    if (!$ds) {
+        return false;
+    }
 
-  //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');
-    return false;
-  }
-  $user_search = extldap_get_user_search_string($username);
-  //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");
-    return false;
-  }
-  $entries_count = ldap_count_entries($ds,$sr);
+    //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');
+        return false;
+    }
+    $user_search = extldap_get_user_search_string($username);
+    //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");
+        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) )");
-    return false;
-  }
-  if ($entries_count < 1) {
-    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];
+    if ($entries_count > 1) {
+        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) )");
+        return false;
+    }
+    $users = ldap_get_entries($ds, $sr);
+    $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
-  $ubind = @ldap_bind($ds, $user['dn'], $password);
-  if($ubind !== false){
-    return $user;
-  }
-  else {
-    error_log('EXTLDAP : Wrong password for '.$user['dn']);
-    return false;
-  }
+    // 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
+    $ubind = @ldap_bind($ds, $user['dn'], $password);
+    if ($ubind !== false) {
+        return $user;
+    } else {
+        error_log('EXTLDAP : Wrong password for ' . $user['dn']);
+        return false;
+    }
 }
 
 /**
@@ -143,87 +140,84 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password=fa
  * @param array correspondance array (if not set use extldap_user_correspondance declared in auth.conf.php
  * @return array userinfo array
  * @author ndiechburg <noel@cblue.be>
- **/
-function extldap_get_chamilo_user($ldap_user, $cor = null)
-{
-  global $extldap_user_correspondance;
-  if ( is_null($cor) ) {
-    $cor = $extldap_user_correspondance;
-  }
-
-  $chamilo_user =array();
-  foreach ($cor as $chamilo_field => $ldap_field) {
-    if (is_array($ldap_field)){
-      $chamilo_user[$chamilo_field] = extldap_get_chamilo_user($ldap_user, $ldap_field);
-      continue;
+ * */
+function extldap_get_chamilo_user($ldap_user, $cor = null) {
+    global $extldap_user_correspondance;
+    if (is_null($cor)) {
+        $cor = $extldap_user_correspondance;
     }
 
-    switch ($ldap_field) {
-    case 'func':
-      $func = "extldap_get_$chamilo_field";
-      if (function_exists($func)) {
-        $chamilo_user[$chamilo_field] = extldap_purify_string($func($ldap_user));
-      } else {
-        error_log("EXTLDAP WARNING : You forgot to declare $func");
-      }
-      break;
-    default:
-      //if string begins with "!", then this is a constant
-      if($ldap_field[0] === '!' ){
-        $chamilo_user[$chamilo_field] = trim($ldap_field, "!\t\n\r\0");
-        break;
-      }
-      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');
-
-      }
-      break;
+    $chamilo_user = array();
+    foreach ($cor as $chamilo_field => $ldap_field) {
+        if (is_array($ldap_field)) {
+            $chamilo_user[$chamilo_field] = extldap_get_chamilo_user($ldap_user, $ldap_field);
+            continue;
+        }
+
+        switch ($ldap_field) {
+            case 'func':
+                $func = "extldap_get_$chamilo_field";
+                if (function_exists($func)) {
+                    $chamilo_user[$chamilo_field] = extldap_purify_string($func($ldap_user));
+                } else {
+                    error_log("EXTLDAP WARNING : You forgot to declare $func");
+                }
+                break;
+            default:
+                //if string begins with "!", then this is a constant
+                if ($ldap_field[0] === '!') {
+                    $chamilo_user[$chamilo_field] = trim($ldap_field, "!\t\n\r\0");
+                    break;
+                }
+                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');
+                }
+                break;
+        }
     }
-  }
-  return $chamilo_user;
+    return $chamilo_user;
 }
 
-
-
 /**
  * Please declare here all the function you use in extldap_user_correspondance
  * All these functions must have an $ldap_user parameter. This parameter is the 
  * array returned by the ldap for the user
- **/
+ * */
+
 /**
  * example function for email
- **/
+ * */
 /*
-function extldap_get_email($ldap_user){
+  function extldap_get_email($ldap_user){
   return $ldap_user['cn'].$ldap['sn'].'@gmail.com';
-}
+  }
  */
-function extldap_get_status($ldap_user){
+function extldap_get_status($ldap_user) {
     return STUDENT;
 }
-function extldap_get_admin($ldap_user){
+
+function extldap_get_admin($ldap_user) {
     return false;
 }
 
-
 /**
  * return the string used to search a user in ldap
  *
  * @param string username
  * @return string the serach string
  * @author ndiechburg <noel@cblue.be>
- **/
+ * */
 function extldap_get_user_search_string($username) {
     global $extldap_config;
     // init
-    $filter = '('.$extldap_config['user_search'].')';
+    $filter = '(' . $extldap_config['user_search'] . ')';
     // replacing %username% by the actual username
-    $filter = str_replace('%username%',$username,$filter);
+    $filter = str_replace('%username%', $username, $filter);
     // append a global filter if needed
     if (isset($extldap_config['filter']) && $extldap_config['filter'] != "")
-    $filter = '(&'.$filter.'('.$extldap_config['filter'].'))';
+        $filter = '(&' . $filter . '(' . $extldap_config['filter'] . '))';
 
     return $filter;
 }

+ 10 - 4
main/auth/external_login/login.ldap.php

@@ -40,18 +40,22 @@
 
 use \ChamiloSession as Session;
 
-require_once dirname(__FILE__).'/ldap.inc.php';
-require_once dirname(__FILE__).'/functions.inc.php';
-
+require_once dirname(__FILE__) . '/ldap.inc.php';
+require_once dirname(__FILE__) . '/functions.inc.php';
+error_log('Entering login.ldap.php');
 $ldap_user = extldap_authenticate($login, $password);
 if ($ldap_user !== false) {
+    error_log('extldap_authenticate works');
     $chamilo_user = extldap_get_chamilo_user($ldap_user);
     //userid is not on the ldap, we have to use $uData variable from local.inc.php
     $chamilo_user['user_id'] = $uData['user_id'];
 
+    error_log("chamilo_user found user_id: {$uData['user_id']}");
+
     //Update user info
     if (isset($extldap_config['update_userinfo']) && $extldap_config['update_userinfo']) {
         external_update_user($chamilo_user);
+        error_log("Calling external_update_user");
     }
 
     $loginFailed = false;
@@ -60,9 +64,11 @@ if ($ldap_user !== false) {
     $_user['uidReset'] = true;
     Session::write('_user', $_user);
     $uidReset = true;
-    event_login();
     $logging_in = true;
+    event_login();
+    error_log("Calling event_login");
 } else {
+    error_log('extldap_authenticate error');
     $loginFailed = true;
     $uidReset = false;
     unset($_user['user_id']);

+ 27 - 26
main/auth/external_login/newUser.ldap.php

@@ -1,4 +1,6 @@
-<?php // External login module : LDAP
+<?php
+
+// External login module : LDAP
 /**
  * This file is included by main/inc/local.inc.php when extldap is activated, a user try to login 
  * and chamilo does not find his user
@@ -33,36 +35,35 @@
  *          - index.php?loginFailed=1&error=account_inactive
  *          - index.php?loginFailed=1&error=user_password_incorrect 
  *          - index.php?loginFailed=1&error=unrecognize_sso_origin');
- **/
-
+ * */
 
 use \ChamiloSession as Session;
 
-require_once dirname(__FILE__).'/ldap.inc.php';
-require_once dirname(__FILE__).'/functions.inc.php';
+require_once dirname(__FILE__) . '/ldap.inc.php';
+require_once dirname(__FILE__) . '/functions.inc.php';
 
-$ldap_user = extldap_authenticate($login,$password);
+$ldap_user = extldap_authenticate($login, $password);
 if ($ldap_user !== false) {
-  $chamilo_user = extldap_get_chamilo_user($ldap_user);
-  //username is not on the ldap, we have to use $login variable
-  $chamilo_user['username'] = $login;
-  $chamilo_uid = external_add_user($chamilo_user);
-  if ($chamilo_uid !==false) {
-    $loginFailed = false;
-    $_user['user_id'] = $chamilo_uid;
-    $_user['status'] = (isset($chamilo_user['status'])?$chamilo_user['status']:5);
-    $_user['uidReset'] = true;  
-    Session::write('_user',$_user);
-    $uidReset=true;
-    // Is user admin? 
-    if ($chamilo_user['admin']=== true){
-			$is_platformAdmin           = true;
-      Database::query("INSERT INTO admin values ('$chamilo_uid')");
+    $chamilo_user = extldap_get_chamilo_user($ldap_user);
+    //username is not on the ldap, we have to use $login variable
+    $chamilo_user['username'] = $login;
+    $chamilo_uid = external_add_user($chamilo_user);
+    if ($chamilo_uid !== false) {
+        $loginFailed = false;
+        $_user['user_id'] = $chamilo_uid;
+        $_user['status'] = (isset($chamilo_user['status']) ? $chamilo_user['status'] : 5);
+        $_user['uidReset'] = true;
+        Session::write('_user', $_user);
+        $uidReset = true;
+        // Is user admin? 
+        if ($chamilo_user['admin'] === true) {
+            $is_platformAdmin = true;
+            Database::query("INSERT INTO admin values ('$chamilo_uid')");
+        }
     }
-  }
-  event_login();
+    event_login();
 } else {
-  $loginFailed = true;
-  $uidReset = false;
-  unset($_user['user_id']);
+    $loginFailed = true;
+    $uidReset = false;
+    unset($_user['user_id']);
 }

+ 28 - 28
main/auth/external_login/newUser.php

@@ -1,59 +1,59 @@
 <?php
+
 /*
- Template to automatically create a new user with information from anywhere.
- This file is loaded by main/inc/local.inc.php
- To use it please add this line to main/inc/conf/configuration.php :
-   $extAuthSource["external_logininfo"]["newUser"] = $_configuration['root_sys'].$_configuration['code_append']."auth/external_logininfo/newUser.php";
- 
- You also have to implements the external_get_user_info function in functions.inc.php
+  Template to automatically create a new user with information from anywhere.
+  This file is loaded by main/inc/local.inc.php
+  To use it please add this line to main/inc/conf/configuration.php :
+  $extAuthSource["external_logininfo"]["newUser"] = $_configuration['root_sys'].$_configuration['code_append']."auth/external_logininfo/newUser.php";
+
+  You also have to implements the external_get_user_info function in functions.inc.php
  */
 
 use \ChamiloSession as Session;
 
-require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'course.lib.php');
-require_once(dirname(__FILE__).'/functions.inc.php');
+require_once(api_get_path(LIBRARY_PATH) . 'usermanager.lib.php');
+require_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
+require_once(dirname(__FILE__) . '/functions.inc.php');
 
 
 //MAIN CODE
-
 //$login and $password variables are setted in main/inc/local.inc.php
 
 if ($password != DEFAULT_PASSWORD) {
-    $user =  false;
+    $user = false;
 } else {
-  $user = external_get_user_info($login, $password);
+    $user = external_get_user_info($login, $password);
 }
 
 if ($user !== false && ($chamilo_uid = external_add_user($user)) !== false) {
     //log in the user
     $loginFailed = false;
     $_user['user_id'] = $chamilo_uid;
-    $_user['uidReset'] = true;  
-    Session::write('_user',$_user);
-    $uidReset=true;
+    $_user['uidReset'] = true;
+    Session::write('_user', $_user);
+    $uidReset = true;
 
     //Autosubscribe to courses
-    if(!empty($user['courses'])){
-      $autoSubscribe = explode('|', $user['courses']);
-      foreach ($autoSubscribe as $code) {
-        if (CourseManager::course_exists($code)) { 
-          CourseManager::subscribe_user($_user['user_id'], $code);
+    if (!empty($user['courses'])) {
+        $autoSubscribe = explode('|', $user['courses']);
+        foreach ($autoSubscribe as $code) {
+            if (CourseManager::course_exists($code)) {
+                CourseManager::subscribe_user($_user['user_id'], $code);
+            }
         }
-      }
     }
     // Is User Admin ?
-    if ($user['admin']){
-			$is_platformAdmin           = true;
-      Database::query("INSERT INTO admin values ('$chamilo_uid')");
+    if ($user['admin']) {
+        $is_platformAdmin = true;
+        Database::query("INSERT INTO admin values ('$chamilo_uid')");
     }
     // Can user create course
-    $is_allowedCreateCourse     = (bool) (($user['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $user['status'] == SESSIONADMIN));
+    $is_allowedCreateCourse = (bool) (($user['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $user['status'] == SESSIONADMIN));
 
     event_login();
 } else {
-	$loginFailed = true;
-	unset($_user['user_id']);
-	$uidReset = false;
+    $loginFailed = true;
+    unset($_user['user_id']);
+    $uidReset = false;
 }
 ?>

+ 18 - 18
main/auth/external_login/updateUser.php

@@ -1,16 +1,17 @@
-<?php //Script loaded by local.inc.php providing update user information of type external_logininfo.
+<?php
+
+//Script loaded by local.inc.php providing update user information of type external_logininfo.
 /*
-This script must not exit.
+  This script must not exit.
  */
 
 use \ChamiloSession as Session;
 
-require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'course.lib.php');
-require_once(dirname(__FILE__).'/functions.inc.php');
+require_once(api_get_path(LIBRARY_PATH) . 'usermanager.lib.php');
+require_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
+require_once(dirname(__FILE__) . '/functions.inc.php');
 
 //MAIN CODE
-
 //$uData variable is set in local.inc.php
 $user = UserManager::get_user_info_by_id($uData['user_id']);
 $new_user = external_get_user_info($login);
@@ -27,17 +28,16 @@ $user['country_bu'] = $new_user['country_bu'];
 $user['extra'] = $new_user['extra'];
 
 if ($new_user !== false) { //User can login    
-  external_update_user($user); 
-  $loginFailed = false;
-  $_user['user_id'] = $user['user_id'];
-  $_user['uidReset'] = true;   
-  $uidReset=true;              
-  Session::write('_user',$_user);
+    external_update_user($user);
+    $loginFailed = false;
+    $_user['user_id'] = $user['user_id'];
+    $_user['uidReset'] = true;
+    $uidReset = true;
+    Session::write('_user', $_user);
 } else { //User cannot login
-  $loginFailed = true;         
-  Session::erase('_uid');   
-  header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=user_password_incorrect');  
-  exit;
-} 
-
+    $loginFailed = true;
+    Session::erase('_uid');
+    header('Location: ' . api_get_path(WEB_PATH) . 'index.php?loginFailed=1&error=user_password_incorrect');
+    exit;
+}
 ?>

+ 7 - 4
main/auth/profile.php

@@ -446,8 +446,8 @@ if ($form->validate()) {
     
     $changeemail = '';
     
-    //If user is sending the email to be changed (input is available and is not freeze )
-    if (api_get_setting('registration', 'email') == 'true' &&  api_get_setting('profile', 'email') == 'true') {        
+    //If user sending the email to be changed (input available and not frozen )
+    if (api_get_setting('profile', 'email') == 'true') {        
 
         if ($allow_users_to_change_email_with_no_password) {            
             if (!check_user_email($user_data['email'])) {
@@ -578,7 +578,7 @@ if ($form->validate()) {
 
 	//change email
 	if ($allow_users_to_change_email_with_no_password) {	    
-        if (in_array('email', $available_values_to_modify)) {
+        if (isset($changeemail) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."',";
         }
         if (isset($password) && in_array('password', $available_values_to_modify)) {
@@ -590,7 +590,10 @@ if ($form->validate()) {
         }	    
     } else {
         //normal behaviour
-        if (!empty($changeemail) && !isset($password) && in_array('email', $available_values_to_modify)) {
+        if(empty($changeemail) && isset($password)) {
+            $sql .= " email = y@u.com";
+        }
+        if (isset($changeemail) && !isset($password) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."'";
         } elseif (isset($password) && isset($changeemail) && in_array('email', $available_values_to_modify) && in_array('password', $available_values_to_modify)) {            
             $sql .= " email = '".Database::escape_string($changeemail)."',";

+ 28 - 27
main/auth/sso/sso.class.php

@@ -46,11 +46,18 @@ class sso {
         header('Location: '.$this->deauth_url);
         exit;
     }
+
     /**
      * Sends the user to the master URL for a check of active connection
      */
     public function ask_master() {
-        header('Location: '.$this->master_url.'&sso_referer='.urlencode($this->referer).'&sso_target='.urlencode($this->target));
+        $params = 'sso_referer='.urlencode($this->referer).'&sso_target='.urlencode($this->target);
+        if (strpos($this->master_url, "?") === false) {
+            $params = "?$params";
+        } else {
+            $params = "&$params";
+        }
+        header('Location: '.$this->master_url.$params);
         exit;
     }
     
@@ -69,7 +76,7 @@ class sso {
      * @return	bool	Return the loginFailed variable value to local.inc.php
      */
     public function check_user() {
-        global $_user, $_configuration;
+        global $_user;
         $loginFailed = false;
         //change the way we recover the cookie depending on how it is formed
         $sso = $this->decode_cookie($_GET['sso_cookie']);
@@ -79,7 +86,7 @@ class sso {
         
         //lookup the user in the main database
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
-        $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
+        $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status
                 FROM $user_table
                 WHERE username = '".trim(Database::escape_string($sso['username']))."'";
         $result = Database::query($sql);
@@ -106,36 +113,33 @@ class sso {
                     //Check if the account is active (not locked)
                     if ($uData['active']=='1') {
                         // check if the expiration date has not been reached
-                        if ($uData['expiration_date'] > date('Y-m-d H:i:s') 
-                         OR $uData['expiration_date']=='0000-00-00 00:00:00') {
+                        if ($uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') {                            
                             //If Multiple URL is enabled
                             if (api_get_multiple_access_url()) {
-                                $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
-                                //Check if user is an admin
-                                $sql = "SELECT user_id FROM $admin_table
-                                        WHERE user_id = '".intval($uData['user_id'])."' LIMIT 1";
-                                $result = Database::query($sql);
-                                $my_user_is_admin = false;
-                                if (Database::num_rows($result) > 0) {
-                                    $my_user_is_admin = true;
-                                }
-                                //Check the access_url configuration setting if
-                                // the user is registered in the 
-                                // access_url_rel_user table
-                                //Getting the current access_url_id 
-                                // of the platform
+                                //Check the access_url configuration setting if the user is registered in the access_url_rel_user table
+                                //Getting the current access_url_id of the platform
                                 $current_access_url_id = api_get_current_access_url_id();
                                 // my user is subscribed in these 
                                 //sites: $my_url_list
                                 $my_url_list = api_get_access_url_from_user($uData['user_id']);
+                            } else {
+                                $current_access_url_id = 1;
+                                $my_url_list = array(1);
+                            }
+                            
+                            $my_user_is_admin = UserManager::is_admin($uData['user_id']);
                                 if ($my_user_is_admin === false) {
                                     if (is_array($my_url_list) && count($my_url_list)>0 ) {
                                         if (in_array($current_access_url_id, $my_url_list)) {
                                             // the user has permission to enter at this site
                                             $_user['user_id'] = $uData['user_id'];                                            
+                                        $_user = api_get_user_info($_user['user_id']);
                                             Session::write('_user',$_user);
                                             event_login();                                            
-                                            self::redirect_to($sso, $_user['user_id'], true);                                        
+                                            // Redirect to homepage
+                                            $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) .'.index.php';
+                                            header('Location: '. $sso_target);
+                                            exit;
                                         } else {
                                             // user does not have permission for this site
                                             $loginFailed = true;
@@ -158,6 +162,9 @@ class sso {
                                         //Check if this admin is admin on the  
                                         // principal portal
                                         $_user['user_id'] = $uData['user_id'];
+                                    $_user = api_get_user_info($_user['user_id']);
+                                    $is_platformAdmin = $uData['status'] == COURSEMANAGER;
+                                    Session::write('is_platformAdmin', $is_platformAdmin);
                                         Session::write('_user',$_user);
                                         event_login();
                                         self::redirect_to($sso, $_user['user_id'], true);
@@ -166,6 +173,7 @@ class sso {
                                         // so we check as a normal user
                                         if (in_array($current_access_url_id, $my_url_list)) {
                                             $_user['user_id'] = $uData['user_id'];
+                                        $_user = api_get_user_info($_user['user_id']);
                                             Session::write('_user',$_user);
                                             event_login();
                                             self::redirect_to($sso, $_user['user_id'], true);
@@ -178,13 +186,6 @@ class sso {
                                     }
                                 }
                             } else {
-                                //Single URL access (Only 1 portal)
-                                $_user['user_id'] = $uData['user_id'];
-                                Session::write('_user',$_user);
-                                event_login();
-                                self::redirect_to($sso, $_user['user_id'], true);                               
-                            }
-                        } else {
                             // user account expired
                             $loginFailed = true;
                             Session::erase('_uid');

+ 13 - 7
main/calendar/agenda.lib.php

@@ -167,12 +167,12 @@ class Agenda {
      * @param string    event content 
      */
 	function edit_event($id, $start, $end, $all_day, $view, $title, $content) {		
-		$start 		= api_get_utc_datetime($start);
+		$start = api_get_utc_datetime($start);
 		
 		if ($all_day == '0') {
-			$end 		= api_get_utc_datetime($end);			
+			$end = api_get_utc_datetime($end);			
 		}
-		$all_day 	= isset($all_day) && $all_day == '1' ? 1:0;
+		$all_day = isset($all_day) && $all_day == '1' ? 1 : 0;
 		
 		$attributes = array();
 
@@ -185,11 +185,14 @@ class Agenda {
 				Database::update($this->tbl_personal_agenda, $attributes, array('id = ?' => $id));
 				break;
 			case 'course':
+                $course_id = api_get_course_int_id();
 				$attributes['title'] 		= $title;
 				$attributes['content'] 		= $content;
 				$attributes['start_date'] 	= $start;
 				$attributes['end_date'] 	= $end;
-				Database::update($this->tbl_course_agenda, $attributes, array('id = ?' => $id));
+                if (!empty($course_id)) {
+                    Database::update($this->tbl_course_agenda, $attributes, array('id = ? AND c_id = ?' => array($id, $course_id)));
+                }
 				break;
 			case 'admin':
 				$attributes['title'] 		= $title;
@@ -205,13 +208,16 @@ class Agenda {
 	function delete_event($id) {
 		switch($this->type) {
 			case 'personal':
-				Database::delete($this->tbl_personal_agenda, array('id = ?' =>$id));
+				Database::delete($this->tbl_personal_agenda, array('id = ?' => $id));
 				break;
 			case 'course':
-				Database::delete($this->tbl_course_agenda, array('id = ?' =>$id));
+                $course_id = api_get_course_int_id();
+                if (!empty($course_id)) {
+                    Database::delete($this->tbl_course_agenda, array('id = ? AND c_id = ?' => array($id, $course_id)));
+                }
 				break;
 			case 'admin':
-				Database::delete($this->tbl_global_agenda, array('id = ?' =>$id));
+				Database::delete($this->tbl_global_agenda, array('id = ?' => $id));
 				break;
 		}
 	}

+ 35 - 10
main/coursecopy/classes/CourseBuilder.class.php

@@ -160,6 +160,8 @@ class CourseBuilder {
 			}
 		}
 
+        // Once we've built the resouces array a bit more, try to get items
+        //  from the item_propry table and order them in the "resources" array
 		foreach ($this->course->resources as $type => $resources) {
 			foreach ($resources as $id => $resource) {
 				$tool = $resource->get_tool();
@@ -438,13 +440,27 @@ class CourseBuilder {
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result)) {
 			if (strlen($obj->sound) > 0) {
-                $sql = "SELECT id FROM ".$table_doc." WHERE c_id = $course_id AND path = '/audio/".$obj->sound."'";
+                $sql = "SELECT id FROM $table_doc WHERE c_id = $course_id AND path = '/audio/".$obj->sound."'";
                 $res = Database::query($sql);
 				$doc = Database::fetch_object($res);
 				$obj->sound = $doc->id;
 			}
-			$quiz = new Quiz($obj->id, $obj->title, $obj->description, $obj->random, $obj->type, $obj->active, $obj->sound, $obj->max_attempt, 
-			                 $obj->results_disabled, $obj->access_condition, $obj->start_time, $obj->end_time, $obj->feedback_type, $obj->random_answers, $obj->expired_time, $obj->session_id);
+            $quiz = new Quiz(   $obj->id,
+                                $obj->title,
+                                $obj->description,
+                                $obj->random,
+                                $obj->type,
+                                $obj->active,
+                                $obj->sound,
+                                $obj->max_attempt,
+                                $obj->results_disabled,
+                                $obj->access_condition,
+                                $obj->start_time,
+                                $obj->end_time,
+                                $obj->feedback_type,
+                                $obj->random_answers,
+                                $obj->expired_time,
+                                $obj->session_id);
 			$sql = 'SELECT * FROM '.$table_rel.' WHERE c_id = '.$course_id.' AND exercice_id = '.$obj->id;            
 			$db_result2 = Database::query($sql);
 			while ($obj2 = Database::fetch_object($db_result2)) {
@@ -474,8 +490,7 @@ class CourseBuilder {
 
 		// Building normal tests.
 		$sql = "SELECT * FROM $table_que WHERE c_id = $course_id ";
-		
-		$db_result = Database::query($sql);
+        $db_result = Database::query($sql);		
 		while ($obj = Database::fetch_object($db_result)) {            
 			$question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture, $obj->level, $obj->extra);
 			$sql = 'SELECT * FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id = '.$obj->id;
@@ -489,18 +504,23 @@ class CourseBuilder {
 		// Building a fictional test for collecting orphan questions.
 		$build_orphan_questions = !empty($_POST['recycle_option']); // When a course is emptied this option should be activated (true).
         
-		$sql = "SELECT * FROM $table_que as questions 
+        $sql = "SELECT questions.*
+                FROM $table_que as questions
                 LEFT JOIN $table_rel as quizz_questions 
                     ON (questions.id = quizz_questions.question_id AND questions.c_id = $course_id AND quizz_questions.c_id = $course_id)
                 LEFT JOIN $table_qui as exercices 
                     ON (exercice_id = exercices.id AND exercices.c_id = $course_id AND questions.c_id = $course_id)
-				WHERE quizz_questions.exercice_id IS NULL OR exercices.active = -1"; // active = -1 means "deleted" test.
+                WHERE  questions.c_id = $course_id AND
+                       exercices.c_id = $course_id AND
+                       (quizz_questions.exercice_id IS NULL OR exercices.active = -1) "; // active = -1 means "deleted" test.
         
 		$db_result = Database::query($sql);
 		if (Database::num_rows($db_result) > 0) {
 			$build_orphan_questions = true;
 			while ($obj = Database::fetch_object($db_result)) {
-				$question = new QuizQuestion($obj->id.$course_id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture,$obj->level, $obj->extra);
+                //Avoid adding the same question twice
+                if (!isset($this->course->resources[$obj->id])) {
+                    $question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture,$obj->level, $obj->extra);
 				$sql = "SELECT * FROM $table_ans WHERE c_id = $course_id AND question_id = ".$obj->id;
 				$db_result2 = Database::query($sql);
                 if (Database::num_rows($db_result2)) {
@@ -511,6 +531,7 @@ class CourseBuilder {
 				$this->course->add_resource($question);
 			}
 		}
+        }
         
 		if ($build_orphan_questions) {
 			//$this->course->add_resource(new Quiz(-1, get_lang('OrphanQuestions', ''), '', 0, 0, 1, '', 0));
@@ -925,8 +946,12 @@ class CourseBuilder {
             //$sql = 'SELECT * FROM '.$table_thematic_plan.' WHERE c_id = '.$course_id.' AND thematic_id = '.$row['id'];
             
             $sql = "SELECT tp.*
-                FROM $table_thematic_plan tp INNER JOIN $table_thematic t ON (t.id=tp.thematic_id) 			        
-                WHERE  t.c_id = $course_id AND tp.c_id = $course_id  AND thematic_id = {$row['id']}  AND tp.id IN (".implode(', ', $thematic_plan_id_list).") ";
+                    FROM $table_thematic_plan tp
+                        INNER JOIN $table_thematic t ON (t.id=tp.thematic_id)
+                    WHERE   t.c_id = $course_id AND
+                            tp.c_id = $course_id AND
+                            thematic_id = {$row['id']}  AND
+                             tp.id IN (".implode(', ', $thematic_plan_id_list).") ";
 
 				
 			$result = Database::query($sql);

+ 41 - 19
main/coursecopy/classes/CourseRecycler.class.php

@@ -30,8 +30,11 @@ class CourseRecycler
      * Delete all items from the course.
      * This deletes all items in the course-object from the current Chamilo-
      * course
+     * @param string The type of recycling we want (full_backup or select_items)
+     * @assert (null) === false
      */
     function recycle($type) {
+        if (empty($type)) { return false; }
         $this->type = $type;
             	
         $table_tool_intro 		= Database::get_course_table(TABLE_TOOL_INTRO);
@@ -301,34 +304,44 @@ class CourseRecycler
      * Recycle quizzes - doesn't remove the questions and their answers, as they might still be used later
      */
     function recycle_quizzes() {
-    	
         if ($this->course->has_resources(RESOURCE_QUIZ)) {
-            $table_qui_que 	= Database :: get_course_table(TABLE_QUIZ_QUESTION);
-            $table_qui_ans 	= Database :: get_course_table(TABLE_QUIZ_ANSWER);
-            $table_qui 		= Database :: get_course_table(TABLE_QUIZ_TEST);
-            $table_rel 		= Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
+            $table_qui_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+            $table_qui_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
+            $table_qui 	   = Database :: get_course_table(TABLE_QUIZ_TEST);
+            $table_rel 	   = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
+            $table_qui_que_opt = Database :: get_course_table(TABLE_QUIZ_QUESTION_OPTION);
+            $table_qui_que_cat = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
+            $table_qui_que_rel_cat = Database :: get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
 
             $ids = array_keys($this->course->resources[RESOURCE_QUIZ]);
+            // If the value "-1" is in the ids of elements (questions) to
+            // be deleted, then consider all orphan questions should be deleted
+            // This value is set in CourseBuilder::quiz_build_questions()
             $delete_orphan_questions = in_array(-1, $ids);
             $ids = implode(',', $ids);
 
-            // Deletion of the normal tests, questions in them are not deleted, they become orphan at this moment.
+            // Deletion of the tests first. Questions in these tests are 
+            //   not deleted and become orphan at this point
             $sql = "DELETE FROM ".$table_qui." WHERE c_id = ".$this->course_id." AND id IN(".$ids.")";
             Database::query($sql);
-            
             $sql = "DELETE FROM ".$table_rel." WHERE c_id = ".$this->course_id." AND exercice_id IN(".$ids.")";
             Database::query($sql);
 
             // Identifying again and deletion of the orphan questions, if it was desired.
             if ($delete_orphan_questions) {
-                $sql = 'SELECT questions.id FROM '.$table_qui_que.' as questions LEFT JOIN '.$table_rel.' as quizz_questions 
-                		ON questions.id=quizz_questions.question_id LEFT JOIN '.$table_qui.' as exercices 
-                		ON exercice_id=exercices.id 
-                		WHERE 
-                			questions.c_id = '.$this->course_id.' AND
-                			quizz_questions.c_id = '.$this->course_id.' AND
-                			exercices.c_id = '.$this->course_id.' AND 
-                			quizz_questions.exercice_id IS NULL OR exercices.active = -1'; // active = -1 means "deleted" test.
+                $sql = 'SELECT questions.id '.
+                       ' FROM '.$table_qui_que.' as questions '.
+                       ' LEFT JOIN '.$table_rel.' as quizz_questions '.
+                       '   ON questions.id=quizz_questions.question_id '.
+                       ' LEFT JOIN '.$table_qui.' as exercices '.
+                       '   ON exercice_id=exercices.id '.
+                       ' WHERE '.
+                       '   questions.c_id = '.$this->course_id.' AND '.
+                       '   quizz_questions.c_id = '.$this->course_id.' AND '.
+                       '   exercices.c_id = '.$this->course_id.' AND '.
+                       '   quizz_questions.exercice_id IS NULL OR '.
+                       '   exercices.active = -1'; 
+                       // active = -1 means "deleted" test.
                 $db_result = Database::query($sql);
                 if (Database::num_rows($db_result) > 0) {
                     $orphan_ids = array();
@@ -343,10 +356,19 @@ class CourseRecycler
                     $sql = "DELETE FROM ".$table_qui_que." WHERE c_id = ".$this->course_id." AND id IN(".$orphan_ids.")";
                     Database::query($sql);
                 }
-            }            
+                // Also delete questions categories and options
+                $sql = "DELETE FROM $table_qui_que_rel_cat WHERE c_id = ".$this->course_id;
+                Database::query($sql);
+                $sql = "DELETE FROM $table_qui_que_cat WHERE c_id = ".$this->course_id;
+                Database::query($sql);
+                $sql = "DELETE FROM $table_qui_que_opt WHERE c_id = ".$this->course_id;
+                Database::query($sql);
+            }
+            // Quizzes previously deleted are, in fact, kept with a status
+            //  (active field) of "-1". Delete those, now.
             $sql = "DELETE FROM ".$table_qui." WHERE c_id = ".$this->course_id." AND active = -1";
-            Database::query($sql);            
-        }        
+            Database::query($sql); 
+        }
     }
     
     /**
@@ -493,4 +515,4 @@ class CourseRecycler
             }
         }
     }
-}
+}

+ 127 - 105
main/coursecopy/classes/CourseRestorer.class.php

@@ -56,19 +56,19 @@ class CourseRestorer
 	var $file_option;
 	var $set_tools_invisible_by_default;
 	var $skip_content;
-    var $tools_to_restore = array(                            
+    var $tools_to_restore = array(
                             'announcements',
                             'attendance',
                             'course_descriptions',
-                            'documents', 
+                            'documents',
                             'events',
-                            'forum_category', 
+                            'forum_category',
                             'forums',
                            // 'forum_topics',
                             'glossary',
-                            'quizzes', 
-                            'links', 
-                            'learnpaths',                       
+                            'quizzes',
+                            'links',
+                            'learnpaths',
                             'surveys',
                             //'scorm_documents', ??
                             'tool_intro',
@@ -130,8 +130,8 @@ class CourseRestorer
 			$this->course->destination_path = $course_info['path'];
 		}
 		$this->destination_course_id = $course_info['real_id'];
-        
-        //Getting first teacher (for the forums)        
+
+        //Getting first teacher (for the forums)
         $teacher_list = CourseManager::get_teacher_list_from_course_code($course_info['code']);
         $this->first_teacher_id = api_get_user_id();
         if (!empty($teacher_list)) {
@@ -301,7 +301,7 @@ class CourseRestorer
 
 			$table = Database :: get_course_table(TABLE_DOCUMENT);
 			$resources = $this->course->resources;
-            
+
 			foreach ($resources[RESOURCE_DOCUMENT] as $id => $document) {
 				$path = api_get_path(SYS_COURSE_PATH).$this->course->destination_path.'/';
 				//$dirs = explode('/', dirname($document->path));
@@ -311,7 +311,7 @@ class CourseRestorer
                 } else {
                     $my_session_id = $session_id;
                 }
-                
+
 		    	if ($document->file_type == FOLDER) {
 		    		$visibility = $document->item_properties[0]['visibility'];
 		    		if (!empty($document->title))  {
@@ -321,17 +321,17 @@ class CourseRestorer
 		    		}
 		    		$new = substr($document->path, 8);
 
-		    		if (!is_dir($path.'document'.$new)) {		    			
+		    		if (!is_dir($path.'document'.$new)) {
 						$created_dir = create_unexisting_directory($course_info, api_get_user_id(), $my_session_id, 0, 0 ,$path.'document', $new, $title, $visibility);
 		    		}
-		    	} elseif ($document->file_type == DOCUMENT) {		                     
-                    //Checking if folder exists in the database otherwise we created it 
-                    $dir_to_create = dirname($document->path);                    
+		    	} elseif ($document->file_type == DOCUMENT) {
+                    //Checking if folder exists in the database otherwise we created it
+                    $dir_to_create = dirname($document->path);
                     if (!empty($dir_to_create) && $dir_to_create != 'document' && $dir_to_create != '/') {
                         if (is_dir($path.dirname($document->path))) {
                             $sql = "SELECT id FROM ".$table." WHERE c_id = ".$this->destination_course_id." AND path = '/".self::DBUTF8escapestring(substr(dirname($document->path), 9))."'";
-                            $res = Database::query($sql);                            
-                            if (Database::num_rows($res) == 0) {                         
+                            $res = Database::query($sql);
+                            if (Database::num_rows($res) == 0) {
                                 //continue;
                                 $visibility = $document->item_properties[0]['visibility'];
                                 $new        = '/'.substr(dirname($document->path), 9);
@@ -346,7 +346,7 @@ class CourseRestorer
                         }
                     }
 
-					if (file_exists($path.$document->path)) {					    
+					if (file_exists($path.$document->path)) {
 						switch ($this->file_option) {
 							case FILE_OVERWRITE :
                                 $origin_path = $this->course->backup_path.'/'.$document->path;
@@ -386,7 +386,7 @@ class CourseRestorer
                                 //Replace old course code with the new destination code
 
                                 $file_info = pathinfo($path.$document->path);
-                                
+
                                 if (in_array($file_info['extension'], array('html','htm'))) {
                                     $content    = file_get_contents($path.$document->path);
                                     if (UTF8_CONVERT) $content = utf8_encode($content);
@@ -714,90 +714,91 @@ class CourseRestorer
                 } else {
                     $cat_id = $this->course->resources[RESOURCE_FORUMCATEGORY][$params['forum_category']]->destination_id;
                 }
-                
+
                 self::DBUTF8_array($params);
                 $params['c_id'] = $this->destination_course_id;
-                $params['forum_category'] = $cat_id;    
+                $params['forum_category'] = $cat_id;
                 unset($params['forum_id']);
-                
-                $params['forum_comment'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($params['forum_comment'], $this->course->code, $this->course->destination_path);        
-                
+
+                $params['forum_comment'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($params['forum_comment'], $this->course->code, $this->course->destination_path);
+
                 if (!empty($params['forum_image'])) {
-                    $original_forum_image = $this->course->path.'upload/forum/images/'.$params['forum_image'];                    
+                    $original_forum_image = $this->course->path.'upload/forum/images/'.$params['forum_image'];
                     if (file_exists($original_forum_image)) {
-                        $new_forum_image = api_get_path(SYS_COURSE_PATH).$this->destination_course_info['path'].'/upload/forum/images/'.$params['forum_image'];                        
+                        $new_forum_image = api_get_path(SYS_COURSE_PATH).$this->destination_course_info['path'].'/upload/forum/images/'.$params['forum_image'];
                         @copy($original_forum_image, $new_forum_image);
                     }
                 }
-                
+
                 $new_id = Database::insert($table_forum, $params);
-			
+
 				$this->course->resources[RESOURCE_FORUM][$id]->destination_id = $new_id;
-                
+
 				$forum_topics = 0;
-				if (is_array($this->course->resources[RESOURCE_FORUMTOPIC])) {                    
-					foreach ($this->course->resources[RESOURCE_FORUMTOPIC] as $topic_id => $topic) {                        
+				if (is_array($this->course->resources[RESOURCE_FORUMTOPIC])) {
+					foreach ($this->course->resources[RESOURCE_FORUMTOPIC] as $topic_id => $topic) {
 						if ($topic->obj->forum_id == $id) {
 							$this->restore_topic($topic_id, $new_id);
 							$forum_topics ++;
 						}
 					}
 				}
-				if ($forum_topics > 0) {					
-					$sql = "UPDATE ".$table_forum." SET forum_threads = ".$forum_topics." 
+				if ($forum_topics > 0) {
+					$sql = "UPDATE ".$table_forum." SET forum_threads = ".$forum_topics."
                             WHERE c_id = {$this->destination_course_id} AND forum_id = ".(int)$new_id;
 					Database::query($sql);
 				}
 			}
 		}
 	}
-    
+
 	/**
 	 * Restore forum-categories
-	 */    
+	 */
 	function restore_forum_category($my_id = null) {
 		$forum_cat_table = Database :: get_course_table(TABLE_FORUM_CATEGORY);
 		$resources = $this->course->resources;
-		//$forum_cat = $resources[RESOURCE_FORUMCATEGORY][$id];
-        foreach ($resources[RESOURCE_FORUMCATEGORY] as $id => $forum_cat) {
-            if (!empty($my_id)) {
-                if ($my_id != $id) {
-                    continue;
+        if (!empty($resources[RESOURCE_FORUMCATEGORY])) {
+            foreach ($resources[RESOURCE_FORUMCATEGORY] as $id => $forum_cat) {
+                if (!empty($my_id)) {
+                    if ($my_id != $id) {
+                        continue;
+                    }
                 }
-            }
-            if ($forum_cat && !$forum_cat->is_restored()) {
-                $title = $forum_cat->obj->cat_title;
-                if (!empty($title)) {
-                    if (!preg_match('/.*\((.+)\)$/', $title, $matches)) {
-                        // This is for avoiding repetitive adding of training code after several backup/restore cycles.
-                        if ($matches[1] != $this->course->code) {
-                            $title = $title.' ('.$this->course->code.')';
+                if ($forum_cat && !$forum_cat->is_restored()) {
+                    $title = $forum_cat->obj->cat_title;
+                    if (!empty($title)) {
+                        if (!preg_match('/.*\((.+)\)$/', $title, $matches)) {
+                            // This is for avoiding repetitive adding of training code after several backup/restore cycles.
+                            if ($matches[1] != $this->course->code) {
+                                $title = $title.' ('.$this->course->code.')';
+                            }
                         }
                     }
+                    $params = (array) $forum_cat->obj;
+                    $params['c_id'] = $this->destination_course_id;
+                    $params['cat_comment']    = DocumentManager::replace_urls_inside_content_html_from_copy_course($params['cat_comment'], $this->course->code, $this->course->destination_path);
+                    unset($params['cat_id']);
+                    self::DBUTF8_array($params);
+                    $new_id = Database::insert($forum_cat_table, $params);
+                    $this->course->resources[RESOURCE_FORUMCATEGORY][$id]->destination_id = $new_id;
+                    if (!empty($my_id)) {
+                        return $new_id;
+                    }
                 }
-                $params = (array) $forum_cat->obj;
-                $params['c_id'] = $this->destination_course_id;                
-                $params['cat_comment']    = DocumentManager::replace_urls_inside_content_html_from_copy_course($params['cat_comment'], $this->course->code, $this->course->destination_path);
-                unset($params['cat_id']);
-                self::DBUTF8_array($params);     
-                $new_id = Database::insert($forum_cat_table, $params);                
-                $this->course->resources[RESOURCE_FORUMCATEGORY][$id]->destination_id = $new_id;                
-                if (!empty($my_id)) {
-                    return $new_id;
-                }
-            }            
+            }
         }
 	}
-    
+
 	/**
 	 * Restore a forum-topic
 	 */
 	function restore_topic($thread_id, $forum_id) {
-		$table = Database :: get_course_table(TABLE_FORUM_THREAD);        
+		$table = Database :: get_course_table(TABLE_FORUM_THREAD);
 		$topic = $this->course->resources[RESOURCE_FORUMTOPIC][$thread_id];
-		                 
+
         $params = (array)$topic->obj;
-        self::DBUTF8_array($params);        
+        self::DBUTF8_array($params);
         $params['c_id']     = $this->destination_course_id;
         $params['forum_id'] = $forum_id;
         $params['thread_poster_id'] = $this->first_teacher_id;
@@ -807,44 +808,44 @@ class CourseRestorer
         $params['thread_replies'] = 0;
         $params['thread_views'] = 0;
         unset($params['thread_id']);
-        
-        $new_id = Database::insert($table, $params);        
+
+        $new_id = Database::insert($table, $params);
         api_item_property_update($this->destination_course_info, TOOL_FORUM_THREAD, $new_id, 'ThreadAdded', api_get_user_id(), 0, 0, null, null);
-        
+
 		$this->course->resources[RESOURCE_FORUMTOPIC][$thread_id]->destination_id = $new_id;
-        
-		$topic_replies = -1;        
-        
-		foreach ($this->course->resources[RESOURCE_FORUMPOST] as $post_id => $post){    
+
+		$topic_replies = -1;
+
+		foreach ($this->course->resources[RESOURCE_FORUMPOST] as $post_id => $post){
 			if ($post->obj->thread_id == $thread_id) {
 				$topic_replies++;
 				$this->restore_post($post_id, $new_id, $forum_id);
 			}
-		}       
+		}
 		return $new_id;
 	}
-    
+
 	/**
 	 * Restore a forum-post
 	 * @TODO Restore tree-structure of posts. For example: attachments to posts.
 	 */
 	function restore_post($id, $topic_id, $forum_id) {
 		$table_post = Database :: get_course_table(TABLE_FORUM_POST);
-		$post = $this->course->resources[RESOURCE_FORUMPOST][$id];        
+		$post = $this->course->resources[RESOURCE_FORUMPOST][$id];
         $params = (array) $post->obj;
         $params['c_id'] = $this->destination_course_id;
         $params['forum_id'] = $forum_id;
         $params['thread_id'] = $topic_id;
         $params['poster_id'] = $this->first_teacher_id;
         $params['post_date'] = api_get_utc_datetime();
-        unset($params['post_id']);        
-        $params['post_text']    = DocumentManager::replace_urls_inside_content_html_from_copy_course($params['post_text'], $this->course->code, $this->course->destination_path);        
+        unset($params['post_id']);
+        $params['post_text']    = DocumentManager::replace_urls_inside_content_html_from_copy_course($params['post_text'], $this->course->code, $this->course->destination_path);
         $new_id = Database::insert($table_post, $params);
-        api_item_property_update($this->destination_course_info, TOOL_FORUM_POST, $new_id, 'PostAdded', api_get_user_id(), 0, 0, null, null);        
+        api_item_property_update($this->destination_course_info, TOOL_FORUM_POST, $new_id, 'PostAdded', api_get_user_id(), 0, 0, null, null);
 		$this->course->resources[RESOURCE_FORUMPOST][$id]->destination_id = $new_id;
 		return $new_id;
 	}
-    
+
 	/**
 	 * Restore links
 	 */
@@ -877,7 +878,7 @@ class CourseRestorer
 			}
 		}
 	}
-    
+
 	/**
 	 * Restore tool intro
 	 */
@@ -943,7 +944,7 @@ class CourseRestorer
                         all_day = '".$event->all_day."',
         				start_date = '".$event->start_date."',
         				end_date = '".$event->end_date."'";
-                
+
 				Database::query($sql);
 				$new_event_id = Database::insert_id();
 				$this->course->resources[RESOURCE_EVENT][$id]->destination_id = $new_event_id;
@@ -985,7 +986,7 @@ class CourseRestorer
 			}
 		}
 	}
-    
+
 	/**
 	 * Restore course-description
 	 */
@@ -1016,7 +1017,7 @@ class CourseRestorer
 			}
 		}
 	}
-    
+
 	/**
 	 * Restore announcements
 	 */
@@ -1149,13 +1150,14 @@ class CourseRestorer
 					// $id = -1 identifies the fictionary test for collecting orphan questions. We do not store it in the database.
 					$new_id = -1;
 				}
-                
+
 				$this->course->resources[RESOURCE_QUIZ][$id]->destination_id = $new_id;
-				$order = 0;                
+				$order = 0;
+
 				foreach ($quiz->question_ids as $index => $question_id) {
 					$qid = $this->restore_quiz_question($question_id);
-					$question_order = $quiz->question_orders[$index] ? $quiz->question_orders[$index] : ++$order;					
-					$sql = "INSERT IGNORE INTO ".$table_rel." SET c_id = ".$this->destination_course_id." , question_id = ".$qid.", exercice_id = ".$new_id.", question_order = ".$question_order;
+					$question_order = $quiz->question_orders[$index] ? $quiz->question_orders[$index] : ++$order;
+					$sql = "INSERT IGNORE INTO ".$table_rel." SET c_id = ".$this->destination_course_id.", question_id = ".$qid.", exercice_id = ".$new_id.", question_order = ".$question_order;
 					Database::query($sql);
 				}
 			}
@@ -1166,9 +1168,9 @@ class CourseRestorer
 	 * Restore quiz-questions
 	 */
 	function restore_quiz_question($id) {
-		$resources = $this->course->resources;        
-		$question = $resources[RESOURCE_QUIZQUESTION][$id];   
-                
+		$resources = $this->course->resources;
+		$question = $resources[RESOURCE_QUIZQUESTION][$id];
+
 		$new_id = 0;
 
 		if (is_object($question)) {
@@ -1192,17 +1194,26 @@ class CourseRestorer
                     picture='".self::DBUTF8escapestring($question->picture)."',
                     level='".self::DBUTF8escapestring($question->level)."',
                     extra='".self::DBUTF8escapestring($question->extra)."'";
-            
+
 			Database::query($sql);
-			$new_id = Database::insert_id();        
-            
+			$new_id = Database::insert_id();
+
 			if ($question->quiz_type == MATCHING) {
                 $t = array();
                 foreach ($question->answers as $index => $answer) {
                     $t[$answer['position']] = $answer;
                 }
                 foreach ($t as $index => $answer) {
-                    $sql = "INSERT INTO ".$table_ans." SET c_id = ".$this->destination_course_id." , id= '".$index."',question_id = '".$new_id."', answer = '".self::DBUTF8escapestring($answer['answer'])."', correct = '".$answer['correct']."', comment = '".self::DBUTF8escapestring($answer['comment'])."', ponderation='".$answer['ponderation']."', position = '".$answer['position']."', hotspot_coordinates = '".$answer['hotspot_coordinates']."', hotspot_type = '".$answer['hotspot_type']."'";
+                    $sql = "INSERT INTO ".$table_ans." SET
+                            c_id = ".$this->destination_course_id." ,
+                            id = '".$index."', question_id = '".$new_id."',
+                            answer = '".self::DBUTF8escapestring($answer['answer'])."',
+                            correct = '".$answer['correct']."',
+                            comment = '".self::DBUTF8escapestring($answer['comment'])."',
+                            ponderation = '".$answer['ponderation']."',
+                            position = '".$answer['position']."',
+                            hotspot_coordinates = '".$answer['hotspot_coordinates']."',
+                            hotspot_type = '".$answer['hotspot_type']."'";
 					Database::query($sql);
 				}
 			} else {
@@ -1212,10 +1223,21 @@ class CourseRestorer
 					$answer['answer']  = DocumentManager::replace_urls_inside_content_html_from_copy_course($answer['answer'], $this->course->code, $this->course->destination_path);
 					$answer['comment'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($answer['comment'], $this->course->code, $this->course->destination_path);
 
-					$sql = "INSERT INTO ".$table_ans." SET c_id = ".$this->destination_course_id." , id= '". ($index +1)."',question_id = '".$new_id."', answer = '".self::DBUTF8escapestring($answer['answer'])."', correct = '".$answer['correct']."', comment = '".self::DBUTF8escapestring($answer['comment'])."', ponderation='".$answer['ponderation']."', position = '".$answer['position']."', hotspot_coordinates = '".$answer['hotspot_coordinates']."', hotspot_type = '".$answer['hotspot_type']."'";
+					$sql = "INSERT INTO ".$table_ans." SET
+                                c_id = ".$this->destination_course_id." ,
+                                id = '". ($index + 1)."',
+                                question_id = '".$new_id."',
+                                answer = '".self::DBUTF8escapestring($answer['answer'])."',
+                                correct = '".$answer['correct']."',
+                                comment = '".self::DBUTF8escapestring($answer['comment'])."',
+                                ponderation = '".$answer['ponderation']."',
+                                position = '".$answer['position']."',
+                                hotspot_coordinates = '".$answer['hotspot_coordinates']."',
+                                hotspot_type = '".$answer['hotspot_type']."'";
 					Database::query($sql);
 				}
 			}
+
             //@todo check this
             $course_id = api_get_course_int_id();
 
@@ -1231,8 +1253,9 @@ class CourseRestorer
                     $question_option_id = Database::insert($table_options, $item);
                     $old_option_ids[$old_id] = $question_option_id;
                 }
-                $new_answers = Database::select('id, correct', $table_ans, array('WHERE' => array('question_id = ? AND c_id = ? '=>array($new_id, $this->destination_course_id))));
+                $new_answers = Database::select('id, correct', $table_ans, array('WHERE' => array('question_id = ? AND c_id = ? '=> array($new_id, $this->destination_course_id))));
                 foreach ($new_answers as $answer_item) {
+                    $params = array();
                     $params['correct'] = $old_option_ids[$answer_item['correct']];
                     $question_option_id = Database::update($table_ans, $params, array('id = ? AND c_id = ? '=> array($answer_item['id'], $this->destination_course_id)));
                 }
@@ -1241,7 +1264,7 @@ class CourseRestorer
 		}
 		return $new_id;
 	}
-    
+
 	/**
 	 * Restore surveys
 	 */
@@ -1550,19 +1573,19 @@ class CourseRestorer
 				$old_prerequisite 	= array();
 				$old_refs 			= array();
 				$prerequisite_ids 	= array();
-                
-				foreach ($lp->get_items() as $index => $item) {                    
+
+				foreach ($lp->get_items() as $index => $item) {
 					// we set the ref code here and then we update in a for loop
 					$ref = $item['ref'];
 
 					//Dealing with path the same way as ref as some data has been put into path when it's a local resource
 					//Only fix the path for no scos
                     if ($item['item_type'] == 'sco') {
-                        $path = self::DBUTF8escapestring($item['path']);                        
+                        $path = self::DBUTF8escapestring($item['path']);
                     } else {
-                        $path = self::DBUTF8escapestring($item['path']);                    
+                        $path = self::DBUTF8escapestring($item['path']);
                         $path = $this->get_new_id($item['item_type'], $path);
-                    }                
+                    }
 
 					$sql = "INSERT INTO ".$table_item." SET
 							c_id = ".$this->destination_course_id." ,
@@ -1785,15 +1808,15 @@ class CourseRestorer
             return $ref;
         }
 
-		if ($tool == 'hotpotatoes') { 
-            $tool = 'document'; 
+		if ($tool == 'hotpotatoes') {
+            $tool = 'document';
         }
 		if (!empty($this->course->resources[$tool][$ref]->destination_id)) {
 			return $this->course->resources[$tool][$ref]->destination_id;
 		}
 		return '';
 	}
-    
+
 	/**
 	 * Restore glossary
 	 */
@@ -1956,10 +1979,9 @@ class CourseRestorer
 		if (UTF8_CONVERT) $str = utf8_encode($str);
 		return Database::escape_string($str);
 	}
-    
-    function DBUTF8_array($array) {        
+
+    function DBUTF8_array($array) {
         if (UTF8_CONVERT) {
-            
             foreach ($array as &$item)  {
                 $item = utf8_encode($item);
             }

+ 22 - 16
main/coursecopy/classes/CourseSelectForm.class.php

@@ -48,10 +48,7 @@ class CourseSelectForm
 				}
 			}
             
-            function setCheckboxForum(type, value, item_id) {
-                //console.log("#resource["+type+"]["+value+"]");
-                //$("#resource["+type+"]["+value+"]").attr('checked', value);
-                
+            function setCheckboxForum(type, value, item_id) {                
  				d = document.course_select_form;
  				for (i = 0; i < d.elements.length; i++) {
    					if (d.elements[i].type == "checkbox") {
@@ -371,11 +368,17 @@ class CourseSelectForm
 	 * @return course The course-object with all resources selected by the user
 	 * in the form given by display_form(...)
 	 */
-	static function get_posted_course($from='', $session_id = 0, $course_code = '') {
-		$course = Course::unserialize(base64_decode($_POST['course']));
+	static function get_posted_course($from = '', $session_id = 0, $course_code = '') {
+        $course = null;
+        
+        if (isset($_POST['course'])) {
+            $course = Course::unserialize(base64_decode($_POST['course']));
+        } else {
+            return false;
+        }
         
 		//Create the resource DOCUMENT objects
-		//Loading the results from the checkboxes of the javascript
+		//Loading the results from the checkboxes of ethe javascript
 		$resource       = $_POST['resource'][RESOURCE_DOCUMENT];
 
 		$course_info 	= api_get_course_info($course_code);
@@ -408,19 +411,22 @@ class CourseSelectForm
 					$db_result = Database::query($sql);
 					while ($obj = Database::fetch_object($db_result)) {
 						$doc = new Document($obj->id, $obj->path, $obj->comment, $obj->title, $obj->filetype, $obj->size);
-						$course->add_resource($doc);
-						// adding item property
-						$sql = "SELECT * FROM $table_prop WHERE c_id = '.$course_id.'  AND TOOL = '".RESOURCE_DOCUMENT."' AND ref='".$resource_item."'";
-						$res = Database::query($sql);
-						$all_properties = array ();
-						while ($item_property = Database::fetch_array($res,'ASSOC')) {
-							$all_properties[] = $item_property;
-						}
-						$course->resources[RESOURCE_DOCUMENT][$resource_item]->item_properties = $all_properties;
+                        if ($doc) {
+                            $course->add_resource($doc);
+                            // adding item property
+                            $sql = "SELECT * FROM $table_prop WHERE c_id = $course_id AND tool = '".RESOURCE_DOCUMENT."' AND ref = $resource_item ";
+                            $res = Database::query($sql);
+                            $all_properties = array ();
+                            while ($item_property = Database::fetch_array($res,'ASSOC')) {
+                                $all_properties[] = $item_property;
+                            }
+                            $course->resources[RESOURCE_DOCUMENT][$resource_item]->item_properties = $all_properties;
+                        }
 					}
 				}
 			}
 		}
+        
 		if (is_array($course->resources)) {
 			foreach ($course->resources as $type => $resources) {
 				switch ($type) {

+ 47 - 27
main/css/base.css

@@ -385,7 +385,7 @@ footer .container .row {
     border:1px solid #ccc;
     margin-bottom: 11px;
     height:32px;
-    padding: 2px 2px 2px 8px;
+    padding: 2px 2px 2px 14px;
     vertical-align:middle;    
 }
 
@@ -489,10 +489,16 @@ a.tag {
     height: 30px;
 }
 
-/* Fixes course items with bootstrap 2.1.1*/
-.course_item h3{
-    margin:0px 0px 5px 0px;
-    line-height: 28px;
+/* user_portal session list */
+.session_course_item .courses {
+    margin-bottom: 5px;
+    height:35px;
+}
+.session_course_item {
+    /* padding: 0px; */
+    margin: 0px;
+    margin-bottom:15px;
+    font-size:135%;
 }
 
 .userportal-course-item {
@@ -508,6 +514,9 @@ a.tag {
     margin-bottom: 7px;
 }
 
+.session_course_item .item_closed, .userportal-course-item-title .item_closed {
+    font-size:80%;
+}
 #maincontent .courseslist li {
     margin-bottom:8px;
 }
@@ -2523,15 +2532,16 @@ div.admin_section h4 {
     margin: 0;
     width: 100%;
     margin: 0 0 0 0px;
+    padding: 0px 0px 5px 0px;
 }
 .question_answer label {
-    color: #222222;
-    display: block;
-    font-size: 100%;
-    line-height: 150%;
-    margin: -16px 0 0 23px;
-    padding: 0 0 5px;
-    width: 88%;
+    float:left;
+    margin: 0px 0 0 8px;
+}
+
+.question_answer input {
+    float: left;
+    margin: 0px;
 }
 
 #question_description {
@@ -2568,7 +2578,7 @@ div.admin_section h4 {
 }
 
 .ribbon .rib {    
-    height: 30px;
+    height: 28px;
     width: 120px;
     display: block;    
     line-height: 1.3;
@@ -2576,7 +2586,7 @@ div.admin_section h4 {
     top: 0px;
     color: #cfcfcf;
     margin: 0;
-    padding: 5px 10px;
+    padding: 2px 10px;
     position: relative;   
     text-shadow: 0 1px 1px #111;
     border-top: 1px solid #363636;
@@ -2592,11 +2602,13 @@ div.admin_section h4 {
     
     border-radius: 5px 2px 0 0;
     box-shadow: 0 1px 2px rgba(0,0,0,0.3);
+    float: left;
 }
 
 .ribbon .rib h3 {    
     color: white;
     font-size: 16px;
+    float:left;
 }
 
 .ribbon .rib-total {
@@ -2615,6 +2627,7 @@ div.admin_section h4 {
     
     border-top: 1px solid #C56E5B;
     border-bottom: 1px solid #7A290F;
+    float: left;
 }
 
 .ribbon .rib-gray {
@@ -2629,6 +2642,7 @@ div.admin_section h4 {
     
     border-top: 1px solid #bbbbbb;
     border-bottom: 1px solid #bbbbbb;
+    float: left;
 }
 
 
@@ -2643,18 +2657,14 @@ div.admin_section h4 {
 
     border-top: 1px solid #A8C31B;
     border-bottom: 1px solid #617700;
+    float: left;
 }
 
-.ribbon h4 {
-    display: block;
-    left: 140px;
-    height: 30px;
-    line-height: 1.3;    
+.ribbon h4 {  
     margin: 0;
-    padding: 5px 10px;
-    position: absolute;    
-    top: 8px;
+    padding: 8px 10px;
     color: #444;
+    float:left;
 }
 
 .ribbon-total h4 {
@@ -2713,11 +2723,6 @@ div.admin_section h4 {
     color: green;
 }
 
-.ribbon h3 {
-    font-size: 18px;
-    line-height: 9px;
-}
-
 .exercise_save_now_button img {
     position: relative;
     top: 4px;
@@ -3390,6 +3395,21 @@ a:active{
     margin-right: 4px;
 }
 
+.teacher_online {
+    background: url("teacher.png") no-repeat scroll right center transparent;
+    height: 16px;
+    width: 17px;
+    display: inline-block;
+    margin-right: 4px;
+}
+
+.student_online {
+    background: url("student.png") no-repeat scroll right center transparent;
+    height: 16px;
+    width: 17px;
+    display: inline-block;
+    margin-right: 4px;
+}
 #online_grid_container .thumbnail .caption {
     text-align:center;
 }

+ 320 - 384
main/css/responsive.css

@@ -1,103 +1,298 @@
 /* media queries responsive */
+/* Typical screen resolutions (only width matters) are:
+320*
+480*
+640*
+720* (samsung S3)
+800*
+1024*
+1152
+1280*
+1360
+1400
+1440*
+1600*
+1680
+1920*
++more*
+The more frequent ones have been marked with *
+*/
+/* Phone */
 
-/* LARGE DESKTOP SCREENS */
-@media (min-width: 1201px) {   
-}
-
-@media (max-width: 1200px) {
-}
-
-/* Tablet or large-screen phone */
-
-@media (max-width: 1024px) {
-    /* fixes tabs */
-    .subnav .nav-tabs > li > a, .subnav .nav-pills > li > a {
-        padding-left: 6px;
-        padding-right: 6px;
+@media (max-width: 320px) {
+    header #header_center, header #header_right, header #header_left {
+        display:none;
+    }    
+    .navbar {
+      margin-top: 0em;
+    }
+    .navbar .brand {
+         font-size: 14px;
+    }
+    #main_content .span3 #login_block {
+        width: 160px;
+        float: left;
+    }
+    #main_content .span3 #help_block {
+        width: 60px;
+        float: right;
+        margin-left: 10px;
+        margin-right: 10px;
+    }
+    
+    /* No view as link*/
+    #view_as_link {
+        display:none;
+    }
+    /* Smaller brand */
+    .navbar .brand {
+         font-size: 14px;
     }
     
+    /* In order to avoid clicking in the main title instead of the expand button */
+    .subnav .navbar-inner .in{
+        margin-top: 45px;
+    }
+    #main_content .span3 #login_block {
+        width: 180px;
+    }
+    #main_content .span3 #help_block {
+        width: 100px;
+    }
     /* only for the course tools */
-    #course_tools .row > [class*="span"], #course_tools  .row-fluid > [class*="span"] {     
-        float: left;     
+    #course_tools .row > [class*="span"], #course_tools  .row-fluid > [class*="span"] {
+        float: left;
+        margin-left: 20px;
     }
-    #top_main_content .span6 {
-        width: 440px;
+    /* Course- home - Show 2 icons instead of one */
+    .course-tool {
+        float: left;
+        height: 110px;
+        width: 110px;
     }
-    .section-social #top_main_content .span3 {
-        width: 200px;
+
+    .course-tool h4 {
+        font-size: 15px;
+    }
+    /* in admin, reduce block height but increase width (from 47%) as there
+       will be only one for the whole width */
+    #settings .span6 {
+        min-height: none;
+        width: 95%;
+    }
+    .section-mycourses .menu-column, .section-mycampus .menu-column {
+        width: 95%;
+    }
+    .section-mycampus .menu-column #login_block {
+        width: 95%;
+    }
+    .section-mycourses .menu-column #user_image_block, 
+    .section-mycourses .menu-column #profile_block, 
+    .section-mycourses .menu-column #skill_block, 
+    .section-mycourses .menu-column #search_block, 
+    .section-mycourses .menu-column #classes_block, 
+    .section-mycourses .menu-column #reservation_block, 
+    .section-mycourses .menu-column #skill_block, 
+    .section-mycampus .menu-column #help_block, 
+    .section-mycourses .menu-column #notice_block {
+        display: none;
     }
-    #top_main_content #hot_courses .span9 .span6 { 
-        width: 330px;
+    .section-mycampus #homepage {
+        width: 260px;
     }
-    /* Space between course tools */
-    #course_tools .row .span4 {
-        width: 240px;
+    .section-mycampus #hot_courses {
+        width: 260px;
     }
-    #course_tools .row .span4 h4 {
-        font-size: 14px;
+    .section-mycourses #top_main_content {
+        margin-right: 15px;
+    }
+    .section-mycourses #main_content {
+        margin-right: 15px;
+        width: 260px;
+    }
+    .section-mycourses .course-box .course-box-actions {
+        display: none;
+    }
+    .section-mycampus .hot-course-box, .section-mycourses .course-box {
+        width: 95%;
+    }
+    footer {
+        margin-top: 0px;
     }
 }
 
-/* Normal tablet or normal-screen phone */
-@media (max-width: 979px) {
-    /* Remove any padding from the body */
-    body {
-        padding-top: 0;
+@media (min-width: 321px) and (max-width: 480px) {
+    header #header_center, header #header_right, header #header_left {
+        display:none;
+    }
+    .navbar {
+      margin-top: 0em;
+    }
+    .subnav .navbar-inner .in{
+        margin-top: 45px; 
     }
 
-    #topbar_push {
-        height: 0px;
+    /* No chat in mobiles */
+    #chatmain {
+        display:none;
     }
 
     /* No topbar */
     #topbar {
         display:none;
     }
-    
-    /* fixes tabs */
-    .subnav .nav-tabs > li > a, .subnav .nav-pills > li > a {
-        padding-left: 6px;
-        padding-right: 6px;
+
+    /* No view as link*/
+    #view_as_link {
+        display:none;
     }
-    
+
+    /* Brand fix */
+    .navbar .brand {
+         font-size: 14px;
+    }
+
     .subnav .dropdown-toggle {
         display:none;
-    }    
-    
-    .subnav .nav > li > a, .navbar .dropdown-menu a, #main .subnav .dropdown-menu li a {
-        color: #fff;
     }
-    
-   .subnav .nav > li > a:hover,
-   .subnav .dropdown-menu a:hover {
+
+    .subnav .nav > li > a, .navbar .dropdown-menu a {
+        color: white;
+    }
+
+    /* Footer fixes */
+
+    footer {
+        border-top: 1px solid #CCCCCC;
+        background-color: #fff;
+        background-image: none;
+        color: #666;
     }
-    .section-social #top_main_content .span3 {
-        width: 190px;
+
+    footer #footer_left a, footer #footer_center a, footer #footer_right a {
+        color : #999;
     }
-    #top_main_content .span4, #top_main_content .span5 {
-        width: 250px;
-        margin-left: 5px;
+
+    #footer_left , #footer_right #admin_name, #footer_right #software_name {
+        text-align: center !important;
     }
-    #top_main_content .span6 {
-        width: 340px;
+
+    footer .container .row {
+        padding-top: 15px;
     }
-    #top_main_content .span9 {
-        width: 500px;
+
+    /* No resize font */
+    .resize_font {
+        display:none;
     }
-    /* Space between course tools */
-    #course_tools .row .span4 {
-        width: 220px;
+
+    h3 {
+        font-size: 18px;
+    }
+
+    h4 {
+        font-size: 16px;
+    }
+
+    /* No notifications */
+    .notification-panel {
+        display:none;
+    }
+
+    /* only for the course tools */
+    #course_tools .row > [class*="span"], #course_tools  .row-fluid > [class*="span"] {
+        float: left;
+        margin-left: 10px;
+    }
+    /* Course- home - Show 2 icons instead of one */
+    .course-tool {
+        float: left;
+        height: 150px;
+        width: 160px;
+    }
+
+    .course-tool h4 {
+        font-size: 14px;
     }
-    .section-mycourses #top_main_content .span9 #main_content .well .pull-right, .section-mycampus #top_main_content .span9 #hot_courses .pull-right {
+
+    .subbav .nav > li > a:hover,
+    .subbav .dropdown-menu a:hover {
+        background-color: #555;
+    }
+    #main_content .span3 #login_block {
+        width: 280px;
+        float: left;
+    }
+    #main_content .span3 #help_block {
+        width: 100px;
+        float: right;
+        margin-left: 10px;
+        margin-right: 10px;
+    }
+    /* in admin, reduce block height but increase width (from 47%) as there
+       will be only one for the whole width */
+    #settings .span6 {
+        min-height: none;
+        width: 95%;
+    }
+    .section-mycourses .menu-column, .section-mycampus .menu-column {
+        width: 95%;
+    }
+    .section-mycampus .menu-column #login_block {
+        width: 95%;
+    }
+    .section-mycourses .menu-column #user_image_block, 
+    .section-mycourses .menu-column #profile_block, 
+    .section-mycourses .menu-column #skill_block, 
+    .section-mycourses .menu-column #search_block, 
+    .section-mycourses .menu-column #classes_block, 
+    .section-mycourses .menu-column #reservation_block, 
+    .section-mycourses .menu-column #skill_block, 
+    .section-mycampus .menu-column #help_block, 
+    .section-mycourses .menu-column #notice_block {
         display: none;
     }
+    .section-mycampus #homepage {
+        width: 400px;
+    }
+    .section-mycampus #hot_courses {
+        width: 400px;
+    }
+    .section-mycourses #top_main_content {
+        margin-right: 15px;
+    }
+    .section-mycourses #main_content {
+        margin-right: 15px;
+        width: 400px;
+    }
+    .section-mycourses .course-box .course-box-actions {
+        display: none;
+    }
+    .section-mycampus .hot-course-box, .section-mycourses .course-box {
+        width: 95%;
+    }
+    footer {
+        margin-top: 0px;
+    }
 }
 
-@media (max-width: 767px) {
+@media (min-width: 481px) and (max-width: 800px) {
     /* No topbar */
     #topbar {
         display:none;
     }    
+    
+    /* only for the course tools */
+    #course_tools .row > [class*="span"], #course_tools  .row-fluid > [class*="span"] {     
+        float: left;     
+    }
+    .course-tool {
+        width: 210px;
+    }
+    .course-tool h4 {
+        font-size: 14px;
+    }
+    
     .subnav .dropdown-toggle {
         display:none;
     }
@@ -110,7 +305,7 @@
         text-align: center !important;
     }    
     
-    .subnav .nav > li > a, .navbar .dropdown-menu a, #main .subnav .dropdown-menu li a  {
+    .subnav .nav > li > a, .navbar .dropdown-menu a {        
         color: white;
     }
     
@@ -159,7 +354,7 @@
     }
     
     .subnav .navbar-inner li a:hover {
-        background-color: #6B8E23;
+        background-color: #666;
         color: #fff;
     }    
     
@@ -192,39 +387,29 @@
                 border-radius: 4px 4px 0 0;
     }
 
-    .section-social #top_main_content .span3 {
-        width: 170px;
+    #section-social .row > [class*="span"], #section-social .row-fluid > [class*="span"] {     
+        float: left;     
     }
-    .section-social #top_main_content .span4 {
-        width: 200px;
-        margin-left: 5px;
-        float: right;
+    /* Some fixes for w~720px */
+    .section-mycampus #top_main_content .content-column {
+        float: none;
     }
-    .section-social #top_main_content .span5 {
-        width: 240px;
-        margin-left: 5px;
+    .section-mycampus #homepage {
         float: left;
+        width: 450px;
     }
-    #top_main_content .span6 {
-        width: 328px;
+    .section-mycampus #hot_courses {
         float: left;
-        margin-left: 5px;
-    }
-    #top_main_content .span9 {
-        width: 420px;
-        margin-left: 5px;
+        width: 660px;
     }
-    .section-social #top_main_content .span9 {
-        width: 480px;
-        margin-left: 5px;
+    .section-mycampus #hot_courses .page-header {
+        width: 650px;
     }
-    /* Space between course tools */
-    #course_tools .row .span4 {
-        width: 180px;
-        float: left;
+    .section-mycourses .course-box .course-box-actions {
+        display: none;
     }
-    #course_tools .row .span4 h4 {
-        font-size: 14px;
+    .section-mycampus .hot-course-box, .section-mycourses .course-box {
+        width: 660px;
     }
 
     /* Footer fixes */
@@ -249,332 +434,83 @@
     }
 }
 
-/* Intermediary */
-@media (max-width: 680px) {
-    #top_main_content .span9 {
-        width: 320px;
-    }
-    #announcements .bx-prev, #announcements .bx-next {
-        display: none;
-    }
-}
-@media (max-width: 640px) {
-    .section-mycampus #top_main_content .span3 #user_image_block, .section-mycampus #top_main_content .span3 #profile_block,
-    .section-mycourses #top_main_content .span3 #user_image_block, .section-mycourses #top_main_content .span3 #profile_block {
-        margin: 5px;
-        width: 202px;
-        float: left;
-    }
-    .section-mycampus #top_main_content .span3 #course_block, .section-mycampus #top_main_content .span3 #help_block, .section-mycampus #top_main_content .span3 #skill_block,
-    .section-mycourses #top_main_content .span3 #course_block, .section-mycourses #top_main_content .span3 #help_block, .section-mycourses #top_main_content .span3 #skill_block {
-        margin: 5px;
-        width: 202px;
-        float: left;
-    }
-    .section-mycampus #top_main_content .span3 #help_block {
-        width: 202px;
-        float: left;
-        margin: 5px;
-    }
-    #top_main_content .span9 {
-        width: 540px;
-        margin-left: 5px;
-    }
-    #top_main_content #hot_courses .span9 .thumbnail, .section-mycourses #top_main_content .span9 #main_content .thumbnail {
-        width: 80px;
-        float: left;
-    }
-    #top_main_content #hot_courses .span9 .well_border, .section-mycourses #top_main_content .span9 #main_content .well {
-        padding: 8px;
-    }
-    #top_main_content #hot_courses .span9 .span6, .section-mycourses #top_main_content .span9 #main_content .well .span7 .span6 {
-        width: 400px;
-        float: right;
-        min-height: auto;
-    }
-}
-
-/* Small-screen phones, horizontal */
-
-@media (max-width: 480px) {
-    body {
-        padding-left: 6px;
-        padding-right: 6px;
-    }
-    header #header_center, header #header_right, header #header_left {
-        display:none;
-    }    
-    .navbar {
-      margin-top: 1em;
-    }
-    .subnav .navbar-inner .in{
-        margin-top: 45px 
-    }
-    
-    /* No chat in mobiles */
-    #chatmain {
-        display:none;
-    }
-    
+@media (min-width: 801px) and (max-width: 979px) {
     /* No topbar */
     #topbar {
         display:none;
     }
     
-    /* No view as link*/
-    #view_as_link {
-        display:none;
-    }
-    
-    /* Brand fix */
-    .navbar .brand {
-         margin-top: 2px;
-         font-size: 18px;
+    /* fixes tabs */
+    .subnav .nav-tabs > li > a, .subnav .nav-pills > li > a {
+        padding-left: 6px;
+        padding-right: 6px;
     }
     
     .subnav .dropdown-toggle {
         display:none;
-    }
-    
-    .subnav .nav > li > a, .navbar .dropdown-menu a {        
-        color: white;        
-    }
-    
-    /* Footer fixes */
-    
-    footer {
-        border-top: 1px solid #CCCCCC;
-        background-color: #fff;
-        background-image: none;
-        color: #666;
-    }
-    
-    footer #footer_left a, footer #footer_center a, footer #footer_right a {
-        color : #999;
-    }
-    
-    #footer_left , #footer_right #admin_name, #footer_right #software_name {
-        text-align: center !important;
     }    
     
-    footer .container .row {
-        padding-top: 15px;        
-    }
-    
-    /* No resize font */
-    .resize_font {
-        display:none;
+    .subnav .nav > li > a, .navbar .dropdown-menu a {      
+        color: #ccc;        
     }
     
-    h3 {
-        font-size: 18px;
-    }
-    
-    h4 {
-        font-size: 16px;
-    }   
-        
-    /* No notifications */
-    .notification-panel {
-        display:none;
-    }
-    
-    /* Course- home - Show 2 icons instead of one */
-    #course_tools .row .span4 {
-        float: left;        
-        height: 150px;
-        width: 148px;
-    }
-    #course_tools .row .span4 h4 {
-        font-size: 11px;
-    }
-    
-    #course_tools .span12 .page-header {
-        text-align: center;
-    }
-    
-    .subbav .nav > li > a:hover,
-    .subbav .dropdown-menu a:hover {
-        background-color: #555;
-    }
-    /* Improving the login form */
-    #top_main_content .span3 #login_block {
-        width: 190px;
-        float: left;
-        margin-left: 5px;
-        margin-top: 5px;
-    }
-    #top_main_content .span3 #login_block #lang_form {
-        margin-bottom: 4px;
-    }
-    #top_main_content .span3 #login_block #formLogin form {
-        margin-bottom: 8px;
-    }
-    #top_main_content .span3 #login_block #formLogin .control-label{
-        font-weight: bold;
-    }
-    #top_main_content .span3 #login_block ul.nav-list {
-        float: left;
-        width: 120px;
-        margin-top: -40px;
-    }
-    #top_main_content .span3 #login_block .btn {
-        float: right;
-    }
-    /* Improving blocks layout in social network */
-    .section-social #top_main_content .span3 {
-        width: 170px;
-    }
-    .section-social #top_main_content .span4 {
-        width: 200px;
-        margin-left: 5px;
-        float: right;
-    }
-    .section-social #top_main_content .span5 {
-        width: 240px;
-        margin-left: 5px;
-        float: left;
-    }
-    #top_main_content .span6 {
-        width: 400px;
-        /*min-height: 200px;*/
-    }
-    #top_main_content .span9 {
-        width: 400px;
-        margin-left: 5px;
-    }
-    /* Improving blocks layout in my courses and homepage */
-    .section-mycampus #top_main_content.span9 {
-        float: left;
-    }
-    #top_main_content .span9 #announcements .span6 {
-        width: 330px;
-    }
-    #top_main_content #hot_courses .span9 .thumbnail, .section-mycourses #top_main_content .span9 #main_content .thumbnail {
-        width: 80px;
-        float: left;
-    }
-    #top_main_content #hot_courses .span9 .well_border, .section-mycourses #top_main_content .span9 #main_content .well {
-        padding: 8px;
-    }
-    #top_main_content #hot_courses .span9 .span6, .section-mycourses #top_main_content .span9 #main_content .well .span7 .span6 {
-        width: 270px;
-        float: right;
-        min-height: auto;
-    }
-    .section-mycourses #top_main_content .span9 #main_content .well .pull-right, .section-mycampus #top_main_content .span9 #hot_courses .pull-right {
-        display: none;
-    }
-    .section-mycampus #top_main_content .span3, .section-mycourses #top_main_content .span3 {
-        float: left;
-        width: auto;
-        clear: both;
-    }
-    .section-social #top_main_content .span9, .section-mycourses #top_main_content .span9 {
-        width: 480px;
-        margin-left: 5px;
-    }
-    .section-mycampus #top_main_content .span3 #user_image_block, .section-mycampus #top_main_content .span3 #profile_block,
-    .section-mycourses #top_main_content .span3 #user_image_block, .section-mycourses #top_main_content .span3 #profile_block {
-        margin: 5px;
-        width: 192px;
-        float: left;
-    }
-    .section-mycampus #top_main_content .span3 #course_block, .section-mycampus #top_main_content .span3 #help_block, .section-mycampus #top_main_content .span3 #skill_block,
-    .section-mycourses #top_main_content .span3 #course_block, .section-mycourses #top_main_content .span3 #help_block, .section-mycourses #top_main_content .span3 #skill_block {
-        margin: 5px;
-        width: 192px;
-        float: left;
-    }
-    .section-mycampus #top_main_content .span3 #help_block {
-        width: 192px;
-        float: left;
-        margin-left: 5px;
-    }
-    .section-mycampus #top_main_content #homepage {
-        margin-top: 20px;
-    }
-    .section-mycourses #top_main_content .span9 #main_content {
-        width: 420px;
+   .subnav .nav > li > a:hover,
+   .subnav .dropdown-menu a:hover {
     }
-    #top_main_content .page-header h1 {
-        text-align: center;
+    .course-tool {
+        width: 220px;
     }
 }
 
-/* Phone, vertical screen */
-
-@media (max-width: 320px) {    
+@media (max-width: 979px) {
+    /* Remove any padding from the body */
     body {
-        padding-left: 3px;
-        padding-right: 3px;
-    }
-    header #header_center, header #header_right, header #header_left {
-        display:none;
-    }    
-    .navbar {
-      margin-top: 1em;
-    }
-    .navbar .brand {
-         margin-top: 2px;
-         font-size: 14px;
-    }
-    #top_main_content .span3 #login_block {
-        width: 160px;
-        float: left;
+        padding-top: 0;
     }
-    #top_main_content .span3 #help_block {
-        width: 60px;
-        float: right;
-        margin-left: 10px;
-        margin-right: 10px;
+
+    #topbar_push {
+        height: 0px;
     }
-    
-    /* No view as link*/
-    #view_as_link {
-        display:none;
+    .section-social .span9 {
+        width: 530px;
     }
-    
-    /* Smaller brand */
-    .navbar .brand {
-         font-size: 14px;
+}
+
+@media (min-width: 980px) and (max-width: 1200px) {
+    /* fixes tabs */
+    .subnav .nav-tabs > li > a, .subnav .nav-pills > li > a {
+        padding-left: 6px;
+        padding-right: 6px;
     }
     
-    /* In order to avoid clicking in the main title instead of the expand button */
-    .subnav .navbar-inner .in{
-        margin-top: 45px 
+    /* only for the course tools */
+    #course_tools .row > [class*="span"], #course_tools  .row-fluid > [class*="span"] {     
+        float: left;     
     }
-    #top_main_content .span9 {
-        width: 290px;
-        margin: 0;
+    .course-tool {
+        width: 280px;
     }
-    #top_main_content .span3 #login_block {
-        width: 190px;
+    .section-social .span9, .section-mycourses .span9{
+        width: 680px;
     }
-    #top_main_content .span3 #help_block {
-        width: 100px;
+    .section-social .social-menu {
+        width: 200px;
     }
-/*
-    .section-mycourses #top_main_content .span9 #main_content {
-        width: 290px;
+    .section-social .span5 {
+        width: 350px;
     }
-*/
-    #top_main_content #hot_courses .span9 .span6, .section-mycourses #top_main_content .span9 #main_content .well .span7 .span6 {
-        width: 150px;
+}
+
+/* LARGE DESKTOP SCREENS */
+@media (min-width: 1201px) {
+    #top_main_content .span12 {
+      width: 98%;
     }
-    #top_main_content #hot_courses .span9 .span6 .btn {
+    /* only for the course tools */
+    #course_tools .row > [class*="span"], #course_tools  .row-fluid > [class*="span"] {
         float: left;
-        margin-top: 5px;
-    }
-    #top_main_content #hot_courses .vote_label_info {
-        display: none;
     }
-    #course_tools .row .span4 {
-        width: 120px;
+    .course-tool {
+        width: 260px;
     }
 }
-
-
-
-
-

BIN
main/css/student.png


BIN
main/css/teacher.png


+ 46 - 44
main/document/document.php

@@ -106,8 +106,8 @@ if (api_get_session_id() != 0) {
     $group_member_with_upload_rights = $group_member_with_upload_rights && api_is_allowed_to_session_edit(false, true);
 }
 
-//Setting group variables 
-if (api_get_group_id()) {        
+//Setting group variables
+if (api_get_group_id()) {
     // Get group info
     $group_properties = GroupManager::get_group_properties(api_get_group_id());
     $noPHP_SELF = true;
@@ -117,17 +117,17 @@ if (api_get_group_id()) {
     if ($group_properties['doc_state'] == 2) {
         // Documents are private
         if ($is_allowed_to_edit || GroupManager :: is_user_in_group(api_get_user_id(), api_get_group_id())) {
-            // Only courseadmin or group members (members + tutors) allowed            
+            // Only courseadmin or group members (members + tutors) allowed
             $interbreadcrumb[] = array('url' => '../group/group.php', 'name' => get_lang('Groups'));
             $interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq=' . api_get_group_id(), 'name' => get_lang('GroupSpace') . ' ' . $group_properties['name']);
             //they are allowed to upload
             $group_member_with_upload_rights = true;
         } else {
-            $to_group_id = 0;            
+            $to_group_id = 0;
         }
     } elseif ($group_properties['doc_state'] == 1) {
         // Documents are public
-        $to_group_id = api_get_group_id();        
+        $to_group_id = api_get_group_id();
         $interbreadcrumb[] = array('url' => '../group/group.php', 'name' => get_lang('Groups'));
         $interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq=' . api_get_group_id(), 'name' => get_lang('GroupSpace') . ' ' . $group_properties['name']);
         //allowed to upload?
@@ -136,12 +136,12 @@ if (api_get_group_id()) {
             $group_member_with_upload_rights = true;
         }
     } else { // Documents not active for this group
-        $to_group_id = 0;        
+        $to_group_id = 0;
     }
     $_SESSION['group_member_with_upload_rights'] = $group_member_with_upload_rights;
 } else {
     $_SESSION['group_member_with_upload_rights'] = false;
-    $to_group_id = 0;    
+    $to_group_id = 0;
 }
 
 //Actions
@@ -194,7 +194,7 @@ switch ($action) {
         }
         break;
     case 'copytomyfiles':
-        // Copy a file to general my files user's        
+        // Copy a file to general my files user's
         if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('users_copy_files') == 'true' && api_get_user_id() != 0 && !api_is_anonymous()) {
             $document_info = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id(), true);
             $parent_id = $document_info['parent_id'];
@@ -236,7 +236,7 @@ switch ($action) {
                 if (!copy($file, $copyfile)) {
                     $message = Display::return_message(get_lang('CopyFailed'), 'error');
                 } else {
-                    $message = Display::return_message(get_lang('CopyMade') . ' ' . $file_link, 'confirmation', false);                    
+                    $message = Display::return_message(get_lang('CopyMade') . ' ' . $file_link, 'confirmation', false);
                 }
             }
         }
@@ -249,7 +249,7 @@ if (isset($_REQUEST['certificate']) && $_REQUEST['certificate'] == 'true') {
     $is_certificate_mode = true;
 }
 
-//If no actions we proceed to show the document (Hack in order to use document.php?id=X) 
+//If no actions we proceed to show the document (Hack in order to use document.php?id=X)
 if (isset($document_id) && empty($action)) {
     $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), true);
 
@@ -282,9 +282,9 @@ if (isset($document_id) && empty($action)) {
         $curdirpath = Security::remove_XSS($_POST['curdirpath']);
     } else {
         $curdirpath = '/';
-    }    
+    }
 
-    $curdirpathurl = urlencode($curdirpath);    
+    $curdirpathurl = urlencode($curdirpath);
 } else {
     // What's the current path?
     // We will verify this a bit further down
@@ -296,7 +296,7 @@ if (isset($document_id) && empty($action)) {
         $curdirpath = '/';
     }
 
-	
+
     $curdirpathurl = urlencode($curdirpath);
 
     // Check the path
@@ -324,21 +324,21 @@ $current_folder_id = $document_id;
 // Show preview
 if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && isset($_GET['set_preview']) && $_GET['set_preview'] == strval(intval($_GET['set_preview']))) {
     if (isset($_GET['set_preview'])) {
-        // Generate document HTML        
+        // Generate document HTML
         $content_html = DocumentManager::replace_user_info_into_html(api_get_user_id(), api_get_course_id(), true);
-        
+
         $filename = 'certificate_preview/'.api_get_unique_id().'.png';
         $qr_code_filename = api_get_path(SYS_ARCHIVE_PATH).$filename;
-        
+
         $temp_folder = api_get_path(SYS_ARCHIVE_PATH).'certificate_preview';
         if (!is_dir($temp_folder)) mkdir($temp_folder, api_get_permissions_for_new_directories());
-                    
+
         $qr_code_web_filename = api_get_path(WEB_ARCHIVE_PATH).$filename;
-                
+
         $certificate = new Certificate();
-        $text = $certificate->parse_certificate_variables($content_html['variables']);                                        
+        $text = $certificate->parse_certificate_variables($content_html['variables']);
         $result = $certificate->generate_qr($text, $qr_code_filename);
-                                
+
         $new_content_html = $content_html['content'];
         $path_image = api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/images/gallery';
         $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
@@ -346,9 +346,9 @@ if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && isse
         $path_image_in_default_course = api_get_path(WEB_CODE_PATH) . 'default_course_document';
         $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
         $new_content_html = str_replace('/main/img/', api_get_path(WEB_IMG_PATH), $new_content_html);
-        
+
         Display::display_reduced_header();
-        
+
         echo '<style>body {background:none;}</style><style media="print" type="text/css"> #print_div { visibility:hidden; } </style>';
         echo '<a href="javascript:window.print();" style="float:right; padding:4px;" id="print_div"><img src="../img/printmgr.gif" alt="'.get_lang('Print').'"/>'.get_lang('Print').'</a>';
         if (is_file($qr_code_filename) && is_readable($qr_code_filename)) {
@@ -516,9 +516,9 @@ if (!empty($docs_and_folders))
     }
 
 $htmlHeadXtra[] = '<script>
-$(document).ready( function() {        
-    //Experimental changes to preview mp3, ogg files        
-     ' . $jquery . '            
+$(document).ready( function() {
+    //Experimental changes to preview mp3, ogg files
+     ' . $jquery . '
 });
 </script>';
 
@@ -601,7 +601,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
             }
         }
         $document_to_move = DocumentManager::get_document_data_by_id($_POST['move_file'], api_get_course_id());
-        
+
         // Security fix: make sure they can't move files that are not in the document table
         if (!empty($document_to_move)) {
 
@@ -658,10 +658,10 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
                 api_not_allowed();
             }
         }
-        
+
         $document_data = DocumentManager::get_document_id($_course, $_GET['delete']);
         // Check whether the document is in the database
-        if (!empty($document_data)) {         
+        if (!empty($document_data)) {
             if (DocumentManager::delete_document($_course, $_GET['delete'], $base_work_dir)) {
                 if (isset($_GET['delete_certificate_id']) && $_GET['delete_certificate_id'] == strval(intval($_GET['delete_certificate_id']))) {
                     $default_certificate_id = $_GET['delete_certificate_id'];
@@ -709,7 +709,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
     // Create directory with $_POST data
 
     if (isset($_POST['create_dir']) && $_POST['dirname'] != '') {
-        // Needed for directory creation        
+        // Needed for directory creation
         $post_dir_name = $_POST['dirname'];
 
         if ($post_dir_name == '../' || $post_dir_name == '.' || $post_dir_name == '..') {
@@ -808,7 +808,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         $document_id_for_template = intval(Database::escape_string($_GET['add_as_template']));
 
         $title = Security::remove_XSS($_POST['template_title']);
-        //$description = Security::remove_XSS($_POST['template_description']);        
+        //$description = Security::remove_XSS($_POST['template_description']);
         $user_id = api_get_user_id();
 
         // Create the template_thumbnails folder in the upload folder (if needed)
@@ -943,15 +943,15 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
             <?php
         }
 
-		
+
 		// Record an image clip from my webcam
 		if (api_get_setting('enable_webcam_clip') == 'true') {
 		?>
 			<a href="webcam_clip.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
 		   	<?php Display::display_icon('webcam.png', get_lang('WebCamClip'),'',ICON_SIZE_MEDIUM); ?></a>
 		<?php
-		}	
-		
+		}
+
 		// Record audio (nanogong)
         if (api_get_setting('enable_nanogong') == 'true') {
             ?>
@@ -1026,7 +1026,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         // 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'];
 
-        // Get the title or the basename depending on what we're using        
+        // Get the title or the basename depending on what we're using
         if ($document_data['title'] != '') {
             $document_name = $document_data['title'];
         } else {
@@ -1037,7 +1037,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         if (($is_allowed_to_edit || $group_member_with_upload_rights) && count($docs_and_folders) > 1) {
             $row[] = $document_data['path'];
         }
-        
+
         if (DocumentManager::is_folder_to_avoid($document_data['path'], $is_certificate_mode)) {
             continue;
         }
@@ -1065,7 +1065,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         // Validacion when belongs to a session
         $session_img = api_get_session_image($document_data['session_id'], $_user['status']);
 
-        // Document title with link        
+        // Document title with link
         $row[] = create_document_link($document_data, false, null, $is_visible) . $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
@@ -1073,15 +1073,15 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         $row[] = '<span style="display:none;">'.$size.'</span>'.$invisibility_span_open.$display_size.$invisibility_span_close;
 
         // Last edit date
-        
-        $last_edit_date = api_get_local_time($document_data['lastedit_date']);      
+
+        $last_edit_date = api_get_local_time($document_data['lastedit_date']);
         $display_date = date_to_str_ago($last_edit_date).' <div class="muted"><small>'.$last_edit_date."</small></div>";
         $row[] = $invisibility_span_open.$display_date.$invisibility_span_close;
         // Admins get an edit column
 
         if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)) {
             $is_template = isset($document_data['is_template']) ? $document_data['is_template'] : false;
-            // If readonly, check if it the owner of the file or if the user is an admin            
+            // If readonly, check if it the owner of the file or if the user is an admin
             if ($document_data['insert_user_id'] == api_get_user_id() || api_is_platform_admin()) {
                 $edit_icons = build_edit_icons($document_data, $key, $is_template, 0, $is_visible);
             } else {
@@ -1092,7 +1092,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         $row[] = $last_edit_date;
         $row[] = $size;
         $row[] = $document_name;
-        
+
         $total_size = $total_size + $size;
 
         if ((isset($_GET['keyword']) && search_keyword($document_name, $_GET['keyword'])) || !isset($_GET['keyword']) || empty($_GET['keyword'])) {
@@ -1133,7 +1133,9 @@ echo '</div>'; //end actions
 if (isset($message)) {
     echo $message;
 }
-
+if (isset($_POST['move_to'])) {
+    $document_id = DocumentManager::get_document_id($course_info, $_POST['move_to']);
+}
 if (!$is_certificate_mode) {
     echo build_directory_selector($folders, $document_id, (isset($group_properties['directory']) ? $group_properties['directory'] : array()), true);
 }
@@ -1222,9 +1224,9 @@ if (count($docs_and_folders) > 1) {
 
         // Calculating the total space
         $already_consumed_space_course = DocumentManager::documents_total_space(api_get_course_int_id());
-        
-        // Displaying the quota        
-        DocumentManager::display_simple_quota($course_quota, $already_consumed_space_course);        
+
+        // Displaying the quota
+        DocumentManager::display_simple_quota($course_quota, $already_consumed_space_course);
     }
 }
 if (!empty($table_footer)) {

+ 22 - 15
main/document/download.php

@@ -65,22 +65,29 @@ if (substr($refer_script, 0, 15) == '/fillsurvey.php') {
 	}	
 }
 
-if (Security::check_abs_path($sys_course_path.$doc_url, $sys_course_path.'/')) {
-    $full_file_name = $sys_course_path.$doc_url;
-    // Check visibility of document and paths    doc_url
-    //var_dump($document_id, api_get_course_id(), api_get_session_id(), api_get_user_id());
-    $is_visible = false;
-    //$course_info   = api_get_course_info(api_get_course_id());
-    //$document_id = DocumentManager::get_document_id($course_info, $doc_url);
+        
+//Fixes swf upload problem in chamilo 1.8.x. When uploading a file with 
+//the character "-" the filename was changed from "-" to "_" in the DB for no reason
+$path_info = pathinfo($doc_url);
 
-    //HotPotatoes_files
-    //if ($document_id) {
-    	// Correct choice for strict security (only show if whole tree visible)
-        //$is_visible = DocumentManager::check_visibility_tree($document_id, api_get_course_id(), api_get_session_id(), api_get_user_id());
-        // Correct choice for usability
-    	$is_visible = DocumentManager::is_visible($doc_url, $_course, api_get_session_id());
-    //}
-	
+$fix_file_name = false;
+if (isset($path_info['extension']) && $path_info['extension'] == 'swf') {
+    $fixed_url = str_replace('-', '_', $doc_url);
+    $doc_id = DocumentManager::get_document_id(api_get_course_info(), $doc_url);
+    if (!$doc_id) {
+        $fix_file_name = true;
+    }
+}
+
+
+if (Security::check_abs_path($sys_course_path.$doc_url, $sys_course_path.'/')) {
+    $full_file_name = $sys_course_path.$doc_url;    
+    if ($fix_file_name) {
+        $doc_url = $fixed_url;
+    }
+    // Check visibility of document and paths
+    $is_visible = DocumentManager::is_visible($doc_url, $_course, api_get_session_id());
+    
 	//Documents' slideshow thumbnails
 	//correct $is_visible used in below and ??. Now the students can view the thumbnails too
 	if ( preg_match('/\.thumbs\/\./',  $doc_url)){ 

+ 51 - 61
main/dropbox/dropbox_class.inc.php

@@ -282,33 +282,30 @@ class Dropbox_SentWork extends Dropbox_Work
 
         $table_post = $dropbox_cnf['tbl_post'];
         $table_person = $dropbox_cnf['tbl_person'];
-        $session_id = intval($_SESSION['id_session']);
+        $session_id = api_get_session_id();
         $uploader_id = $this->uploader_id;
 		// Insert data in dropbox_post and dropbox_person table for each recipient
 		foreach ($this->recipients as $rec) {
             $file_id = (int)$this->id;
             $user_id = (int)$rec['id'];            
-			$sql = "INSERT INTO $table_post 
-                        (c_id, file_id, dest_user_id, session_id) 
-                    VALUES 
-                        ($course_id, $file_id, $user_id, $session_id)";
-	        $result = Database::query($sql);	// If work already exists no error is generated
+			$sql = "INSERT INTO $table_post (c_id, file_id, dest_user_id, session_id) 
+                    VALUES ($course_id, $file_id, $user_id, $session_id)";
+	        $result = Database::query($sql);	
+            // If work already exists no error is generated
 
             /**
              * Poster is already added when work is created - not so good to split logic 
              */
-            if($user_id != $user_id){
+            //if ($user_id != $user_id) {
                 // Insert entries into person table
-                $sql = "INSERT INTO $table_person 
-                            (c_id, file_id, user_id)
-                        VALUES 
-                            ($course_id, $file_id, $user_id)";
+                $sql = "INSERT INTO $table_person (c_id, file_id, user_id)
+                        VALUES ($course_id, $file_id, $user_id)";
 
                 // Do not add recipient in person table if mailing zip or just upload.
                 if (!$justSubmit) {
                     $result = Database::query($sql);	// If work already exists no error is generated
                 }
-            }
+            //}
 
 			// Update item_property table for each recipient
 			global $_course, $dropbox_cnf;
@@ -329,31 +326,35 @@ class Dropbox_SentWork extends Dropbox_Work
 	 */
 	function _createExistingSentWork ($id) {
 		global $dropbox_cnf;
+        
+        $id = intval($id);
 		
 		$course_id = api_get_course_int_id(); 
 
 		// Call constructor of Dropbox_Work object
 		$this->Dropbox_Work($id);
 
-		// Do sanity check. The sanity check for ex-coursemembers is already done in base constructor
-		settype($id, 'integer') or die(get_lang('GeneralError').' (code 211)'); // Set $id to correct type
-
 		// Fill in recipients array
 		$this->recipients = array();
 		$sql = "SELECT dest_user_id, feedback_date, feedback
 				FROM ".$dropbox_cnf['tbl_post']."
 				WHERE c_id = $course_id AND file_id='".Database::escape_string($id)."'";
         $result = Database::query($sql);
-		while ($res = Database::fetch_array($result)) {
+		while ($res = Database::fetch_array($result, 'ASSOC')) {
+            
 			// Check for deleted users
 			$dest_user_id = $res['dest_user_id'];
-			$recipientName = getUserNameFromId($dest_user_id);
+			$user_info = api_get_user_info($dest_user_id);
 			//$this->category = $res['cat_id'];
-			if (!$recipientName) {
+			if (!$user_info) {
 				$this->recipients[] = array('id' => -1, 'name' => get_lang('Unknown', ''));
 			} else {
-				$this->recipients[] = array('id' => $dest_user_id, 'name' => $recipientName, 'user_id' => $dest_user_id,
-				    'feedback_date' => $res['feedback_date'], 'feedback' => $res['feedback']);
+				$this->recipients[] = array(
+                    'id' => $dest_user_id, 
+                    'name' => $user_info['complete_name'], 
+                    'user_id' => $dest_user_id,
+				    'feedback_date' => $res['feedback_date'], 
+                    'feedback' => $res['feedback']);
 			}
 		}
 	}
@@ -373,64 +374,53 @@ class Dropbox_Person
 	/**
 	 * Constructor for recreating the Dropbox_Person object
 	 *
-	 * @param unknown_type $userId
-	 * @param unknown_type $isCourseAdmin
-	 * @param unknown_type $isCourseTutor
+	 * @param int $userId
+	 * @param bool $isCourseAdmin
+	 * @param bool $isCourseTutor
 	 * @return Dropbox_Person
 	 */
-	function Dropbox_Person ($userId, $isCourseAdmin, $isCourseTutor) {
+	function Dropbox_Person($userId, $isCourseAdmin, $isCourseTutor) {
 	    $course_id = api_get_course_int_id(); 
         
 		// Fill in properties
-		$this->userId = $userId;
-		$this->isCourseAdmin = $isCourseAdmin;
-		$this->isCourseTutor = $isCourseTutor;
-		$this->receivedWork = array();
-		$this->sentWork = array();
+		$this->userId           = $userId;
+		$this->isCourseAdmin    = $isCourseAdmin;
+		$this->isCourseTutor    = $isCourseTutor;
+		$this->receivedWork     = array();
+		$this->sentWork         = array();
 
 		// Note: perhaps include an ex coursemember check to delete old files
 
 		$session_id = api_get_session_id();
 		$condition_session = api_get_session_condition($session_id);
-		$course_id = api_get_course_int_id();
-		
+				
 		$post_tbl = Database::get_course_table(TABLE_DROPBOX_POST);
 		$person_tbl = Database::get_course_table(TABLE_DROPBOX_PERSON);
 		$file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
-		// Find all entries where this person is the recipient
-		 $sql = "SELECT r.file_id, r.cat_id FROM $post_tbl r, $person_tbl p ".
-			" WHERE ".
-			" r.c_id = $course_id AND ".
-			" p.c_id = $course_id AND ". 
-			" r.dest_user_id = ".intval($this->userId)." AND ".
-		 	" r.file_id      = p.file_id $condition_session AND ".
-		 	" r.c_id = $course_id AND ".
-		 	" p.c_id = $course_id ";
-
-		//if (intval($_SESSION['id_session']>0)) { $sql .= " AND r.session_id = ".intval($_SESSION['id_session']); }
-
+               
+        // Find all entries where this person is the recipient
+		$sql = "SELECT DISTINCT r.file_id, r.cat_id 
+                FROM $post_tbl r INNER JOIN $person_tbl p 
+                    ON (r.file_id = p.file_id AND r.c_id = $course_id AND p.c_id = $course_id )
+                WHERE
+                     p.user_id = ".intval($this->userId)." AND
+                     r.dest_user_id = ".intval($this->userId)." $condition_session ";
+        
         $result = Database::query($sql);
 		while ($res = Database::fetch_array($result)) {
 			$temp = new Dropbox_Work($res['file_id']);
-			$temp -> category = $res['cat_id'];
+			$temp->category = $res['cat_id'];
 			$this->receivedWork[] = $temp;
-		}
-
+		}        
 		// Find all entries where this person is the sender/uploader
-		$sql = "SELECT f.id
-				FROM $file_tbl f, $person_tbl p
-				WHERE 
-				f.c_id = $course_id AND
-                p.c_id = $course_id AND
-				f.uploader_id 	= '".Database::escape_string($this->userId)."' AND 
-				f.uploader_id 	= p.user_id AND 
-				f.id 			= p.file_id $condition_session AND
-				f.c_id 			= $course_id AND
-		 		p.c_id 			= $course_id				 
-		";
-
-		//if(intval($_SESSION['id_session']>0)) { $sql .= " AND f.session_id = ".intval($_SESSION['id_session']); }
-
+        $sql = "SELECT DISTINCT f.id
+				FROM $file_tbl f INNER JOIN $person_tbl p
+				ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
+                WHERE 
+                    f.uploader_id 	= '".Database::escape_string($this->userId)."' AND 
+                    p.user_id       = '".Database::escape_string($this->userId)."'            
+                    $condition_session
+                ";
         $result = Database::query($sql);
 		while ($res = Database::fetch_array($result)) {
 			$this->sentWork[] = new Dropbox_SentWork($res['id']);
@@ -583,7 +573,7 @@ class Dropbox_Person
 			}
 		}
 		// Delete entries in person table concerning received works
-        $sql = "DELETE FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND user_id='".$this->userId."' AND file_id='".$id."'";        
+        $sql = "DELETE FROM ".$dropbox_cnf['tbl_person']." WHERE c_id = $course_id AND user_id = '".$this->userId."' AND file_id ='".$id."'";        
 		Database::query($sql);
 		removeUnusedFiles();	// Check for unused files
 	}

+ 12 - 19
main/dropbox/dropbox_functions.inc.php

@@ -522,20 +522,8 @@ function display_add_form() {
     	}
     	$complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
     }
-
-	?>
-
-    <select name="recipients[]" size="
-	<?php
-	if ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) {
-		echo 10;
-	} else {
-		echo 6;
-	}
-
-	?>" multiple style="width: 350px;">
-	<?php
-
+    
+    echo '<select name="recipients[]" size="10" multiple class="span4">';	
 	/*
 		Create the options inside the select box:
 		List all selected users their user id as value and a name string as display
@@ -658,15 +646,17 @@ function removeUnusedFiles() {
     $sql = "SELECT DISTINCT f.id, f.filename
 			FROM " . dropbox_cnf('tbl_file') . " f
 			LEFT JOIN " . dropbox_cnf('tbl_person') . " p 
-            ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id )
-			WHERE p.user_id IS NULL";
+            ON (f.id = p.file_id)
+			WHERE p.user_id IS NULL AND
+                  f.c_id = $course_id 
+            ";
     $result = Database::query($sql);
     while ($res = Database::fetch_array($result)) {
         
 		//delete the selected files from the post and file tables
-        $sql = "DELETE FROM " . dropbox_cnf('tbl_post') . " WHERE c_id = $course_id AND file_id='" . $res['id'] . "'";
+        $sql = "DELETE FROM " . dropbox_cnf('tbl_post') . " WHERE c_id = $course_id AND file_id = '" . $res['id'] . "'";
         Database::query($sql);
-        $sql = "DELETE FROM " . dropbox_cnf('tbl_file') . " WHERE c_id = $course_id AND id='" . $res['id'] . "'";
+        $sql = "DELETE FROM " . dropbox_cnf('tbl_file') . " WHERE c_id = $course_id AND id ='" . $res['id'] . "'";
         Database::query($sql);
 
 		//delete file from server
@@ -694,7 +684,10 @@ function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '') {
     $sql = "SELECT f.uploader_id
 			FROM " . $dropbox_cnf['tbl_file'] . " f
 			LEFT JOIN " . $dropbox_cnf['tbl_post'] . " p ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
-			WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
+			WHERE 
+                p.dest_user_id = '" . $mailingPseudoId . "' AND 
+                p.c_id = $course_id 
+            ";
     $result = Database::query($sql);
 
     if (!($res = Database::fetch_array($result)))

+ 7 - 3
main/dropbox/dropbox_init.inc.php

@@ -54,6 +54,7 @@ require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 // protecting the script
 api_protect_course_script();
 
+
 /*	Libraries */
 
 // including the library for the sortable table
@@ -71,12 +72,15 @@ require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 /*	Virtual course support */
 
 $user_id = api_get_user_id();
-$course_code = $_course['sysCode'];
+$course_code = api_get_course_id();
 $course_info = Database::get_course_info($course_code);
 
 $session_id = api_get_session_id();
-$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_code,$session_id);
-
+if (empty($session_id)) {
+    $is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code, false);
+} else {
+    $is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code, true, $session_id);
+}
 
 /*	Object Initialisation */
 

+ 0 - 32
main/dropbox/dropbox_submit.php

@@ -10,47 +10,15 @@
  * behaviours with POST requests.
  */
 
-/*
-if (isset($_POST['dropbox_unid'])) {
-	$dropbox_unid = $_POST['dropbox_unid'];
-} elseif (isset($_GET['dropbox_unid'])) {
-	$dropbox_unid = $_GET['dropbox_unid'];
-} else {
-	die(get_lang('BadFormData').' (code 400)');
-}
-
-if (isset($_SESSION['dropbox_uniqueid']) && isset($_GET['dropbox_unid']) && $dropbox_unid == $_SESSION['dropbox_uniqueid']) {
-	//resubmit : go to index.php
-	// only prevent resending of data for GETS, not POSTS because this gives annoying results
-
-	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
-		$mypath = 'https';
-	} else {
-		$mypath = 'http';
-	}
-	$mypath = $mypath.'://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/index.php';
-
-    header("Location: $mypath");
-}
-
-$dropbox_uniqueid = $dropbox_unid;
-
-api_session_register('dropbox_uniqueid');
-*/
-
-
 /**
  * FORM SUBMIT
  * - VALIDATE POSTED DATA
  * - UPLOAD NEW FILE
  */
 if (isset($_POST['submitWork'])) {
-
     require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
-
     $error = false;
     $errormsg = '';
-
     /**
      * FORM SUBMIT : VALIDATE POSTED DATA
      */

+ 12 - 18
main/dropbox/index.php

@@ -204,7 +204,7 @@ if (($action == 'deletereceivedfile' OR $action == 'deletesentfile') AND isset($
 	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
 		api_not_allowed();
 	}
-	$dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
+	$dropboxfile = new Dropbox_Person(api_get_user_id(), $is_courseAdmin, $is_courseTutor);
 	if ($action == 'deletereceivedfile') {
 		$dropboxfile->deleteReceivedWork($_GET['id']);
 		$message = get_lang('ReceivedFileDeleted');
@@ -309,9 +309,7 @@ if ($action != 'add') {
 		}
 	}
 
-	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
-		//echo '<h3>'.get_lang('SentFiles').'</h3>';
-
+	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {		
 		// This is for the categories
 		if (isset($_GET['view_sent_category']) AND $_GET['view_sent_category'] != '') {
 			$view_dropbox_category_sent = $_GET['view_sent_category'];
@@ -367,9 +365,7 @@ if ($action != 'add') {
 
 	/*	RECEIVED FILES */
 
-	if ($_GET['view'] == 'received' OR !$dropbox_cnf['sent_received_tabs']) {
-		//echo '<h3>'.get_lang('ReceivedFiles').'</h3>';
-
+	if ($_GET['view'] == 'received' OR !$dropbox_cnf['sent_received_tabs']) {		
 		// This is for the categories
 		if (isset($_GET['view_received_category']) AND $_GET['view_received_category'] != '') {
 			$view_dropbox_category_received = $_GET['view_received_category'];
@@ -378,7 +374,7 @@ if ($action != 'add') {
 		}
 
 		// Object initialisation
-		$dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor); // note: are the $is_courseAdmin and $is_courseTutor parameters needed????
+		$dropbox_person = new Dropbox_Person(api_get_user_id(), $is_courseAdmin, $is_courseTutor); // note: are the $is_courseAdmin and $is_courseTutor parameters needed????
 
 		// Constructing the array that contains the total number of feedback messages per document.
 		$number_feedback = get_total_number_feedback();
@@ -431,7 +427,8 @@ if ($action != 'add') {
 		// The content of the sortable table = the received files
 		foreach ($dropbox_person -> receivedWork as $dropbox_file) {
 			$dropbox_file_data = array();
-			if ($view_dropbox_category_received == $dropbox_file->category) { // we only display the files that are in the category that we are in.
+			if ($view_dropbox_category_received == $dropbox_file->category) {
+                // we only display the files that are in the category that we are in.
 				$dropbox_file_data[] = $dropbox_file->id;
 
 				if (!is_array($_SESSION['_seen'][$_course['id']][TOOL_DROPBOX])) {
@@ -458,9 +455,9 @@ if ($action != 'add') {
 				$action_icons = check_number_feedback($dropbox_file->id, $number_feedback).' '.get_lang('Feedback').'
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('discuss.png', get_lang('Comment'),'',ICON_SIZE_SMALL).'</a>
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=movereceived&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>
-									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletereceivedfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
-				//$action_icons='	<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$_GET['view_received_category'].'&amp;view_sent_category='.$_GET['view_sent_category'].'&amp;action=movereceived&amp;move_id='.$dropbox_file->id.'">'.Display::return_icon('deplacer.gif',get_lang('Move')).'</a>
-				//					<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.$_GET['view_received_category'].'&amp;view_sent_category='.$_GET['view_sent_category'].'&amp;action=deletereceivedfile&amp;id='.$dropbox_file->id.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
+									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletereceivedfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.
+                                    Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
+				
 				// This is a hack to have an additional row in a sortable table
 
 				if ($action == 'viewfeedback' AND isset($_GET['id']) and is_numeric($_GET['id']) AND $dropbox_file->id == $_GET['id']) {
@@ -519,9 +516,7 @@ if ($action != 'add') {
 
 	/*	SENT FILES */
 
-	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
-		//echo '<h3>'.get_lang('SentFiles').'</h3>';
-
+	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {		
 		// This is for the categories
 		if (isset($_GET['view_sent_category']) AND $_GET['view_sent_category'] != '') {
 			$view_dropbox_category_sent = $_GET['view_sent_category'];
@@ -530,8 +525,8 @@ if ($action != 'add') {
 		}
 
 		// Object initialisation
-		$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-
+		$dropbox_person = new Dropbox_Person(api_get_user_id(), $is_courseAdmin, $is_courseTutor);
+        
 		// Constructing the array that contains the total number of feedback messages per document.
 		$number_feedback = get_total_number_feedback();
 
@@ -604,7 +599,6 @@ if ($action != 'add') {
 				//$dropbox_file_data[] = $dropbox_file->author;
 				$receivers_celldata = '';
 
-
 				$action_icons = check_number_feedback($dropbox_file->id, $number_feedback).' '.get_lang('Feedback').'
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('discuss.png', get_lang('Comment'),'',ICON_SIZE_SMALL).'</a>
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=movesent&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>

+ 52 - 0
main/dropbox/recover_dropbox_files.php

@@ -0,0 +1,52 @@
+<?php
+
+require_once 'dropbox_init.inc.php';
+
+$file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
+$person_tbl = Database::get_course_table(TABLE_DROPBOX_PERSON);
+$course_id = api_get_course_int_id();
+$user_id = api_get_user_id();
+$session_id = api_get_session_id();
+
+if (empty($course_id)) {
+    api_not_allowed();
+}
+
+if (!api_is_allowed_to_session_edit(false, true)) {
+    api_not_allowed();
+}
+
+echo Display::page_subheader(get_lang('RecoverDropboxFiles'));
+if (isset($_GET['recover_id']) && !empty($_GET['recover_id'])) {
+    $recover_id = intval($_GET['recover_id']);
+    
+    $sql = "INSERT INTO $person_tbl VALUES('$course_id', $recover_id, $user_id)";
+    $result = Database::query($sql);
+    if ($result) {    
+        Display::display_confirmation_message(get_lang('Recovered'));
+    }
+}
+
+$sql = "SELECT * FROM $file_tbl WHERE c_id = $course_id AND session_id = $session_id";
+$result = Database::query($sql);
+
+if (Database::num_rows($result)) {
+    $files  = Database::store_result($result);
+    $rows = array();
+    foreach ($files as $file) {
+        //Check if I have this file:
+        $sql = "SELECT * FROM $person_tbl WHERE c_id = $course_id AND user_id = $user_id AND file_id = {$file['id']}";
+        $result_person = Database::query($sql);
+        if (Database::num_rows($result_person) == 0 ) {
+        
+            $rows[] = array(
+                    $file['filename'], 
+                    api_convert_and_format_date($file['upload_date']),
+                    Display::url(get_lang('Recover'), api_get_self().'?recover_id='.$file['id'], array('class' => 'btn'))
+            );
+        }
+    }
+    $headers = array(get_lang('Filename'), get_lang('UploadedDate'), get_lang('Action'));
+    echo Display::table($headers, $rows);
+}
+Display::display_footer();

+ 4 - 14
main/exercice/admin.php

@@ -437,18 +437,8 @@ function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
 
 Display::display_header($nameTools, 'Exercise');
 
-$course_id = api_get_course_int_id();
-
-$show_quiz_edition = true;
-if (isset($exerciseId) && !empty($exerciseId)) {
-    $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
-    $sql = "SELECT max_score FROM $TBL_LP_ITEM
-		  WHERE c_id = $course_id AND item_type = '" . TOOL_QUIZ . "' AND path ='" . Database::escape_string($exerciseId) . "'";
-    $result = Database::query($sql);
-    if (Database::num_rows($result) > 0) {
+if ($objExercise->edit_exercise_in_lp == false) {
         Display::display_warning_message(get_lang('EditingExerciseCauseProblemsInLP'));
-        $show_quiz_edition = false;
-    }
 }
 
 // If we are in a test
@@ -465,10 +455,10 @@ if ($inATest) {
 
     echo Display::url(Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_MEDIUM), 'exercise_report.php?' . api_get_cidReq() . '&exerciseId=' . $objExercise->id);
 
-    if ($show_quiz_edition) {
-        echo '<a href="exercise_admin.php?' . api_get_cidreq() . '&modifyExercise=yes&exerciseId=' . $objExercise->id . '">' . Display::return_icon('settings.png', get_lang('ModifyExercise'), '', ICON_SIZE_MEDIUM) . '</a>';
-    } else {
+    if ($objExercise->edit_exercise_in_lp == false) {
         echo '<a href="">' . Display::return_icon('settings_na.png', get_lang('ModifyExercise'), '', ICON_SIZE_MEDIUM) . '</a>';
+    } else {
+        echo '<a href="exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.Display::return_icon('settings.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
     }
 
     $maxScoreAllQuestions = 0;

+ 4 - 4
main/exercice/answer_admin.inc.php

@@ -787,7 +787,7 @@ if ($modifyAnswers) {
 
                 <input type="hidden" name="formSent" value="1">
                 <input type="hidden" name="nbrAnswers" value="<?php echo $nbrAnswers; ?>">
-                <input type="hidden" name="myid" value="<?php echo $_REQUEST['myid']; ?>">
+                <input type="hidden" name="myid" value="<?php echo intval($_REQUEST['myid']); ?>">
 
                 <table width="650" border="0" cellpadding="5">
 
@@ -890,7 +890,7 @@ if ($modifyAnswers) {
             <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?modifyAnswers=<?php echo $modifyAnswers; ?>">
                 <input type="hidden" name="formSent" value="1">
                 <input type="hidden" name="setWeighting" value="<?php echo $setWeighting; ?>">
-                <input type="hidden" name="myid" value="<?php echo $_REQUEST['myid']; ?>">
+                <input type="hidden" name="myid" value="<?php echo intval($_REQUEST['myid']); ?>">
 
             <?php
             if (!$setWeighting) {
@@ -1024,7 +1024,7 @@ if ($modifyAnswers) {
             <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?modifyAnswers=<?php echo $modifyAnswers; ?>">
                 <input type="hidden" name="formSent" value="1">
                 <input type="hidden" name="setWeighting" value="1">
-                <input type="hidden" name="myid" value="<?php echo $_REQUEST['myid']; ?>">
+                <input type="hidden" name="myid" value="<?php echo intval($_REQUEST['myid']); ?>">
                 <table border="0" cellpadding="5" width="500">
                 <?php
                 if ($okPicture) {
@@ -1077,7 +1077,7 @@ if ($modifyAnswers) {
                     <input type="hidden" name="formSent" value="1">
                     <input type="hidden" name="nbrOptions" value="<?php echo $nbrOptions; ?>">
                     <input type="hidden" name="nbrMatches" value="<?php echo $nbrMatches; ?>">
-                    <input type="hidden" name="myid" value="<?php echo $_REQUEST['myid']; ?>">
+                    <input type="hidden" name="myid" value="<?php echo intval($_REQUEST['myid']); ?>">
 
                     <table border="0" cellpadding="5">
 

+ 12 - 34
main/exercice/exercice.php

@@ -54,7 +54,6 @@ $TBL_ITEM_PROPERTY 			= Database :: get_course_table(TABLE_ITEM_PROPERTY);
 $TBL_EXERCICE_QUESTION 		= Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
 $TBL_EXERCICES 				= Database :: get_course_table(TABLE_QUIZ_TEST);
 $TBL_TRACK_EXERCICES 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$table_lp_item              = Database :: get_course_table(TABLE_LP_ITEM);
 
 // document path
 $documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document";
@@ -448,7 +447,10 @@ if (!empty($exercise_list)) {
         foreach ($exercise_list as $row) {
             $my_exercise_id = $row['id'];
 
-            $locked = api_resource_is_locked_by_gradebook($my_exercise_id, LINK_EXERCISE);
+            $exercise_obj = new Exercise();
+            $exercise_obj->read($my_exercise_id);
+
+            $locked = $exercise_obj->is_gradebook_locked;
 
             //echo '<div  id="tabs-'.$i.'">';
             $i++;
@@ -502,7 +504,7 @@ if (!empty($exercise_list)) {
                 }
 			}
 
-            $cut_title = cut($row['title'], EXERCISE_MAX_NAME_SIZE);
+            $cut_title = $exercise_obj->getCutTitle();
             $alt_title = '';
             if ($cut_title != $row['title']) {
                 $alt_title = ' title = "'.$row['title'].'" ';
@@ -510,28 +512,11 @@ if (!empty($exercise_list)) {
 
             // Teacher only
             if ($is_allowedToEdit) {
-                $added_to_lp = false;
-
-                $sql="SELECT max_score FROM $table_lp_item
-                      WHERE c_id = $course_id AND
-                            item_type = '".TOOL_QUIZ."' AND
-                            path ='".Database::escape_string($row['id'])."'";
-                $result = Database::query($sql);
-                if (Database::num_rows($result) > 0) {
-                    $added_to_lp = true;
-                }
-
-                $lp_blocked = '';
-                if ($added_to_lp) {                    
+                $lp_blocked = null;                
+                if ($exercise_obj->edit_exercise_in_lp == false) {            
                     $lp_blocked = Display::div(get_lang('AddedToLPCannotBeAccessed'), array('class'=> 'lp_content_type_label'));
                 }
-
-                //Showing exercise title
-
-                if ($session_id == $row['session_id']) {
-                    //Settings
-                    //echo Display::url(Display::return_icon('settings.png',get_lang('Edit'), array('width'=>'22px'))." ".get_lang('Edit'), 'exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$row['id']);
-                }                
+               
                 
                 $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
 
@@ -541,9 +526,7 @@ if (!empty($exercise_list)) {
                     $title = $cut_title;
                 }
 
-                /*
-                 * Exercise results counter
-                 * $count = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id));
+                $count = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id));
 
                 $class_tip = '';
                 if (!empty($count)) {
@@ -551,12 +534,6 @@ if (!empty($exercise_list)) {
                     $title .= '<span class="exercise_tooltip" style="display: none;">'.$count.' '.$results_text.' </span>';
                     $class_tip = 'link_tooltip';
                 }
-
-                if ($added_to_lp) {
-                    //$title .= Display::div(get_lang('AddedToLPCannotBeAccessed'), array('class'=> 'lp_content_type_label'));
-                }*/
-                
-                $class_tip = null;
                 $url = '<a '.$alt_title.' class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'"><img src="../img/quiz.gif" /> '.$title.' </a>';
 
                 $item =  Display::tag('td', $url.' '.$session_img.$lp_blocked);
@@ -585,12 +562,13 @@ if (!empty($exercise_list)) {
 
                     //Visible / invisible
                     //Check if this exercise was added in a LP
-                    if ($added_to_lp) {
+                    if ($exercise_obj->edit_exercise_in_lp == false) {
                         $actions .= Display::return_icon('invisible.png', get_lang('AddedToLPCannotBeAccessed'),'',ICON_SIZE_SMALL);
                     } else {
                         if ($row['active'] == 0 || $visibility == 0) {
                             $actions .= Display::url(Display::return_icon('invisible.png', get_lang('Activate'),'',ICON_SIZE_SMALL) , 'exercice.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);                            
-                        } else { // else if not active
+                        } else { 
+                            // else if not active
                             $actions .= Display::url(Display::return_icon('visible.png', get_lang('Deactivate'),'',ICON_SIZE_SMALL) , 'exercice.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);
                         }
                     }

+ 55 - 6
main/exercice/exercise.class.php

@@ -30,6 +30,8 @@ require_once dirname(__FILE__).'/../inc/lib/exercise_show_functions.lib.php';
 class Exercise {
 
 	public $id;
+    public $name;
+    public $title;
 	public $exercise;
 	public $description;
 	public $sound;
@@ -53,6 +55,10 @@ class Exercise {
 	public $text_when_finished;
 	public $display_category_name;
     public $pass_percentage;
+    public $edit_exercise_in_lp = false;
+    public $is_gradebook_locked = false;
+    public $exercise_was_added_in_lp = false;
+    public $force_edit_exercise_in_lp = false;
 	 
 	/**
 	 * Constructor of the class
@@ -98,8 +104,10 @@ class Exercise {
 	 * @return - boolean - true if exercise exists, otherwise false
 	 */
 	function read($id) {		
+        global $_configuration;
 		$TBL_EXERCICES          = Database::get_course_table(TABLE_QUIZ_TEST);
 		
+        $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
 		$id  = intval($id);
         if (empty($this->course_id)) {
             return false;
@@ -111,7 +119,8 @@ class Exercise {
 		if ($object = Database::fetch_object($result)) {
 			$this->id                       = $id;
 			$this->exercise                 = $object->title;
-			$this->name                     = cut($object->title, EXERCISE_MAX_NAME_SIZE);
+			$this->name                     = $object->title;
+            $this->title                    = $object->title;
 			$this->description              = $object->description;
 			$this->sound                    = $object->sound;
 			$this->type                     = $object->type;
@@ -126,8 +135,26 @@ class Exercise {
 			$this->text_when_finished       = $object->text_when_finished; 
 			$this->display_category_name    = $object->display_category_name;
             $this->pass_percentage          = $object->pass_percentage;
+            $this->is_gradebook_locked      = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
 		
 			$this->review_answers   = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;  
+            $sql = "SELECT max_score FROM $table_lp_item
+                    WHERE   c_id = {$this->course_id} AND
+                            item_type = '".TOOL_QUIZ."' AND
+                            path = '".$id."'";
+            $result = Database::query($sql);
+
+            if (Database::num_rows($result) > 0) {
+                $this->exercise_was_added_in_lp = true;
+            }
+
+            $this->force_edit_exercise_in_lp = isset($_configuration['force_edit_exercise_in_lp']) ? $_configuration['force_edit_exercise_in_lp'] : false;
+
+            if ($this->exercise_was_added_in_lp) {
+                $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
+            } else {
+                $this->edit_exercise_in_lp = true;
+            }
 			
 			if ($object->end_time != '0000-00-00 00:00:00') {
 				$this->end_time 	= $object->end_time;
@@ -135,28 +162,33 @@ class Exercise {
 			if ($object->start_time != '0000-00-00 00:00:00') {
 				$this->start_time 	= $object->start_time;
 			}
-			$this->expired_time 	= $object->expired_time; //control time
             
+            //control time
+			$this->expired_time 	= $object->expired_time;
             //Checking if question_order is correctly set
             $this->questionList = $this->selectQuestionList(true);
 				
 			//overload questions list with recorded questions list
 			//load questions only for exercises of type 'one question per page'
 			//this is needed only is there is no questions
-            //			
+            /*
 			// @todo not sure were in the code this is used somebody mess with the exercise tool
 			// @todo don't know who add that config and why $_configuration['live_exercise_tracking']
 			global $_configuration, $questionList;
 			if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
 			isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {				
+				//if(empty($_SESSION['questionList']))
 				$this->questionList = $questionList;
-			}
+			}*/
 			return true;
 		}
 		// exercise not found
 		return false;
 	}
 
+    function getCutTitle() {
+        return cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
+	}
 	/**
 	 * returns the exercise ID
 	 *
@@ -1587,8 +1619,7 @@ class Exercise {
 		global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;        
 		$nbrQuestions = $this->get_count_question_list();
         		 
-		$all_button = $html = $label = null;
-		//$confirmation_alert = $this->type == ALL_ON_ONE_PAGE? " onclick=\"javascript:if(!confirm('".get_lang("ConfirmYourChoice")."')) return false;\" ":"";
+		$all_button = $html = $label = '';
 		$hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']):null;		
 	
 		if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {            
@@ -3377,6 +3408,7 @@ class Exercise {
 			}
 			foreach ($question_list as $questionId) {
 				$question_result = $objExercise->manage_answer($exe_id, $questionId, '','exercise_show', array(), false, true, false, $objExercise->selectPropagateNeg());				
+				$questionScore   = $question_result['score'];
 				$totalScore      += $question_result['score'];
 			}
 				
@@ -3660,6 +3692,23 @@ class Exercise {
 		$new_array = array();
 		if (Database::num_rows($result) > 0 ) {
 			$new_array = Database::fetch_array($result, 'ASSOC');
+
+            $new_array['duration'] = null;
+
+            $start_date = api_get_utc_datetime($new_array['start_date'], true);
+            $end_date = api_get_utc_datetime($new_array['exe_date'], true);
+
+            if (!empty($start_date) && !empty($end_date)) {
+                $start_date = api_strtotime($start_date, 'UTC');
+                $end_date = api_strtotime($end_date, 'UTC');
+                if ($start_date && $end_date) {
+                    $mytime = $end_date- $start_date;
+                    $time_attemp = learnpathItem :: get_scorm_time('js', $mytime);
+                    $h = get_lang('h');
+                    $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
+                    $new_array['duration'] = $time_attemp;
+                }
+            }
 		}
 		return $new_array;
 	}

+ 74 - 34
main/exercice/exercise.lib.php

@@ -422,6 +422,7 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
                             $correct_item = preg_quote($correct_item);
                             $correct_item = api_preg_replace('|/|', '\/', $correct_item);   // to prevent error if there is a / in the text to find
 				            $answer = api_preg_replace('/'.$correct_item.'/', Display::input('text', "choice[$questionId][]", $value), $answer);                            
+                            //$answer = api_preg_replace('/\['.$correct_item.'+\]/', Display::input('text', "choice[$questionId][]", $value), $answer);	
 				        }		        				        
 				        $i++;				        
 				    }
@@ -993,7 +994,8 @@ function get_exam_results_data($from, $number_of_items, $column, $direction, $ex
                     propagate_neg,
                     revised,
                     group_name,
-                    group_id";
+                    group_id,
+                    orig_lp_id";
         }
         
         $sql = " $sql_select            
@@ -1003,9 +1005,7 @@ function get_exam_results_data($from, $number_of_items, $column, $direction, $ex
                 WHERE $extra_where_conditions AND
                     te.status != 'incomplete' 
                     AND te.exe_cours_id='" . api_get_course_id() . "' $session_id_and 
-                    AND ce.active <>-1 
-                    AND orig_lp_id = 0 
-                    AND orig_lp_item_id = 0
+                    AND ce.active <>-1
                     AND ce.c_id=".api_get_course_int_id()."					
                     $exercise_where ";
          
@@ -2077,9 +2077,7 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
     if ($show_results || $show_only_score) {
         $user_info   = api_get_user_info($exercise_stat_info['exe_user_id']);
         //Shows exercise header
-        $objExercise->description = '';
-        //var_dump($exercise_stat_info);
-        echo $objExercise->show_exercise_result_header($user_info['complete_name'], api_convert_and_format_date($exercise_stat_info['exe_date'], DATE_TIME_FORMAT_LONG));
+        echo $objExercise->show_exercise_result_header($user_info['complete_name'], api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG), $exercise_stat_info['duration']);
     }
     
     if ($save_user_result) {    
@@ -2095,6 +2093,7 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
     
     $question_list_answers = array();
     $media_list = array();
+    $category_list = array();
 
     // Loop over all question to show results for each of them, one by one
     if (!empty($question_list)) {
@@ -2115,10 +2114,36 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
             $total_score     += $result['score'];
             $total_weight    += $result['weight'];
             
-            $question_list_answers[] = array('question' => $result['open_question'], 'answer' => $result['open_answer']);            
+            $question_list_answers[] = array(
+                'question' => $result['open_question'],
+                'answer' => $result['open_answer']
+            );
             
             $my_total_score  = $result['score'];
-            $my_total_weight = $result['weight'];   
+            $my_total_weight = $result['weight'];  
+ 
+            //Category report
+            $category_was_added_for_this_test = false;
+
+            if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
+                $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
+                $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
+                $category_was_added_for_this_test = true;
+            }
+
+            if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
+                foreach($objQuestionTmp->category_list as $category_id) {
+                    $category_list[$category_id]['score'] += $my_total_score;
+                    $category_list[$category_id]['total'] += $my_total_weight;
+                    $category_was_added_for_this_test = true;
+                }
+            }
+
+            //No category for this question!
+            if ($category_was_added_for_this_test == false) {
+                $category_list['none']['score'] += $my_total_score;
+                $category_list['none']['total'] += $my_total_weight;
+            }
 
             if ($objExercise->selectPropagateNeg() == 0 && $my_total_score < 0) {
                 $my_total_score = 0;
@@ -2135,7 +2160,7 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
             
             $score = array();    
             if ($show_results) {	    
-                $score['result'] = get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, false);
+                $score['result']    = get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, true);
                 $score['pass'] = $my_total_score >= $my_total_weight ? true : false;
                 $score['score'] = $my_total_score;
                 $score['weight'] = $my_total_weight;
@@ -2175,34 +2200,18 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
     if ($origin != 'learnpath') {
         if ($show_results || $show_only_score) {
             
-            $is_success = is_success_exercise_result($total_score, $total_weight, $objExercise->selectPassPercentage());
+
             $total_score_text .= '<div class="question_row">';
-            $total_score_text .= '<div class="ribbon ribbon-total ">';
-            
-            // Color the final test score if pass_percentage activated
-            $ribbon_total_success_or_error = "";
-            if (is_pass_pourcentage_enabled($objExercise->selectPassPercentage())) {
-                if ($is_success) {
-                    $ribbon_total_success_or_error = ' ribbon-total-success';
-                } else {
-                    $ribbon_total_success_or_error = ' ribbon-total-error';
+            $total_score_text .= get_question_ribbon($objExercise, $total_score, $total_weight, true);
+            $total_score_text .= '</div>';
                 }
             }
-            $total_score_text .= '<div class="rib rib-total $ribbon_total_success_or_error">';
-            
-            $total_score_text .= '<h3>';
-            $total_score_text .= get_lang('YourTotalScore')."&nbsp;";
-            if ($objExercise->selectPropagateNeg() == 0 && $total_score < 0) {
-                $total_score = 0;
-            }
-            $total_score_text .= show_score($total_score, $total_weight, false, true);
-            $total_score_text .= '</h3>';            
-            $total_score_text .= '</div>';
-            $total_score_text .= show_success_message($total_score, $total_weight, $objExercise->selectPassPercentage());
+
             
-            $total_score_text .= '</div>';
-            $total_score_text .= '</div>';
-        }
+    if (!empty($category_list) && ($show_results || $show_only_score) ) {
+        //Adding total
+        $category_list['total'] = array('score' => $total_score, 'total' => $total_weight);
+        echo Testcategory::get_stats_table_by_attempt($objExercise->id, $category_list);
     }
     
     echo $total_score_text;   
@@ -2228,4 +2237,35 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
             $objExercise->send_notification_for_open_questions($question_list_answers, $origin, $exe_id);
         }
     }    
+}
+
+
+function get_question_ribbon($objExercise, $score, $weight, $check_pass_percentage = false) {
+    $ribbon = '<div class="ribbon">';
+    if ($check_pass_percentage) {
+        $is_success = is_success_exercise_result($score, $weight, $objExercise->selectPassPercentage());
+        // Color the final test score if pass_percentage activated
+        $ribbon_total_success_or_error = "";
+        if (is_pass_pourcentage_enabled($objExercise->selectPassPercentage())) {
+            if ($is_success) {
+                $ribbon_total_success_or_error = ' ribbon-total-success';
+            } else {
+                $ribbon_total_success_or_error = ' ribbon-total-error';
+            }
+        }
+        $ribbon .= '<div class="rib rib-total '.$ribbon_total_success_or_error.'">';
+    } else {
+        $ribbon .= '<div class="rib rib-total">';
+    }
+    $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
+    $ribbon .= show_score($score, $weight, false, true);
+    $ribbon .= '</h3>';
+    $ribbon .= '</div>';
+    if ($check_pass_percentage) {
+        $ribbon .= show_success_message($score, $weight, $objExercise->selectPassPercentage());
+    }
+
+
+    $ribbon .= '</div>';
+    return $ribbon;
 }

+ 2 - 1
main/exercice/exercise_admin.php

@@ -113,7 +113,8 @@ $htmlHeadXtra[] = '<script>
 				document.getElementById(\'divtimecontrol\').style.display=\'none\';
 				document.getElementById(\'enabletimercontroltotalminutes\').value=\'\';
 			}*/
-			if (document.getElementById(\'exerciseType_1\').checked) {
+            
+			if (document.getElementById(\'exerciseType_1\') && document.getElementById(\'exerciseType_1\').checked) {
 				document.getElementById(\'exerciseType_0\').checked = true;
 			}
 		}

+ 17 - 12
main/exercice/exercise_report.php

@@ -322,22 +322,31 @@ if (!empty($group_parameters)) {
 if ($is_allowedToEdit || $is_tutor) {
 
 	//The order is important you need to check the the $column variable in the model.ajax.php file
-	$columns        = array(get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'),
-                        get_lang('Group'), get_lang('Duration').' ('.get_lang('MinMinute').')', get_lang('StartDate'),  get_lang('EndDate'), get_lang('Score'), get_lang('Status'), get_lang('Actions'));
+	$columns        = array(get_lang('FirstName'), 
+                            get_lang('LastName'), 
+                            get_lang('LoginName'),
+                            get_lang('Group'), 
+                            get_lang('Duration').' ('.get_lang('MinMinute').')', 
+                            get_lang('StartDate'),  
+                            get_lang('EndDate'), 
+                            get_lang('Score'), 
+                            get_lang('Status'), 
+                            get_lang('ToolLearnpath'), 
+                            get_lang('Actions')
+    );
 
 //Column config
 	$column_model   = array(
                         array('name'=>'firstname',      'index'=>'firstname',		'width'=>'50',   'align'=>'left', 'search' => 'true'),
                         array('name'=>'lastname',		'index'=>'lastname',		'width'=>'50',   'align'=>'left', 'formatter'=>'action_formatter', 'search' => 'true'),
-                        array('name'=>'login',          'hidden'=>'true',          'index'=>'username',        'width'=>'40',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'group_name',		'index'=>'group_id',    'width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=> 'select',
+                        array('name'=>'login',          'index'=>'username',        'width'=>'40',   'align'=>'left', 'search' => 'true', 'hidden'=>'true'),
+                        array('name'=>'group_name',		'index'=>'group_id',        'width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=> 'select',
                             //for the bottom bar
                             'searchoptions' => array(
                                             'defaultValue'  => 'group_all',
                                             'value'         => $group_parameters),
                               //for the top bar
-                              'editoptions' => array('value' => $group_parameters)),
-
+                            'editoptions' => array('value' => $group_parameters)),
                         array('name'=>'duration',       'index'=>'exe_duration',	'width'=>'30',   'align'=>'left', 'search' => 'true'),
                         array('name'=>'start_date',		'index'=>'start_date',		'width'=>'60',   'align'=>'left', 'search' => 'true'),
 						array('name'=>'exe_date',		'index'=>'exe_date',		'width'=>'60',   'align'=>'left', 'search' => 'true'),
@@ -350,8 +359,7 @@ if ($is_allowedToEdit || $is_tutor) {
 
                               //for the top bar
                               'editoptions' => array('value' => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang('NotValidated'))),
-//issue fixed in jqgrid
-//                      array('name'=>'actions',        'index'=>'actions',         'width'=>'100',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false')
+                        array('name'=>'lp',             'index'=>'lp',              'width'=>'60',  'align'=>'left', 'search' => 'false'),
 						array('name'=>'actions',        'index'=>'actions',         'width'=>'60',  'align'=>'left', 'search' => 'false')
                        );
 
@@ -372,9 +380,6 @@ $extra_params['autowidth'] = 'true';
 
 //height auto
 $extra_params['height'] = 'auto';
-//$extra_params['excel'] = 'excel';
-
-$extra_params['rowList'] = array(10, 20 ,30);
 
 ?>
 <script>
@@ -420,7 +425,7 @@ function exportExcel() {
 
 $(function() {
     <?php
-        echo Display::grid_js('results', $url,$columns,$column_model, $extra_params, array(), $action_links, true);
+        echo Display::grid_js('results', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
 
     if ($is_allowedToEdit || $is_tutor) { ?>
 

+ 5 - 6
main/exercice/exercise_result.php

@@ -132,6 +132,7 @@ if ($objExercise->selectAttempts() > 0) {
 
 Display :: display_normal_message(get_lang('Saved').'<br />',false);
 
+//Display questions
 display_question_list_by_attempt($objExercise, $exe_id, true);
 
 //If is not valid
@@ -150,7 +151,7 @@ delete_chat_exercise_session($exe_id);
 if ($origin != 'learnpath') {
     echo '<hr>';
     echo Display::url(get_lang('ReturnToCourseHomepage'), api_get_course_url(), array('class' => 'btn btn-large'));
-    
+
     if (api_is_allowed_to_session_edit()) {
         Session::erase('objExercise');
         Session::erase('exe_id');
@@ -160,16 +161,14 @@ if ($origin != 'learnpath') {
 } else {
 	$lp_mode =  $_SESSION['lp_mode'];
 	$url = '../newscorm/lp_controller.php?cidReq='.api_get_course_id().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exercise_stat_info['exe_id'].'&fb_type='.$objExercise->feedback_type;
-	//echo $total_score.','.$total_weight;	exit;
 	$href = ($lp_mode == 'fullscreen')?' window.opener.location.href="'.$url.'" ':' top.location.href="'.$url.'"';
-    
+
     if (api_is_allowed_to_session_edit()) {
         Session::erase('objExercise');
         Session::erase('exe_id');
     }
-
-	echo '<script type="text/javascript">'.$href.'</script>';
 	//record the results in the learning path, using the SCORM interface (API)
-	echo '<script type="text/javascript">window.parent.API.void_save_asset('.$total_score.','.$total_weight.');</script>';
+	echo "<script>window.parent.API.void_save_asset('$total_score', '$total_weight', 0, 'completed');</script>";
+    echo '<script type="text/javascript">'.$href.'</script>';
 	echo '</body></html>';
 }

+ 40 - 13
main/exercice/exercise_show.php

@@ -242,14 +242,21 @@ $query = "SELECT attempts.question_id, answer FROM ".$TBL_TRACK_ATTEMPT." as att
           //GROUP BY questions.position, attempts.question_id";
 
 $result = Database::query($query);
+$questionList = array();
 $exerciseResult = array();
 
 while ($row = Database::fetch_array($result)) {	
+	$questionList[] = $row['question_id'];
 	$exerciseResult[$row['question_id']] = $row['answer'];
 }
 
-// always getting question list from the DB
-$questionList = explode(',',$track_exercise_info['data_tracking']);
+//Fixing #2073 Fixing order of questions
+if (!empty($track_exercise_info['data_tracking']) && !empty($track_exercise_info['random']) ) {
+	$tempquestionList = explode(',',$track_exercise_info['data_tracking']);
+	if (is_array($tempquestionList) && count($tempquestionList) == count($questionList)) {	
+		$questionList = $tempquestionList;			
+	}		
+}
 
 // Display the text when finished message if we are on a LP #4227
 $end_of_message = $objExercise->selectTextWhenFinished();
@@ -270,7 +277,7 @@ $counter = 1;
 $exercise_content = null;
 
 $media_list = array();
-
+$category_list = array();
 foreach ($questionList as $questionId) {
     
 	$choice = $exerciseResult[$questionId];
@@ -573,6 +580,27 @@ foreach ($questionList as $questionId) {
 	$my_total_weight = $questionWeighting;   
     $totalWeighting += $questionWeighting;
 	
+    $category_was_added_for_this_test = false;
+
+    if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
+        $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
+        $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
+        $category_was_added_for_this_test = true;
+    }
+
+    if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
+        foreach($objQuestionTmp->category_list as $category_id) {
+            $category_list[$category_id]['score'] += $my_total_score;
+            $category_list[$category_id]['total'] += $my_total_weight;
+            $category_was_added_for_this_test = true;
+        }
+    }
+
+    //No category for this question!
+    if ($category_was_added_for_this_test == false) {
+        $category_list['none']['score'] += $my_total_score;
+        $category_list['none']['total'] += $my_total_weight;
+    }
     if ($objExercise->selectPropagateNeg() == 0 && $my_total_score < 0) {
         $my_total_score = 0;
     }
@@ -621,23 +649,22 @@ $total_score_text = null;
 if ($origin!='learnpath' || ($origin == 'learnpath' && isset($_GET['fb_type']))) {
 	if ($show_results || $show_only_total_score ) {
         
-        $total_score_text .= '<div class="question_row">
-        <div class="ribbon">
-        <div class="rib rib-total">';
-        
-		$total_score_text .= '<h3>'.get_lang('YourTotalScore').": ";
+        $total_score_text .= '<div class="question_row">';
         $my_total_score_temp = $totalScore; 
 	    if ($objExercise->selectPropagateNeg() == 0 && $my_total_score_temp < 0) {
 	        $my_total_score_temp = 0;
 	    }          
-        $total_score_text .= show_score($my_total_score_temp, $totalWeighting, false);	        
-		$total_score_text .= '</h3>';
-        $total_score_text .= '</div>';
-        $total_score_text .= '</div>';
+        $total_score_text .= get_question_ribbon($objExercise, $my_total_score_temp, $totalWeighting, true);
         $total_score_text .= '</div>';
 	}
 }
 
+if (!empty($category_list) && ($show_results || $show_only_total_score)) {
+    //Adding total
+    $category_list['total'] = array('score' => $my_total_score_temp, 'total' => $totalWeighting);
+
+    echo Testcategory::get_stats_table_by_attempt($objExercise->id, $category_list);
+}
 echo $total_score_text;
 echo $exercise_content;
 echo $total_score_text;
@@ -693,7 +720,7 @@ if ($origin != 'learnpath') {
 		echo '<script type="text/javascript">'.$href.'</script>';		
 		
 		//Record the results in the learning path, using the SCORM interface (API)		
-		echo '<script type="text/javascript">window.parent.API.void_save_asset('.$totalScore.','.$totalWeighting.');</script>'."\n";
+		echo "<script>window.parent.API.void_save_asset('$totalScore', '$totalWeighting'); </script>";
 		echo '</body></html>';
 	} else {
 		Display::display_normal_message(get_lang('ExerciseFinished').' '.get_lang('ToContinueUseMenu'));

+ 2 - 5
main/exercice/exercise_submit.php

@@ -217,12 +217,11 @@ if ($objExercise->selectAttempts() > 0) {
 }
 
 
+if ($debug) { error_log("4. Setting the exe_id: $exe_id");} ;
 
 //5. Getting user exercise info (if the user took the exam before) - generating exe_id
 //var_dump($learnpath_id.' - '.$learnpath_item_id.' - '.$learnpath_item_view_id);
 $exercise_stat_info = $objExercise->get_stat_track_exercise_info($learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
-
-if ($debug)  error_log('4. Trying to create an attempt ');
  
 if (empty($exercise_stat_info)) {
     if ($debug)  error_log('5  $exercise_stat_info is empty ');
@@ -256,8 +255,6 @@ if (empty($exercise_stat_info)) {
     if ($debug)  error_log("5  exercise_stat_info[] exists getting exe_id $exe_id ");
 }
 
-if ($debug) { error_log("4. Setting the exe_id: $exe_id");} ;
-
 //Array to check in order to block the chat
 create_chat_exercise_session($exe_id);
 
@@ -332,7 +329,7 @@ if ($time_control) {
         $clock_expired_time =  $_SESSION['expired_time'][$current_expired_time_key];
     }
 } else {
-    if ($debug) { error_log("7. No time control"); };
+    if ($debug) { error_log("7 No time control"); };
 }
 
 // Get time left for exipiring time

+ 2 - 2
main/exercice/global_multiple_answer.class.php

@@ -143,10 +143,10 @@ if (!class_exists('GlobalMultipleAnswer')):
             $form->addRule('weighting[1]', get_lang('ThisFieldIsRequired'), 'required');
 
             $navigator_info = api_get_navigator();
-            global $text, $class, $show_quiz_edition;
+            global $text, $class;
 
             //ie6 fix
-            if ($show_quiz_edition) {
+            if ($obj_ex->edit_exercise_in_lp == true) {
                 if ($navigator_info['name'] == 'Internet Explorer' && $navigator_info['version'] == '6') {
                     $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'), 'class="minus"');
                     $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'), 'class="plus"');

+ 1 - 1
main/exercice/hotpotatoes_exercise_report.php

@@ -366,7 +366,7 @@ $extra_params['autowidth'] = 'true';
 //height auto
 $extra_params['height'] = 'auto';
 //$extra_params['excel'] = 'excel';
-$extra_params['rowList'] = array(20, 50, 100, 500, 1000, 2000, 5000, 10000);
+//$extra_params['rowList'] = array(20, 50, 100, 500, 1000, 2000, 5000, 10000);
 
 ?>
 <script>

+ 14 - 18
main/exercice/hotspot_answers.as.php

@@ -14,10 +14,9 @@ include('question.class.php');
 include('answer.class.php');
 include('../inc/global.inc.php');
 
-// set vars
-$userId        = $_user['user_id'];
-$questionId    = $_GET['modifyAnswers'];
-$exe_id        = $_GET['exe_id'];
+// Set vars
+$questionId    = intval($_GET['modifyAnswers']);
+$exe_id        = intval($_GET['exe_id']);
 $from_db 	   = isset($_GET['from_db']) ? $_GET['from_db'] : 0;
 $objQuestion   = Question :: read($questionId);
 $TBL_ANSWERS   = Database::get_course_table(TABLE_QUIZ_ANSWER);
@@ -30,13 +29,14 @@ $pictureWidth  = $pictureSize[0];
 $pictureHeight = $pictureSize[1];
 
 $courseLang    = $_course['language'];
-$courseCode    = $_course['sysCode'];
+$course_code   = Database::escape_string($_course['id']);
+
 $coursePath    = $_course['path'];
 $answer_type   = $objQuestion->selectType();
 
 $course_id     = api_get_course_int_id();
 
-if ($answer_type==HOT_SPOT_DELINEATION) {
+if ($answer_type == HOT_SPOT_DELINEATION) {
 	// Query db for answers
 	$sql = "SELECT id, answer, hotspot_coordinates, hotspot_type FROM $TBL_ANSWERS 
 	        WHERE c_id = $course_id AND question_id = '".Database::escape_string($questionId)."' AND hotspot_type <> 'noerror' ORDER BY id";
@@ -84,24 +84,21 @@ for ($i; $i <= 12; $i++) {
 	$output .= "&hotspot_".$i."=false";
 }
 
-// set vars
-$questionId    = $_GET['modifyAnswers'];
-$course_code   = $_course['id'];
 
 // Get clicks
 if(isset($_SESSION['exerciseResultCoordinates']) && $from_db==0) {    
 	foreach ($_SESSION['exerciseResultCoordinates'][$questionId] as $coordinate) {
 		$output2 .= $coordinate."|";
 	}
-} else {
-    
+} else {    
 	// get it from db
 	$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
-	$sql = 'SELECT hotspot_coordinate '.
-			' FROM '.$tbl_track_e_hotspot.
-			' WHERE hotspot_question_id = '.intval($questionId).
-			' AND hotspot_course_code = "'.Database::escape_string($course_code).'"'.
-			' AND hotspot_exe_id='.intval($exe_id);
+	$sql = "SELECT hotspot_coordinate
+            FROM $tbl_track_e_hotspot
+            WHERE   hotspot_question_id = $questionId AND 
+                    hotspot_course_code = '$course_code' AND 
+                    hotspot_exe_id = $exe_id 
+            ORDER by hotspot_id";
 	$rs = @Database::query($sql); // don't output error because we are in Flash execution.
 	while($row = Database :: fetch_array($rs)) {
 		$output2 .= $row['hotspot_coordinate']."|";
@@ -109,5 +106,4 @@ if(isset($_SESSION['exerciseResultCoordinates']) && $from_db==0) {
 }
 $output .= "&p_hotspot_answers=".api_substr($output2,0,-1)."&done=done";
 $explode = explode('&', $output);
-
-echo $output;
+echo $output;

+ 3 - 7
main/exercice/matching.class.php

@@ -35,7 +35,6 @@ class Matching extends Question {
 	 * @param the formvalidator instance
 	 */
 	function createAnswersForm ($form) {
-
 		$defaults = array();
 		$navigator_info = api_get_navigator();
 
@@ -71,8 +70,7 @@ class Matching extends Question {
 				}
 
 			}
-		}
-		else {
+		} else {
 			$defaults['answer[1]'] = get_lang('DefaultMakeCorrespond1');
 			$defaults['answer[2]'] = get_lang('DefaultMakeCorrespond2');
 			$defaults['matches[2]'] = '2';
@@ -80,8 +78,7 @@ class Matching extends Question {
 			$defaults['option[2]'] = get_lang('DefaultMatchingOptB');
 		}
 		$a_matches = array();
-		for($i=1 ; $i<=$nb_options ; ++$i)
-		{
+		for($i=1 ; $i<=$nb_options ; ++$i) {
 			$a_matches[$i] = chr(64+$i);  // fill the array with A, B, C.....
 		}
 
@@ -212,8 +209,7 @@ class Matching extends Question {
 		$position = 0;
 
 		// insert the options
-		for($i=1 ; $i<=$nb_options ; ++$i)
-		{
+		for($i=1 ; $i<=$nb_options; ++$i) {
 			$position++;
 			$option = $form -> getSubmitValue('option['.$i.']');
 			$objAnswer->createAnswer($option, 0, '', 0, $position);

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

@@ -137,8 +137,8 @@ class MultipleAnswer extends Question {
 
 		$navigator_info = api_get_navigator();
 
-		global $text, $class, $show_quiz_edition;
-		if ($show_quiz_edition) {
+		global $text, $class;
+		if ($obj_ex->edit_exercise_in_lp == true) {
 			//ie6 fix
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');

+ 4 - 6
main/exercice/multiple_answer_combination.class.php

@@ -78,8 +78,7 @@ class MultipleAnswerCombination extends Question {
 		if ($nb_answers < 1) {
 			$nb_answers = 1;
 			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
-		}
-		
+		}		
 
 		for($i = 1 ; $i <= $nb_answers ; ++$i) {
 			if(is_object($answer)) {
@@ -125,16 +124,15 @@ class MultipleAnswerCombination extends Question {
 		$form -> addElement ('html', '</table>');
 		$form -> addElement ('html', '<br />');
 
-		$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');
-		
+		$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');		
 						
 		//only 1 answer the all deal ...
 		$form->addElement('text', 'weighting[1]', get_lang('Score'), array('class' => "span1", 'value' => '10'));
 				
 		$navigator_info = api_get_navigator();
-		global $text, $class, $show_quiz_edition;
+		global $text, $class;
 		//ie6 fix
-		if ($show_quiz_edition) {
+		if ($obj_ex->edit_exercise_in_lp == true) {
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
                 
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');

+ 5 - 10
main/exercice/multiple_answer_true_false.class.php

@@ -159,16 +159,11 @@ class MultipleAnswerTrueFalse extends Question {
         
         $form->addRule('option[1]', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('option[2]', get_lang('ThisFieldIsRequired'), 'required');
-        $form->addRule('option[3]', get_lang('ThisFieldIsRequired'), 'required');
-                
+        $form->addRule('option[3]', get_lang('ThisFieldIsRequired'), 'required');                
         
         $form -> addElement ('html', '</tr><table>');
-        
-
-        $form -> addElement('hidden', 'options_count', 3);
-                    
-        $form -> addElement ('html', '</table><br /><br />');
-        
+        $form -> addElement('hidden', 'options_count', 3);                    
+        $form -> addElement ('html', '</table><br /><br />');        
         
         //Extra values True, false,  Dont known
         if (!empty($this->extra)) {
@@ -184,8 +179,8 @@ class MultipleAnswerTrueFalse extends Question {
 
 		$navigator_info = api_get_navigator();
 
-		global $text, $class, $show_quiz_edition;
-		if ($show_quiz_edition) {
+		global $text, $class;
+		if ($obj_ex->edit_exercise_in_lp == true) {
 			//ie6 fix
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
                 

+ 21 - 29
main/exercice/question.class.php

@@ -1336,53 +1336,44 @@ abstract class Question
 	/**
 	 * Displays the menu of question types
 	 */
-	static function display_type_menu ($feedback_type = 0) {
-		global $exerciseId;
-        $course_id = api_get_course_int_id();
+	static function display_type_menu($objExercise) {
+        $feedback_type = $objExercise->feedback_type;
+        $exerciseId = $objExercise->id;
         
 		// 1. by default we show all the question types
 		$question_type_custom_list = self::get_question_type_list();
 
-		if (!isset($feedback_type)) $feedback_type=0;
+		if (!isset($feedback_type)) {
+            $feedback_type = 0;
+        }
 		if ($feedback_type==1) {
 			//2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
-			//$question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER]);
-			$question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION]);  
+			$question_type_custom_list = array (
+                UNIQUE_ANSWER           => self::$questionTypes[UNIQUE_ANSWER],
+                HOT_SPOT_DELINEATION    => self::$questionTypes[HOT_SPOT_DELINEATION]
+            );
 		} else {
 			unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
 		}
-
-		//blocking edition
-
-		$show_quiz_edition = true;
-		if (isset($exerciseId) && !empty($exerciseId)) {
-			$TBL_LP_ITEM	= Database::get_course_table(TABLE_LP_ITEM);
-			$sql="SELECT max_score FROM $TBL_LP_ITEM
-				  WHERE c_id = $course_id AND item_type = '".TOOL_QUIZ."' AND path ='".Database::escape_string($exerciseId)."'";
-			$result = Database::query($sql);
-			if (Database::num_rows($result) > 0) {
-				$show_quiz_edition = false;
-			}
-		}
         
         echo '<div class="actionsbig">';
 		echo '<ul class="question_menu">';
 
 		foreach ($question_type_custom_list as $i=>$a_type) {
 			// include the class of the type
-			require_once($a_type[0]);
+			require_once $a_type[0];
             // get the picture of the type and the langvar which describes it
             $img = $explanation = '';
 			eval('$img = '.$a_type[1].'::$typePicture;');
 			eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
 			echo '<li>';
 			echo '<div class="icon_image_content">';
-			if ($show_quiz_edition) {
-				echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation).'</a>';				
-			} else {
+			if ($objExercise->edit_exercise_in_lp == false) {
 				$img = pathinfo($img);
 				$img = $img['filename'].'_na.'.$img['extension'];
-				echo ''.Display::return_icon($img,$explanation).'';				
+				echo Display::return_icon($img,$explanation);
+			} else {
+                echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation).'</a>';
 			}
 			echo '</div>';
 			echo '</li>';
@@ -1390,15 +1381,15 @@ abstract class Question
 
 		echo '<li>';
 		echo '<div class="icon_image_content">';
-		if ($show_quiz_edition) {
+		if ($objExercise->edit_exercise_in_lp == false) {
+            echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'));
+		} else {
 			if ($feedback_type==1) {
 				echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&type=1&fromExercise='.$exerciseId.'">';
 			} else {
 				echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
 			}
-			echo Display::return_icon('database.png', get_lang('GetExistingQuestion'), '');
-		} else {
-			echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'), '');
+			echo Display::return_icon('database.png', get_lang('GetExistingQuestion'));
 		}	
 		echo '</a>';
 		echo '</div></li>';
@@ -1441,7 +1432,7 @@ abstract class Question
      * @param type $counter
      * @param type $score
      */
-	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {          
+	function return_header($feedback_type = null, $counter = null, $score = null) {
 	    $counter_label = '';
 	    if (!empty($counter)) {
 	        $counter_label = intval($counter);
@@ -1462,6 +1453,7 @@ abstract class Question
                 $class = 'error';
             }
         }
+        $question_title = $this->question;
         
         $question_title = $this->question;
 	    $header =  Display::div('<div class="rib rib-'.$class.'"><h3>'.$score_label.'</h3></div> <h4>'.get_lang("Question").' '.($counter_label).' </h4><h5 class="'.$class.'">'.$score['result'].' </h5>', array('class'=>'ribbon'));

+ 2 - 19
main/exercice/question_admin.inc.php

@@ -18,25 +18,14 @@ $course_id = api_get_course_int_id();
 if (isset($_GET['editQuestion'])) {
 	$objQuestion = Question::read ($_GET['editQuestion']);    
 	$action = api_get_self()."?".api_get_cidreq()."&myid=1&modifyQuestion=".$modifyQuestion."&editQuestion=".$objQuestion->id;
-
-	if (isset($exerciseId) && !empty($exerciseId)) {
-		$TBL_LP_ITEM	= Database::get_course_table(TABLE_LP_ITEM);
-		$sql="SELECT max_score FROM $TBL_LP_ITEM
-			  WHERE c_id = $course_id AND item_type = '".TOOL_QUIZ."' AND path ='".Database::escape_string($exerciseId)."'";
-		$result = Database::query($sql);
-		if (Database::num_rows($result) > 0) {
-			//Display::display_warning_message(get_lang('EditingScoreCauseProblemsToExercisesInLP'));
-		}
-	}
 } else {
 	$objQuestion = Question :: getInstance($_REQUEST['answerType']);
 	$action = api_get_self()."?".api_get_cidreq()."&modifyQuestion=".$modifyQuestion."&newQuestion=".$newQuestion;
 }
 
 if (is_object($objQuestion)) {
-	//INIT FORM    
+	//FORM CREATION
 	$form = new FormValidator('question_admin_form','post', $action);
-    //FORM CREATION
     
 	if(isset($_GET['editQuestion'])) {
 		$class="btn save";
@@ -61,16 +50,10 @@ if (is_object($objQuestion)) {
 	$objQuestion->createAnswersForm($form);
 
 	// this variable  $show_quiz_edition comes from admin.php blocks the exercise/quiz modifications
-	if (!$show_quiz_edition) {
+	if ($objExercise->edit_exercise_in_lp == false) {
 		$form->freeze();
 	}
 
-	// submit button is implemented in every question type
-
-	//$form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
-	//$renderer = $form->defaultRenderer();
-	//$renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','submitQuestion');
-	
 	// FORM VALIDATION
     
 	if (isset($_POST['submitQuestion']) && $form->validate()) {

+ 6 - 11
main/exercice/question_list_admin.inc.php

@@ -39,9 +39,9 @@ if ($deleteQuestion) {
     }
 </style>
 
-<div id="dialog-confirm" title="<?php echo get_lang("ConfirmYourChoice"); ?>">
+<div id="dialog-confirm" title="<?php echo get_lang("ConfirmYourChoice"); ?>" style="display:none;">
     <p>
-        <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;">
+        <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0; display:none;">
         </span>
         <?php echo get_lang("AreYouSureToDelete"); ?>
     </p>
@@ -129,9 +129,8 @@ $(function() {
 </script>
 <?php
 
-
 //we filter the type of questions we can add
-Question :: display_type_menu ($objExercise->feedback_type);
+Question :: display_type_menu($objExercise);
 echo '<div style="clear:both;"></div>';
 echo '<div id="message"></div>';
 $token = Security::get_token();
@@ -155,10 +154,7 @@ if (!$inATest) {
 
     echo '<div id="question_list">';
 	if ($nbrQuestions) {
-        $my_exercise = new Exercise();
-        //forces the query to the database
-        $my_exercise->read($_GET['exerciseId']);
-        $questionList=$my_exercise->selectQuestionList();
+        $questionList = $objExercise->selectQuestionList();                
 
         // Style for columns
 
@@ -181,8 +177,7 @@ if (!$inATest) {
 
 				$clone_link = '<a href="'.api_get_self().'?'.api_get_cidreq().'&clone_question='.$id.'">'.Display::return_icon('cd.gif',get_lang('Copy'), array(), ICON_SIZE_SMALL).'</a>';
 				$edit_link  = '<a href="'.api_get_self().'?'.api_get_cidreq().'&type='.$objQuestionTmp->selectType().'&myid=1&editQuestion='.$id.'">'.Display::return_icon('edit.png',get_lang('Modify'), array(), ICON_SIZE_SMALL).'</a>';
-				// this variable  $show_quiz_edition comes from admin.php blocks the exercise/quiz modifications
-				if ($show_quiz_edition) {
+				if ($objExercise->edit_exercise_in_lp == true) {
 				     $delete_link = '<a id="delete_'.$id.'" class="opener"  href="'.api_get_self().'?'.api_get_cidreq().'&exerciseId='.$exerciseId.'&deleteQuestion='.$id.'" >'.Display::return_icon('delete.png',get_lang('RemoveFromTest'), array(), ICON_SIZE_SMALL).'</a>';
 				}
 				$edit_link   = Display::tag('div', $edit_link,   array('style'=>'float:left; padding:0px; margin:0px'));
@@ -242,7 +237,7 @@ if (!$inATest) {
                         echo '<br />';
                         //echo get_lang('Level').': '.$objQuestionTmp->selectLevel();
                         echo '<br />';
-                        showQuestion($id, false, null, null, false, true, false, true, $my_exercise->feedback_type, true);
+                        showQuestion($id, false, null, null, false, true, false, true, $objExercise->feedback_type, true);
                         echo '</p>';
                     echo '</div>';
                 echo '</div>';

+ 4 - 3
main/exercice/question_pool.php

@@ -122,9 +122,10 @@ if ($is_allowedToEdit) {
 	}
 	// deletes a question from the database and all exercises
 	if ($delete) {
-		// construction of the Question object
+		// Construction of the Question object
+        $objQuestionTmp = Question::read($delete);
 		// if the question exists
-		if ($objQuestionTmp = Question::read($delete)) {
+		if ($objQuestionTmp) {
 			// deletes the question from all exercises
 			$objQuestionTmp->delete();
 		}
@@ -134,7 +135,7 @@ if ($is_allowedToEdit) {
 		// gets an existing question and copies it into a new exercise
 		$objQuestionTmp = Question :: read($recup);
 		// if the question exists
-		if($objQuestionTmp = Question :: read($recup)) {
+		if ($objQuestionTmp) {
 			// adds the exercise ID represented by $fromExercise into the list of exercises for the current question
 			$objQuestionTmp->addToList($fromExercise);
 		}

+ 3 - 3
main/exercice/savescores.php

@@ -54,7 +54,7 @@ function save_scores($file, $score) {
 	global $origin, $_user, $_cid,
 	$TABLETRACK_HOTPOTATOES;
 	// if tracking is disabled record nothing
-	$weighting = 100; // 100%	
+	$weighting = 100; // 100%
 	$date = api_get_utc_datetime();
 
 	if ($_user['user_id']) {
@@ -80,7 +80,7 @@ function save_scores($file, $score) {
 		//table to get tracking in there as well
 	    global $jscript2run;
 		//record the results in the learning path, using the SCORM interface (API)
-	    $jscript2run .= '<script>window.parent.API.void_save_asset('.$score.','.$weighting.');</script>';
+	    $jscript2run .= "<script>window.parent.API.void_save_asset('$score', '$weighting', 0, 'completed');</script>";
 	}
 }
 
@@ -88,7 +88,7 @@ function save_scores($file, $score) {
 save_scores($test, $score);
 
 // Back
-if ($origin != 'learnpath') {	
+if ($origin != 'learnpath') {
 	$url = "exercice.php"; // back to exercices
 	$jscript2run .= '<script>'."window.open('$url', '_top', '')".'</script>';
 	echo $jscript2run;

+ 20 - 6
main/exercice/stats.php

@@ -51,7 +51,10 @@ if (!empty($question_list)) {
 		$data[$question_id]['name'] 						= cut($question_obj->question, 100);
         $data[$question_id]['type'] 						= $question_obj->get_question_type_name();
 		//$data[$question_id]['students_who_try_exercise'] 	= $exercise_stats['users'];
-        $percentange = $count_users/$count_students*100;
+        $percentange = 0;
+        if ($count_students) {
+            $percentange = $count_users/$count_students*100;
+        }
         
         $data[$question_id]['students_who_try_exercise'] 	= Display::bar_progress($percentange, false, $count_users .' / '.$count_students);
                 
@@ -133,7 +136,10 @@ if (!empty($question_list)) {
                         
                         $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id(), FILL_IN_BLANKS, $answer_info_db, $answer_item);
                         
-                        $percentange = $count/$count_students*100;
+                        $percentange = 0;
+                        if (!empty($count_students)) {
+                            $percentange = $count/$count_students*100;
+                        }
                         $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
                     
                         $id++;
@@ -160,8 +166,10 @@ if (!empty($question_list)) {
                         $data[$id]['correct'] 	= $answer_info;
                         
                         $count = get_number_students_answer_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id(), MATCHING);
-                        
-                        $percentange = $count/$count_students*100;
+                        $percentange = 0;
+                        if (!empty($count_students)) {
+                            $percentange = $count/$count_students*100;
+                        }
                         $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
                     }                    
                     break;
@@ -175,7 +183,10 @@ if (!empty($question_list)) {
                     $data[$id]['correct'] 	= '-';
                     
                     $count = get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id());                    
-                    $percentange = $count/$count_students*100;
+                    $percentange = 0;
+                    if (!empty($count_students)) {
+                        $percentange = $count/$count_students*100;
+                    }
                     $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);                    
                     break;
                 default:
@@ -188,7 +199,10 @@ if (!empty($question_list)) {
                     $data[$id]['correct'] 	= $correct_answer;
                     
                     $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id());
-                    $percentange = $count/$count_students*100;
+                    $percentange = 0;
+                    if (!empty($count_students)) {
+                        $percentange = $count/$count_students*100;
+                    }
                     $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
             }            
             $id++;

+ 52 - 0
main/exercice/testcategory.class.php

@@ -527,6 +527,58 @@ class Testcategory {
         }        
         return $html;
     }
+
+/**     
+     * Returns a category summary report
+     * @params int exercise id
+     * @params array prefilled array with the category_id, score, and weight example: array(1 => array('score' => '10', 'total' => 20));
+     */
+    public static function get_stats_table_by_attempt($exercise_id, $category_list = array()) {
+        if (empty($category_list)) {
+            return null;
+        }          
+        $category_name_list = Testcategory::getListOfCategoriesNameForTest($exercise_id);
+                
+        $table = new HTML_Table(array('class' => 'data_table'));
+        $table->setHeaderContents(0, 0, get_lang('Categories'));
+        $table->setHeaderContents(0, 1, get_lang('AbsoluteScore'));
+        $table->setHeaderContents(0, 2, get_lang('RelativeScore'));
+        $row = 1;
+        
+        $none_category = array();
+        if (isset($category_list['none'])) {
+            $none_category = $category_list['none'];                    
+            unset($category_list['none']);            
+        }
+        
+        $total = array();
+        if (isset($category_list['total'])) {
+            $total = $category_list['total'];
+            unset($category_list['total']);
+        }
+        if (count($category_list) > 1) {
+            foreach ($category_list as $category_id => $category_item) {            
+                $table->setCellContents($row, 0, $category_name_list[$category_id]);
+                $table->setCellContents($row, 1, show_score($category_item['score'], $category_item['total'], false));            
+                $table->setCellContents($row, 2, show_score($category_item['score'], $category_item['total'], true, false, true));
+                $row++;
+            }
+
+            if (!empty($none_category)) {
+                $table->setCellContents($row, 0, get_lang('None'));
+                $table->setCellContents($row, 1, show_score($none_category['score'], $none_category['total'], false));            
+                $table->setCellContents($row, 2, show_score($none_category['score'], $none_category['total'], true, false, true));
+                $row++;
+            }
+            if (!empty($total)) {
+                $table->setCellContents($row, 0, get_lang('Total'));
+                $table->setCellContents($row, 1, show_score($total['score'], $total['total'], false));
+                $table->setCellContents($row, 2, show_score($total['score'], $total['total'], true, false, true));
+            }
+            return $table->toHtml();
+        }
+        return null;
+    }
     
     
     

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

@@ -44,8 +44,8 @@ class UniqueAnswer extends Question {
 	 * @param the answers number to display
 	 */
 	function createAnswersForm ($form) {
-		// getting the exercise list
-		$obj_ex =$_SESSION['objExercise'];
+		// Getting the exercise list
+		$obj_ex = $_SESSION['objExercise'];
 
 		$editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125');
 
@@ -227,10 +227,10 @@ class UniqueAnswer extends Question {
         
 		$navigator_info = api_get_navigator();
 
-		global $text, $class, $show_quiz_edition;
+		global $text, $class;
         
 		//ie6 fix
-		if ($show_quiz_edition) {
+		if ($obj_ex->edit_exercise_in_lp == true) {
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {                
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"'); 

+ 40 - 40
main/exercice/unique_answer_no_option.class.php

@@ -46,7 +46,7 @@ class UniqueAnswerNoOption extends Question {
 	 */
 	function createAnswersForm ($form) {
 		// getting the exercise list
-		$obj_ex =$_SESSION['objExercise'];
+		$obj_ex = $_SESSION['objExercise'];
 
 		$editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125');
 
@@ -213,53 +213,53 @@ class UniqueAnswerNoOption extends Question {
         
         //Adding the "I don't know" question answer
         //if (empty($this -> id)) {
-            $i = 666;        
-            $form -> addElement ('html', '<tr>'); 
-    
-            $defaults['answer['.$i.']']     = get_lang('DontKnow');
-            $defaults['weighting['.$i.']']  = 0;
-            $defaults['scenario']=$temp_scenario;
-            $renderer = & $form->defaultRenderer();
-            
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']'); 
-             
-            $answer_number=$form->addElement('text', 'counter['.$i.']',null,'value="-"');
-            $answer_number->freeze();
-            
-            $form->addElement('hidden', 'position['.$i.']', '666');
-    
-            $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
-            $form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-         
-            $form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
-       
-    
-            if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
-                // feedback
-                $form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-            } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {                    
+        $i = 666;        
+        $form -> addElement ('html', '<tr>'); 
 
-            }
-    
-            //$form->addElement('select', 'destination'.$i, get_lang('SelectQuestion').' : ',$select_question,'multiple');
-    
-            $form->addElement('text', 'weighting['.$i.']', null, array('class' => "span1", 'value' => '0', 'readonly' =>'readonly'));
-            $form->addElement ('html', '</tr>');
-        
-         //}
+        $defaults['answer['.$i.']']     = get_lang('DontKnow');
+        $defaults['weighting['.$i.']']  = 0;
+        $defaults['scenario']=$temp_scenario;
+        $renderer = & $form->defaultRenderer();
+
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');  
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');  
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']'); 
+
+        $answer_number=$form->addElement('text', 'counter['.$i.']',null,'value="-"');
+        $answer_number->freeze();
+
+        $form->addElement('hidden', 'position['.$i.']', '666');
+
+        $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
+        $form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
+
+        $form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
+
+
+        if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
+            // feedback
+            $form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
+        } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {                    
+
+        }
+
+        //$form->addElement('select', 'destination'.$i, get_lang('SelectQuestion').' : ',$select_question,'multiple');
+
+        $form->addElement('text', 'weighting['.$i.']', null, array('class' => "span1", 'value' => '0', 'readonly' =>'readonly'));
+        $form->addElement ('html', '</tr>');
+
+     //}
     
        
 		$form -> addElement ('html', '</table>');
 		$form -> addElement ('html', '<br />');
 		$navigator_info = api_get_navigator();
 
-		global $text, $class, $show_quiz_edition;
+		global $text, $class;
 		//ie6 fix
-		if ($show_quiz_edition) {
+		if ($obj_ex->edit_exercise_in_lp == true) {
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {                
                 $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');                
 				$form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');

+ 30 - 31
main/exercice/upload_exercise.php

@@ -3,7 +3,7 @@
 /**
  * 	Upload quiz: This script shows the upload quiz feature
  *  Initial work by Isaac flores on Nov 4 of 2010
- *  Encoding fixes Julio Montoya 
+ *  Encoding fixes Julio Montoya
  * 	@package chamilo.exercise
  */
 /**
@@ -87,26 +87,23 @@ function lp_upload_quiz_secondary_actions() {
 }
 
 function lp_upload_quiz_main() {
-        
+
     // variable initialisation
     $lp_id = Security::remove_XSS($_GET['lp_id']);
-    
-    $form = new FormValidator('upload', 'POST', api_get_self() . '?' . api_get_cidreq() . '&lp_id=' . $lp_id, '', 'enctype="multipart/form-data"');
-    $form->addElement('html', '<div><h3>' .Display::return_icon('import_excel.png', get_lang('ImportExcelQuiz'), array('style'=>'margin-bottom:-2px;'),ICON_SIZE_MEDIUM). get_lang('ImportExcelQuiz') . '</h3></div>');
-    $form->addElement('file', 'user_upload_quiz', '');
+
+    $form = new FormValidator('upload', 'POST', api_get_self() . '?' . api_get_cidreq() . '&lp_id=' . $lp_id, '', array('enctype' => 'multipart/form-data'));
+    $form->addElement('header', get_lang('ImportExcelQuiz'));
+    $form->addElement('file', 'user_upload_quiz', get_lang('FileUpload'));
+
+    $link = '<a href="../exercice/quiz_template.xls">'.Display::return_icon('export_excel.png', get_lang('DownloadExcelTemplate'),null,16).get_lang('DownloadExcelTemplate');
+
+    $form->addElement('advanced_settings', $link);
+
     //button send document
     $form->addElement('style_submit_button', 'submit_upload_quiz', get_lang('Send'), 'class="upload"');
-    
+
     // Display the upload field
-    echo '<table style="text-align: left; width: 100%;" border="0" cellpadding="2"cellspacing="2"><tbody><tr>';
-    echo '<td style="vertical-align: top; width: 25%;">';
-    echo '<a href="../exercice/quiz_template.xls">'.Display::return_icon('export_excel.png', get_lang('DownloadExcelTemplate'),null,16).get_lang('DownloadExcelTemplate').'';
-    echo '</a>';
-    echo '</td>';
-    echo '</tr>';
-    echo '<tr><td>';
     $form->display();
-    echo '</td></tr></tbody></table>';
 }
 
 /**
@@ -129,7 +126,7 @@ function lp_upload_quiz_action_handling() {
     $data->setOutputEncoding(api_get_system_encoding());
     // Reading the xls document.
     $data->read($_FILES['user_upload_quiz']['tmp_name']);
- 
+
     // Variables
     $quiz_index = 0;
     $question_title_index = array();
@@ -197,7 +194,7 @@ function lp_upload_quiz_action_handling() {
             $l++;
         }
     }
-    
+
     // Get answers
     for ($i = 0; $i < count($question_name_index_init); $i++) {
         for ($j = $question_name_index_init[$i]; $j <= $question_name_index_end[$i]; $j++) {
@@ -217,33 +214,35 @@ function lp_upload_quiz_action_handling() {
             }
         }
     }
-    
+
     $quiz_title = $quiz[2]; // Quiz title
-    
+
     if ($quiz_title != '') {
         // Variables
         $type = 2;
         $random = $active = $results = $max_attempt = $expired_time = 0;
         //make sure feedback is enabled (3 to disable), otherwise the fields
         // added to the XLS are not shown, which is confusing
-        $feedback = 0; 
+        $feedback = 0;
         // Quiz object
-        $quiz_object = new Exercise();        
+        $quiz_object = new Exercise();
         $quiz_id = $quiz_object->create_quiz($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback);
-        
-        if ($quiz_id) {           
-        
+
+        if ($quiz_id) {
+
             // insert into the item_property table
             api_item_property_update($_course, TOOL_QUIZ, $quiz_id, 'QuizAdded', api_get_user_id());
-            
+
             // Import questions
             for ($i = 0; $i < $number_questions; $i++) {
                 // Create questions
                 $question_title = $question[$i][2]; // Question name
+                // Unique answers are the only question types available for now
+                // through xls-format import
+                $unique_answer = new UniqueAnswer();
                 if ($question_title != '') {
-                    $question_id = Question::create_question($quiz_id, ($question_title));
+                    $question_id = $unique_answer->create_question($quiz_id, ($question_title));
                 }
-                $unique_answer = new UniqueAnswer();
                 if (is_array($new_answer[$i])) {
                     $id = 1;
                     $answers_data = $new_answer[$i];
@@ -257,7 +256,7 @@ function lp_upload_quiz_action_handling() {
                             $score = $score_list[$i][3];
                             $comment = $feedback_true_list[$i][2];
                         } else {
-                            $comment = $feedback_false_list[$i][2];                    	
+                            $comment = $feedback_false_list[$i][2];
                         }
     /*
                         if ($id == 1) {
@@ -297,7 +296,7 @@ function lp_upload_quiz_action_handling() {
             }
         }
         if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
-        	
+
             $previous = $_SESSION['oLP']->select_previous_item_id();
             $parent = 0;
             // Add a Quiz as Lp Item
@@ -306,7 +305,7 @@ function lp_upload_quiz_action_handling() {
             header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id']).'&session_id='.api_get_session_id());
             exit;
         } else {
-            //  header('location: exercice.php?' . api_get_cidreq());	
+            //  header('location: exercice.php?' . api_get_cidreq());
             echo '<script>window.location.href = "admin.php?'.api_get_cidReq().'&exerciseId='.$quiz_id.'&session_id='.api_get_session_id().'"</script>';
         }
     }
@@ -316,4 +315,4 @@ function lp_upload_quiz_action_handling() {
 if ($origin != 'learnpath') {
     //so we are not in learnpath tool
     Display :: display_footer();
-}
+}

+ 1 - 1
main/forum/viewthread.php

@@ -72,7 +72,7 @@ if ($origin == 'group') {
     if ($origin == 'learnpath') {
         Display::display_reduced_header();
     } else {    	
-        $interbreadcrumb[] = array('url' => 'index.php?gradebook='.$gradebook.'&amp;search='.Security::remove_XSS(urlencode($my_search)), 'name' => $nameTools);
+        $interbreadcrumb[] = array('url' => 'index.php?'.(isset($gradebook)?'gradebook='.$gradebook.'&amp;':'').'search='.Security::remove_XSS(urlencode($my_search)), 'name' => $nameTools);
         $interbreadcrumb[] = array('url' => 'viewforumcategory.php?forumcategory='.$current_forum_category['cat_id'].'&amp;origin='.$origin.'&amp;search='.Security::remove_XSS(urlencode($my_search)), 'name' => Security::remove_XSS($current_forum_category['cat_title']));
         $interbreadcrumb[] = array('url' => 'viewforum.php?forum='.Security::remove_XSS($_GET['forum']).'&amp;origin='.$origin.'&amp;search='.Security::remove_XSS(urlencode($my_search)), 'name' => Security::remove_XSS($current_forum['forum_title']));
         $interbreadcrumb[] = array('url' => '#', 'name' => Security::remove_XSS($current_thread['thread_title']));

+ 4 - 2
main/forum/viewthread_threaded.inc.php

@@ -272,8 +272,10 @@ if (!empty($attachment_list)) {
 }
 
 // The post has been displayed => it can be removed from the what's new array
-unset($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]);
-unset($_SESSION['whatsnew_post_info'][$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]);
+if (isset($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']])) {
+  unset($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]);
+  unset($_SESSION['whatsnew_post_info'][$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]);
+}
 echo "</table>";
 
 // 		Displaying the thread (structure)

+ 1 - 6
main/gradebook/gradebook_edit_cat.php

@@ -19,13 +19,11 @@ block_students();
 
 $edit_cat = isset($_REQUEST['editcat']) ? $_REQUEST['editcat'] : '';
 
-
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
 $htmlHeadXtra[] = '<link  href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 
 $htmlHeadXtra[] = '<script type="text/javascript">
-$(document).ready(function () {
-
+$(document).ready(function() {
     $("#skills").fcbkcomplete({
         json_url: "'.api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=find_skills",
         cache: false,
@@ -112,9 +110,6 @@ if ($form->validate()) {
 	$cat->set_skills($values['skills']);    
 	$cat->set_user_id($values['hid_user_id']);
 	$cat->set_parent_id($values['hid_parent_id']);
-    
-    //$cat->update_children_weight($values['weight']);
-    
 	$cat->set_weight($values['weight']);
     
 	if ($values['hid_parent_id'] == 0 ) {

+ 23 - 12
main/gradebook/lib/fe/catform.class.php

@@ -129,18 +129,29 @@ class CatForm extends FormValidator {
         if (empty($links)) {
             $grade_model_id    = 0;
         }
-    
-   		$this->setDefaults(array(
-			'name' 				=> $this->category_object->get_name(),
-    		'description' 		=> $this->category_object->get_description(),
-    		'hid_user_id' 		=> $this->category_object->get_user_id(),
-    		'hid_parent_id' 	=> $this->category_object->get_parent_id(),
-            'grade_model_id' 	=> $grade_model_id,
-    		'skills'            => $skills,
-   	 		'weight' 			=> $this->category_object->get_weight(),
-   	 		'visible' 			=> $this->category_object->is_visible(),
-   	 		'certif_min_score'  => $this->category_object->get_certificate_min_score(),
-    		));
+        
+        $category_name = $this->category_object->get_name();      
+          
+        //The main course category:
+        if (isset($this->category_object) && $this->category_object->get_parent_id() == 0) {
+            if (empty($category_name)) {
+                $category_name = $course_code;
+            }
+        }
+        
+   		$this->setDefaults(
+            array(
+                'name' 				=> $category_name,
+                'description' 		=> $this->category_object->get_description(),
+                'hid_user_id' 		=> $this->category_object->get_user_id(),
+                'hid_parent_id' 	=> $this->category_object->get_parent_id(),
+                'grade_model_id' 	=> $grade_model_id,
+                'skills'            => $skills,
+                'weight' 			=> $this->category_object->get_weight(),
+                'visible' 			=> $this->category_object->is_visible(),
+                'certif_min_score'  => $this->category_object->get_certificate_min_score(),
+            )
+        );
    		$this->addElement('hidden','hid_id', $this->category_object->get_id());
    		$this->addElement('hidden','course_code', $this->category_object->get_course_code());
 		$this->build_basic_form();

+ 34 - 169
main/group/group.php

@@ -45,7 +45,7 @@ if (api_get_setting('allow_group_categories') == 'false') {
 	$num = Database::num_rows($res);
 	if ($num == 0) {
 		$sql = "INSERT INTO ".$cat_table." ( c_id, id , title , description , forum_state, wiki_state, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order) 
-		VALUES ($course_id, '2', '".lang2db($DefaultGroupCategory)."', '', '1', '1', '8', '0', '0', '0', '0');";
+		VALUES ($course_id, '2', '".lang2db(get_lang('DefaultGroupCategory'))."', '', '1', '1', '8', '0', '0', '0', '0');";
 		Database::query ($sql);
 	}
 }
@@ -173,7 +173,8 @@ if (api_is_allowed_to_edit(false, true)) {
 	echo '<a href="../user/user.php?'.api_get_cidreq().'">'.Display::return_icon('user.png', get_lang('GoTo').' '.get_lang('Users'),'',ICON_SIZE_MEDIUM).'</a>';	
 }
 
-$group_cats = GroupManager :: get_categories();
+$group_cats = GroupManager :: get_categories(api_get_course_id());
+
 if (api_get_setting('allow_group_categories') == 'true' && count($group_cats) > 1) {	
 	echo ' <a href="?'.api_get_cidreq().'&show_all=1">'.Display::return_icon('group.png',get_lang('ShowAll'),'',ICON_SIZE_MEDIUM).'</a>';
 }
@@ -183,176 +184,40 @@ echo '</div>';
  * List all categories
  */
 
-
-foreach ($group_cats as $index => $category) {
-	$group_list = array ();
-	$in_category = false;
-	if (api_get_setting('allow_group_categories') == 'true') {
-		
-		if (isset ($_GET['show_all']) || (isset ($_GET['category']) && $_GET['category'] == $category['id'])) {
-			echo '<img src="../img/folder_group_category.gif" alt=""/>';
-			echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'">'.$category['title'].'</a>';
-			$in_category = true;
-		} else {
-			echo '<img src="../img/folder_document.gif" alt=""/>';
-			echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'&amp;category='.$category['id'].'">'.$category['title'].'</a>';
-		}
-		$group_list = GroupManager :: get_group_list($category['id']);
-		echo ' ('.count($group_list).' '.get_lang('ExistingGroups').')';
-		if (api_is_allowed_to_edit(false, true)) {
-			echo '<a href="group_category.php?'.api_get_cidreq().'&id='.$category['id'].'"  title="'.get_lang('Edit').'">'.Display::return_icon('settings.png', get_lang('EditGroup'),'',ICON_SIZE_SMALL).'</a>';
-			echo '<a href="group.php?'.api_get_cidreq().'&action=delete_category&amp;id='.$category['id'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
-			if ($index != 0) {
-				echo ' <a href="group.php?'.api_get_cidreq().'&action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index -1]['id'].'">'.Display::return_icon('up.png','&nbsp;','',ICON_SIZE_SMALL).'</a>';
-
-			}
-			if ($index != count($group_cats) - 1) {
-				echo ' <a href="group.php?'.api_get_cidreq().'&action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index +1]['id'].'">'.Display::return_icon('down.png','&nbsp;','',ICON_SIZE_SMALL).'</a>';
-			}
-		}
-		echo '<p style="margin: 0px;margin-left: 50px;">'.$category['description'].'</p><p/>';
-	} else {
-		$group_list = GroupManager :: get_group_list();        
-		$in_category = true;
-	}
-
-	//if (count($group_list) > 0 && $in_category)
-	
-	if ($in_category) {
-		$totalRegistered = 0;
-				
-		$group_data = array();
-		
-		foreach ($group_list as $index => $this_group) {		    
-
-			// Validacion when belongs to a session
-			$session_img = api_get_session_image($this_group['session_id'], $_user['status']);
-
-			// All the tutors of this group
-			$tutorsids_of_group = GroupManager::get_subscribed_tutors($this_group['id'], true);
-
-			// Create a new table-row
-			$row = array ();
-			// Checkbox
-			if (api_is_allowed_to_edit(false,true) && count($group_list) > 1) {
-				$row[] = $this_group['id'];
-			}
-
-			// Group name
-			if ((api_is_allowed_to_edit(false, true) ||
-					in_array($_user['user_id'], $tutorsids_of_group) ||
-					$this_group['is_member'] ||
-					GroupManager::user_has_access($_user['user_id'], $this_group['id'], GroupManager::GROUP_TOOL_FORUM) ||
-					GroupManager::user_has_access($_user['user_id'], $this_group['id'], GroupManager::GROUP_TOOL_DOCUMENTS) ||
-					GroupManager::user_has_access($_user['user_id'], $this_group['id'], GroupManager::GROUP_TOOL_CALENDAR) ||
-					GroupManager::user_has_access($_user['user_id'], $this_group['id'], GroupManager::GROUP_TOOL_ANNOUNCEMENT) ||
-					GroupManager::user_has_access($_user['user_id'], $this_group['id'], GroupManager::GROUP_TOOL_WORK) ||
-					GroupManager::user_has_access($_user['user_id'], $this_group['id'], GroupManager::GROUP_TOOL_WIKI))
-					&& !(api_is_course_coach() && intval($this_group['session_id']) != intval($_SESSION['id_session']))) {
-				$orig = isset($origin) ? $origin : null;
-				$group_name = '<a href="group_space.php?cidReq='.api_get_course_id().'&amp;origin='.$orig.'&amp;gidReq='.$this_group['id'].'">'.Security::remove_XSS($this_group['name']).'</a>';
-				if (!empty($_SESSION['_user']['user_id']) && !empty($this_group['id_tutor']) && $_SESSION['_user']['user_id'] == $this_group['id_tutor']) {
-					$group_name .= ' ('.get_lang('OneMyGroups').')';
-				} elseif ($this_group['is_member']) {
-					$group_name .= ' ('.get_lang('MyGroup').')';
-				}
-				if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
-					$group_name .= ' ('.$this_group['session_name'].')';
-				}
-				$group_name .= $session_img;
-				$row[] = $group_name.'<br />'.stripslashes(trim($this_group['description']));
-			} else {
-				$row[] = $this_group['name'].'<br />'.stripslashes(trim($this_group['description']));
-			}                      
-            
-            // Tutor name
-            $tutor_info = '';
-
-            if (count($tutorsids_of_group) > 0) {
-                foreach ($tutorsids_of_group as $tutor_id) {
-                    $tutor = api_get_user_info($tutor_id);
-                    $username = api_htmlentities(sprintf(get_lang('LoginX'), $tutor['username']), ENT_QUOTES);
-                    if (api_get_setting('show_email_addresses') == 'true') {
-                        $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title'=>$username)).', ';
-                    } else {
-                        if (api_is_allowed_to_edit()) {
-                            $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title'=>$username)).', ';
-                        } else {
-                            $tutor_info .= Display::tag('span', api_get_person_name($tutor['firstName'], $tutor['lastName']), array('title'=>$username)).', ';
-                        }
-                    }
-                }
+if (api_get_setting('allow_group_categories') == 'true') {
+    foreach ($group_cats as $index => $category) {
+        if (isset ($_GET['show_all']) || (isset ($_GET['category']) && $_GET['category'] == $category['id'])) {
+            //echo '<img src="../img/folder_group_category.gif" alt=""/>';
+            //echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'">'.$category['title'].'</a>';            
+        } else {
+            //echo '<img src="../img/folder_document.gif" alt=""/>';
+            //echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'&amp;category='.$category['id'].'">'.$category['title'].'</a>';
+            //echo Display::page_header($category['title']);            
+        }
+        $group_list = GroupManager :: get_group_list($category['id']);
+        $label = Display::label(count($group_list).' '.get_lang('ExistingGroups'), 'info');
+        
+        $actions = null;
+        if (api_is_allowed_to_edit(false, true)) {
+            $actions .= '<a href="group_category.php?'.api_get_cidreq().'&id='.$category['id'].'"  title="'.get_lang('Edit').'">'.Display::return_icon('edit.png', get_lang('EditGroup'),'',ICON_SIZE_SMALL).'</a>';
+            $actions .= '<a href="group.php?'.api_get_cidreq().'&action=delete_category&amp;id='.$category['id'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
+            if ($index != 0) {
+                $actions .=  ' <a href="group.php?'.api_get_cidreq().'&action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index -1]['id'].'">'.Display::return_icon('up.png','&nbsp;','',ICON_SIZE_SMALL).'</a>';
             }
-            $tutor_info = api_substr($tutor_info, 0, api_strlen($tutor_info) - 2);
-            $row[] = $tutor_info;
-            
-		
-            // Max number of members in group
-            $max_members = ($this_group['maximum_number_of_members'] == GroupManager::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / '.$this_group['maximum_number_of_members']);
-            
-            
-			// Number of members in group
-			$row[] = $this_group['number_of_members'].$max_members;
-			
-            // Self-registration / unregistration
-            if (!api_is_allowed_to_edit(false, true)) {
-                if (GroupManager :: is_self_registration_allowed($_user['user_id'], $this_group['id'])) {
-                    $row[] = '<a class = "btn" href="group.php?'.api_get_cidreq().'&category='.$category['id'].'&amp;action=self_reg&amp;group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."'".')) return false;">'.get_lang('GroupSelfRegInf').'</a>';
-                } elseif (GroupManager :: is_self_unregistration_allowed($_user['user_id'], $this_group['id'])) {
-                    $row[] = '<a class = "btn" href="group.php?'.api_get_cidreq().'&category='.$category['id'].'&amp;action=self_unreg&amp;group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."'".')) return false;">'.get_lang('GroupSelfUnRegInf').'</a>';
-                } else {
-                    $row[] = '-';
-                }
+            if ($index != count($group_cats) - 1) {
+                $actions .= ' <a href="group.php?'.api_get_cidreq().'&action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index +1]['id'].'">'.Display::return_icon('down.png','&nbsp;','',ICON_SIZE_SMALL).'</a>';
             }
-
-			// Edit-links
-			if (api_is_allowed_to_edit(false, true)  && !(api_is_course_coach() && intval($this_group['session_id']) != intval($_SESSION['id_session']))) {
-				$edit_actions = '<a href="group_edit.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'"  title="'.get_lang('Edit').'">'.Display::return_icon('edit.png', get_lang('EditGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';								
-				$edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category['id'].'&amp;action=empty_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('EmptyGroup').'">'.Display::return_icon('clean.png',get_lang('EmptyGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';				
-				$edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category['id'].'&amp;action=fill_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('FillGroup').'">'.Display::return_icon('fill.png',get_lang('FillGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
-				$edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category['id'].'&amp;action=delete_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
-				$row[] = $edit_actions;
-			}
-			if (!empty($this_group['nbMember'])) {
-				$totalRegistered = $totalRegistered + $this_group['nbMember'];
-			}
-
-			$group_data[] = $row;
-		} // while loop
-		if (isset ($_GET['show_all'])) {
-			$paging_options = array('per_page' => count($group_data));
-		} else {
-			$paging_options = array ();
-		}
-		$table = new SortableTableFromArrayConfig($group_data, 1);
-		$my_cat = isset($_GET['category']) ? Security::remove_XSS($_GET['category']) : null;
-		$table->set_additional_parameters(array('category' => $my_cat));
-		$column = 0;
-		if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) {
-			$table->set_header($column++, '', false);
-		}
-		$table->set_header($column++, get_lang('Groups'));
-        $table->set_header($column++, get_lang('GroupTutor'));
-        		
-		$table->set_header($column++, get_lang('Registered'), false);
-		
-		if (!api_is_allowed_to_edit(false, true)) { // If self-registration allowed
-            $table->set_header($column++, get_lang('GroupSelfRegistration'), false);
         }
-		//$table->set_header($column++, get_lang('MaximumOfParticipants'));
-		
-		if (api_is_allowed_to_edit(false, true)) { // Only for course administrator
-			$table->set_header($column++, get_lang('Modify'), false);
-			$form_actions = array();
-            $form_actions['fill_selected'] = get_lang('FillGroup');
-			$form_actions['empty_selected'] = get_lang('EmptyGroup');
-            $form_actions['delete_selected'] = get_lang('Delete');
-			if (count($group_list) > 1) {
-				$table->set_form_actions($form_actions, 'group');
-			}
-		}
-		$table->display();
-	}
+        
+        echo Display::page_header($category['title'].' '. $label.' '.$actions);
+        
+        echo '<p style="margin: 0px;margin-left: 50px;">'.$category['description'].'</p><p/>';
+        
+        GroupManager ::process_groups($group_list, $category['id']);        
+    }
+} else {
+    $group_list = GroupManager :: get_group_list();            
+    GroupManager ::process_groups($group_list);
 }
 
 /*	FOOTER */

+ 6 - 6
main/group/group_category.php

@@ -104,14 +104,14 @@ $form->addElement('hidden', 'action');
 
 // Groups per user
 $group = array ();
-$group[] = & $form->createElement('static', null, null, get_lang('QtyOfUserCanSubscribe_PartBeforeNumber'));
+$group[] = $form->createElement('static', null, null, get_lang('QtyOfUserCanSubscribe_PartBeforeNumber'));
 $possible_values = array ();
 for ($i = 1; $i <= 10; $i ++) {
 	$possible_values[$i] = $i;
 }
 $possible_values[GroupManager::GROUP_PER_MEMBER_NO_LIMIT] = get_lang('All');
-$group[] = & $form->createElement('select', 'groups_per_user', null, $possible_values);
-$group[] = & $form->createElement('static', null, null, get_lang('QtyOfUserCanSubscribe_PartAfterNumber'));
+$group[] = $form->createElement('select', 'groups_per_user', null, $possible_values);
+$group[] = $form->createElement('static', null, null, get_lang('QtyOfUserCanSubscribe_PartAfterNumber'));
 $form->addGroup($group, 'limit_group', get_lang('GroupLimit'), ' ', false);
 $form->addRule('limit_group', get_lang('MaxGroupsPerUserInvalid'), 'callback', 'check_groups_per_user');
 // Default settings for new groups
@@ -123,9 +123,9 @@ $form->addElement('html', '</div>');
 // Members per group
 $form->addElement('radio', 'max_member_no_limit', get_lang('GroupLimit'), get_lang('NoLimit'), GroupManager::MEMBER_PER_GROUP_NO_LIMIT);
 $group = array ();
-$group[] = & $form->createElement('radio', 'max_member_no_limit', null, get_lang('MaximumOfParticipants'), 1);
-$group[] = & $form->createElement('text', 'max_member', null, array ('size' => 2));
-$group[] = & $form->createElement('static', null, null, get_lang('GroupPlacesThis'));
+$group[] = $form->createElement('radio', 'max_member_no_limit', null, get_lang('MaximumOfParticipants'), 1);
+$group[] = $form->createElement('text', 'max_member', null, array ('size' => 2));
+$group[] = $form->createElement('static', null, null, get_lang('GroupPlacesThis'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 $form->addRule('max_member_group', get_lang('InvalidMaxNumberOfMembers'), 'callback', 'check_max_number_of_members');
 

+ 31 - 32
main/group/group_creation.php

@@ -140,7 +140,7 @@ elseif (isset($_POST['number_of_groups'])) {
 		$form = new FormValidator('create_groups_step2');
 
 		// Modify the default templates
-		$renderer = & $form->defaultRenderer();
+		$renderer = $form->defaultRenderer();
 		$form_template = "<form {attributes}>\n<div>\n<table>\n{content}\n</table>\n</div>\n</form>";
 		$renderer->setFormTemplate($form_template);
 		$element_template = <<<EOT
@@ -160,32 +160,32 @@ EOT;
 		$defaults = array ();
 		// Table heading
 		$group_el = array ();
-		$group_el[] = & $form->createElement('static', null, null, '<b>'.get_lang('GroupName').'</b>');
+		$group_el[] =$form->createElement('static', null, null, '<b>'.get_lang('GroupName').'</b>');
 		if (api_get_setting('allow_group_categories') == 'true') {
-			$group_el[] = & $form->createElement('static', null, null, '<b>'.get_lang('GroupCategory').'</b>');
+			$group_el[] = $form->createElement('static', null, null, '<b>'.get_lang('GroupCategory').'</b>');
 		}
-		//$group_el[] = & $form->createElement('static', null, null, '<b>'.get_lang('GroupTutor').'</b>');
-		$group_el[] = & $form->createElement('static', null, null, '<b>'.get_lang('GroupPlacesThis').'</b>');
+		//$group_el[] = $form->createElement('static', null, null, '<b>'.get_lang('GroupTutor').'</b>');
+		$group_el[] = $form->createElement('static', null, null, '<b>'.get_lang('GroupPlacesThis').'</b>');
 		$form->addGroup($group_el, 'groups', null, "\n</td>\n<td>\n", false);
 		// Checkboxes
 		if ($_POST['number_of_groups'] > 1) {
 			$group_el = array ();
-			$group_el[] = & $form->createElement('static', null, null, ' ');
+			$group_el[] = $form->createElement('static', null, null, ' ');
 			if (api_get_setting('allow_group_categories') == 'true') {
-				$group_el[] = & $form->createElement('checkbox', 'same_category', null, get_lang('SameForAll'), array('onclick' => "javascript: switch_state('category');"));
+				$group_el[] = $form->createElement('checkbox', 'same_category', null, get_lang('SameForAll'), array('onclick' => "javascript: switch_state('category');"));
 			}
-			//$group_el[] = & $form->createElement('checkbox', 'same_tutor', null, get_lang('SameForAll'), array ('onclick' => "javascript: switch_state('tutor');"));
-			$group_el[] = & $form->createElement('checkbox', 'same_places', null, get_lang('SameForAll'), array ('onclick' => "javascript: switch_state('places');"));
+			//$group_el[] = $form->createElement('checkbox', 'same_tutor', null, get_lang('SameForAll'), array ('onclick' => "javascript: switch_state('tutor');"));
+			$group_el[] = $form->createElement('checkbox', 'same_places', null, get_lang('SameForAll'), array ('onclick' => "javascript: switch_state('places');"));
 			$form->addGroup($group_el, 'groups', null, '</td><td>', false);
 		}
 		// Properties for all groups
 		for ($group_number = 0; $group_number < $_POST['number_of_groups']; $group_number ++) {
 			$group_el = array ();
-			$group_el[] = & $form->createElement('text', 'group_'.$group_number.'_name');
+			$group_el[] = $form->createElement('text', 'group_'.$group_number.'_name');
 			if (api_get_setting('allow_group_categories') == 'true') {
-				$group_el[] = & $form->createElement('select', 'group_'.$group_number.'_category', null, $cat_options, array('id' => 'category_'.$group_number));
+				$group_el[] = $form->createElement('select', 'group_'.$group_number.'_category', null, $cat_options, array('id' => 'category_'.$group_number));
 			}			
-			$group_el[] = & $form->createElement('text', 'group_'.$group_number.'_places', null, array('class' => 'span1', 'id' => 'places_'.$group_number));
+			$group_el[] = $form->createElement('text', 'group_'.$group_number.'_places', null, array('class' => 'span1', 'id' => 'places_'.$group_number));
 
 			if ($_POST['number_of_groups'] < 10000) {
 				if ($group_id < 10) {
@@ -220,10 +220,10 @@ EOT;
 		$create_groups_form = new FormValidator('create_groups');
 		$create_groups_form->addElement('header', '', $nameTools);
 		$group_el = array ();
-		$group_el[] = & $create_groups_form->createElement('static', null, null, get_lang('Create'));
-		$group_el[] = & $create_groups_form->createElement('text', 'number_of_groups', null, array('class' => 'span1'));
-		$group_el[] = & $create_groups_form->createElement('static', null, null, get_lang('NewGroups'));
-		$group_el[] = & $create_groups_form->createElement('style_submit_button', 'submit', get_lang('ProceedToCreateGroup'), 'class="save"');
+		$group_el[] = $create_groups_form->createElement('static', null, null, get_lang('Create'));
+		$group_el[] = $create_groups_form->createElement('text', 'number_of_groups', null, array('class' => 'span1'));
+		$group_el[] = $create_groups_form->createElement('static', null, null, get_lang('NewGroups'));
+		$group_el[] = $create_groups_form->createElement('style_submit_button', 'submit', get_lang('ProceedToCreateGroup'), 'class="save"');
 		$create_groups_form->addGroup($group_el, 'create_groups', null, ' ', false);
 		$defaults = array();
 		$defaults['number_of_groups'] = 1;
@@ -262,39 +262,38 @@ EOT;
 				$base_group_options[$group['id']] = $group['name'].' ('.$number_of_students.' '.get_lang('Users').')';
 			}
 		}
-		if (count($base_group_options) > 0) {
-			echo '<b>'.get_lang('CreateSubgroups').'</b>';
-			echo '<blockquote>';
-			echo '<p>'.get_lang('CreateSubgroupsInfo').'</p>';
+		if (count($base_group_options) > 0) {			
 			$create_subgroups_form = new FormValidator('create_subgroups');
+            $create_subgroups_form->addElement('header', get_lang('CreateSubgroups'));
+            $create_subgroups_form->addElement('html', get_lang('CreateSubgroupsInfo'));
 			$create_subgroups_form->addElement('hidden', 'action');
 			$group_el = array();
-			$group_el[] = & $create_subgroups_form->createElement('static', null, null, get_lang('CreateNumberOfGroups'));
-			$group_el[] = & $create_subgroups_form->createElement('text', 'number_of_groups', null, array('size' => 3));
-			$group_el[] = & $create_subgroups_form->createElement('static', null, null, get_lang('WithUsersFrom'));
-			$group_el[] = & $create_subgroups_form->createElement('select', 'base_group', null, $base_group_options);
-			$group_el[] = & $create_subgroups_form->createElement('submit', 'submit', get_lang('Ok'));
+			$group_el[] = $create_subgroups_form->createElement('static', null, null, get_lang('CreateNumberOfGroups'));
+			$group_el[] = $create_subgroups_form->createElement('text', 'number_of_groups', null, array('size' => 3));
+			$group_el[] = $create_subgroups_form->createElement('static', null, null, get_lang('WithUsersFrom'));
+			$group_el[] = $create_subgroups_form->createElement('select', 'base_group', null, $base_group_options);
+			$group_el[] = $create_subgroups_form->createElement('button', 'submit', get_lang('Ok'));
 			$create_subgroups_form->addGroup($group_el, 'create_groups', null, ' ', false);
 			$defaults = array();
 			$defaults['action'] = 'create_subgroups';
 			$create_subgroups_form->setDefaults($defaults);
-			$create_subgroups_form->display();
-			echo '</blockquote>';
+			$create_subgroups_form->display();			
 		}
 	}
 
 	/*
 	 * Show form to generate groups from classes subscribed to the course
 	 */
-    /*
-	$classes = ClassManager :: get_classes_in_course($_course['sysCode']);
+    $options['where'] = array(" usergroup.course_id = ? " =>  api_get_real_course_id());
+    $obj = new UserGroup();	 
+    $classes = $obj->get_usergroup_in_course($options);
 	if (count($classes) > 0) {
 		echo '<b>'.get_lang('GroupsFromClasses').'</b>';
 		echo '<blockquote>';
 		echo '<p>'.get_lang('GroupsFromClassesInfo').'</p>';
 		echo '<ul>';
 		foreach ($classes as $index => $class) {
-			$number_of_users = count(ClassManager :: get_users($class['id']));
+			$number_of_users = count($obj->get_users_by_usergroup($class['id']));
 			echo '<li>';
 			echo $class['name'];
 			echo ' ('.$number_of_users.' '.get_lang('Users').')';
@@ -318,12 +317,12 @@ EOT;
 			$create_class_groups_form->addElement('hidden', 'group_category');
 		}
 		$create_class_groups_form->addElement('submit', 'submit', get_lang('Ok'));
-		$defaults['group_category'] = DEFAULT_GROUP_CATEGORY;
+		$defaults['group_category'] = GroupManager::DEFAULT_GROUP_CATEGORY;
 		$defaults['action'] = 'create_class_groups';
 		$create_class_groups_form->setDefaults($defaults);
 		$create_class_groups_form->display();
 		echo '</blockquote>';
-	}*/
+	}
     
 }
 

+ 16 - 8
main/group/group_edit.php

@@ -42,11 +42,11 @@ if (!api_is_allowed_to_edit(false,true) && !$is_group_member) {
  *  List all users registered to the course
  */
 function search_members_keyword($firstname, $lastname, $username, $official_code, $keyword) {
-	if (api_strripos($firstname, $keyword) !== false || api_strripos($lastname, $keyword) !== false || api_strripos($username, $keyword) !== false || api_strripos($official_code, $keyword) !== false) {		
+	if (api_strripos($firstname, $keyword) !== false || api_strripos($lastname, $keyword) !== false || api_strripos($username, $keyword) !== false || api_strripos($official_code, $keyword) !== false) {
 		return true;
 	} else {
 		return false;
-	}	
+	}
 }
 
 
@@ -108,6 +108,14 @@ function check_group_members($value) {
 
 /*	MAIN CODE */
 
+$htmlHeadXtra[] = '<script>
+$(document).ready( function() {
+    $("#max_member").on("focus", function() {
+        $("#max_member_selected").attr("checked", true);
+    });
+});
+ </script>';
+
 // Build form
 $form = new FormValidator('group_edit', 'post', api_get_self().'?'.api_get_cidreq());
 
@@ -133,7 +141,7 @@ foreach ($complete_user_list as $index => $user) {
 $group_tutor_list = GroupManager :: get_subscribed_tutors($current_group['id']);
 $selected_users = array();
 $selected_tutors = array();
-foreach ($group_tutor_list as $index => $user) {    
+foreach ($group_tutor_list as $index => $user) {
     $selected_tutors[] = $user['user_id'];
 }
 
@@ -191,9 +199,9 @@ $form->addFormRule('check_group_members');
 // Members per group
 $form->addElement('radio', 'max_member_no_limit', get_lang('GroupLimit'), get_lang('NoLimit'), GroupManager::MEMBER_PER_GROUP_NO_LIMIT);
 $group = array();
-$group[] = & $form->createElement('radio', 'max_member_no_limit', null, get_lang('MaximumOfParticipants'), 1);
-$group[] = & $form->createElement('text', 'max_member', null, array('class' => 'span1'));
-$group[] = & $form->createElement('static', null, null, get_lang('GroupPlacesThis'));
+$group[] = $form->createElement('radio', 'max_member_no_limit', null, get_lang('MaximumOfParticipants'), 1, array('id' => 'max_member_selected'));
+$group[] = $form->createElement('text', 'max_member', null, array('class' => 'span1', 'id' => 'max_member'));
+$group[] = $form->createElement('static', null, null, get_lang('GroupPlacesThis'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 $form->addRule('max_member_group', get_lang('InvalidMaxNumberOfMembers'), 'callback', 'check_max_number_of_members');
 
@@ -278,8 +286,8 @@ if ($form->validate()) {
 		GroupManager :: subscribe_users($values['group_members'], $current_group['id']);
 	}
 
-	// Returning to the group area (note: this is inconsistent with the rest of chamilo)    
-	$cat = GroupManager :: get_category_from_group($current_group['id']);      
+	// Returning to the group area (note: this is inconsistent with the rest of chamilo)
+	$cat = GroupManager :: get_category_from_group($current_group['id']);
     if (isset($_POST['group_members']) && count($_POST['group_members']) > $max_member && $max_member != GroupManager::MEMBER_PER_GROUP_NO_LIMIT) {
         header('Location: group.php?'.api_get_cidreq(true, false).'&action=warning_message&msg='.get_lang('GroupTooMuchMembers'));
     } else {

BIN
main/img/icons/22/exit_na.png


+ 29 - 9
main/inc/ajax/exercise.ajax.php

@@ -70,11 +70,22 @@ switch ($action) {
             $start = 0;
         }        
         
-        $sql = "SELECT exe_id,  exe_user_id, firstname, lastname, aa.status, start_date, exe_result, exe_weighting, exe_result/exe_weighting as score, exe_duration, questions_to_check, orig_lp_id, aa.qlist as qlist
+        $sql = "SELECT  exe_id,  
+                        exe_user_id, 
+                        firstname, 
+                        lastname, 
+                        aa.status, 
+                        start_date, 
+                        exe_result, 
+                        exe_weighting, 
+                        exe_result/exe_weighting as score, 
+                        exe_duration, 
+                        questions_to_check, 
+                        orig_lp_id
                 FROM $user_table u 
                 INNER JOIN (
                     SELECT  t.exe_id, t.exe_user_id, status,
-                    start_date, exe_result, exe_weighting, exe_result/exe_weighting as score, exe_duration, questions_to_check, orig_lp_id, t.data_tracking as qlist
+                    start_date, exe_result, exe_weighting, exe_result/exe_weighting as score, exe_duration, questions_to_check, orig_lp_id
                     FROM  $track_exercise  t LEFT JOIN $track_attempt a ON (a.exe_id = t.exe_id AND  t.exe_user_id = a.user_id ) 
                     WHERE t.status = 'incomplete' AND
                           $where_condition  
@@ -100,7 +111,6 @@ switch ($action) {
         
         if (!empty($results)) {
             foreach($results as $row) {
-		$qcount = count(split(',',$row['qlist'])); 
                 $sql = "SELECT SUM(count_question_id) as count_question_id FROM (
                             SELECT 1 as count_question_id FROM  $track_attempt a 
                             WHERE user_id = {$row['exe_user_id']} and exe_id = {$row['exe_id']}
@@ -120,7 +130,7 @@ switch ($action) {
                 $array = array( $row['firstname'], 
                                 $row['lastname'], 
                                 api_format_date($row['start_date'], DATE_TIME_FORMAT_LONG).' ['.($h>0?$h.':':'').sprintf("%02d",$m).':'.sprintf("%02d",$s).']',
-                                $row['count_questions'].'/'.$qcount,                              
+                                $row['count_questions'],                                
                                 round($row['score']*100).'%'
                                );
                 $response->rows[$i]['cell'] = $array;
@@ -176,8 +186,8 @@ switch ($action) {
             if ($debug) error_log("exe_id = $exe_id ");
             if ($debug) error_log("type = $type ");
             if ($debug) error_log("choice = ".print_r($choice, 1)." ");
-            if ($debug) error_log("hot_spot_coordinates = $hot_spot_coordinates ");
-            if ($debug) error_log("remind_list = $remind_list ");            
+            if ($debug) error_log("hot_spot_coordinates = ".print_r($hot_spot_coordinates,1));
+            if ($debug) error_log("remind_list = ".print_r($remind_list));
             
             //Exercise information            
             $objExercise             = $_SESSION['objExercise'];
@@ -285,7 +295,7 @@ switch ($action) {
             	$hotspot_delineation_result = $_SESSION['hotspot_delineation_result'][$objExercise->selectId()][$my_question_id];                
                 
                 if ($type == 'simple') {
-                    //Getting old attempt in order to decress the total score 
+                    //Getting old attempt in order to decrees the total score 
                     $old_result = $objExercise->manage_answer($exe_id, $my_question_id, null, 'exercise_show', array(), false, true, false, $objExercise->selectPropagateNeg());                                                     	
                     
                     //Removing old score
@@ -304,7 +314,7 @@ switch ($action) {
                 
             	
             	// We're inside *one* question. Go through each possible answer for this question
-            	$result = $objExercise->manage_answer($exe_id, $my_question_id, $my_choice,'exercise_result', $hot_spot_coordinates, true, false, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result, true);
+            	$result = $objExercise->manage_answer($exe_id, $my_question_id, $my_choice, 'exercise_result', $hot_spot_coordinates, true, false, false, $objExercise->selectPropagateNeg(), $hotspot_delineation_result, true);
                 
                 //Adding the new score 
                 $total_score += $result['score'];              
@@ -336,7 +346,17 @@ switch ($action) {
                 
                 $_SESSION['duration_time'][$key] = time();
                 
-                update_event_exercice($exe_id, $objExercise->selectId(), $total_score, $total_weight, api_get_session_id(), $exercise_stat_info['orig_lp_id'], $exercise_stat_info['orig_lp_item_id'], $exercise_stat_info['orig_lp_item_view_id'], $duration, 'incomplete', $remind_list);
+                update_event_exercice(  $exe_id, 
+                                        $objExercise->selectId(), 
+                                        $total_score, 
+                                        $total_weight, 
+                                        api_get_session_id(),
+                                        $exercise_stat_info['orig_lp_id'], 
+                                        $exercise_stat_info['orig_lp_item_id'], 
+                                        $exercise_stat_info['orig_lp_item_view_id'], 
+                                        $duration, 
+                                        'incomplete', 
+                                        $remind_list);
                 
                  // Destruction of the Question object
             	unset($objQuestionTmp); 

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

@@ -329,8 +329,7 @@ if (!$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
 // ===== end "who is logged in?" module section =====
 
 if (api_get_setting('server_type') == 'test') {    
-    //error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
-    error_reporting(-1);
+    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
 } else {
     /*
     Server type is not test

+ 49 - 12
main/inc/lib/banner.lib.php

@@ -60,8 +60,10 @@ function get_tabs() {
 		$navigation['session_my_progress']['url'] = api_get_path(WEB_CODE_PATH).'auth/my_progress.php';
 		$navigation['session_my_progress']['title'] = get_lang('MyProgress');
 	}
-
-	// Social
+    
+    
+    // Social
+    /*
 	if (api_get_setting('allow_social_tool')=='true') {
 		$navigation['social']['url'] = api_get_path(WEB_CODE_PATH).'social/home.php';
 
@@ -79,7 +81,14 @@ function get_tabs() {
 
 		$navigation['social']['title'] = get_lang('SocialNetwork'). $total_invitations;
 	}
-
+    */
+    
+	// Social
+	if (api_get_setting('allow_social_tool')=='true') {
+		$navigation['social']['url'] = api_get_path(WEB_CODE_PATH).'social/home.php';
+		$navigation['social']['title'] = get_lang('SocialNetwork');
+	} 
+   
 	// Dashboard
 	if (api_is_platform_admin() || api_is_drh() || api_is_session_admin()) {
 		$navigation['dashboard']['url'] = api_get_path(WEB_CODE_PATH).'dashboard/index.php';
@@ -307,15 +316,17 @@ function return_navigation_array() {
             }
         }
 
-		// Custom tabs
-		for ($i=1;$i<=3;$i++)
-			if (api_get_setting('show_tabs', 'custom_tab_'.$i) == 'true') {
-				$navigation['custom_tab_'.$i] = $possible_tabs['custom_tab_'.$i];
-			} else {
-			    if (isset($possible_tabs['custom_tab_'.$i])) {
+        // Custom tabs
+        for ($i=1;$i<=3;$i++) {
+            if (api_get_setting('show_tabs', 'custom_tab_'.$i) == 'true' && isset($possible_tabs['custom_tab_'.$i])) {
+                $navigation['custom_tab_'.$i] = $possible_tabs['custom_tab_'.$i];
+            } else {
+                if (isset($possible_tabs['custom_tab_'.$i])) {
                     $menu_navigation['custom_tab_'.$i] = $possible_tabs['custom_tab_'.$i];
                 }
-			}
+            }
+        }
+
     }
     return array('menu_navigation' => $menu_navigation, 'navigation' => $navigation, 'possible_tabs' => $possible_tabs);
 }
@@ -409,7 +420,6 @@ function return_menu() {
 }
 
 function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
-
     $session_id     = api_get_session_id();
     $session_name   = api_get_session_name($session_id);
     $_course        = api_get_course_info();
@@ -463,6 +473,9 @@ function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
     // part 2: Interbreadcrumbs. If there is an array $interbreadcrumb defined then these have to appear before the last breadcrumb (which is the tool itself)
     if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
         foreach ($interbreadcrumb as $breadcrumb_step) {
+            if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {
+                continue;
+            }
             if ($breadcrumb_step['url'] != '#') {
                 $sep = (strrchr($breadcrumb_step['url'], '?') ? '&amp;' : '?');
                 $navigation_item['url'] = $breadcrumb_step['url'].$sep.api_get_cidreq();
@@ -498,6 +511,24 @@ function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
             $navigation[] = $navigation_item;
         }
     }
+    
+    $navigation_right = array();
+    
+    if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
+        foreach ($interbreadcrumb as $breadcrumb_step) {
+            if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {
+                if ($breadcrumb_step['url'] != '#') {
+                    $sep = (strrchr($breadcrumb_step['url'], '?') ? '&amp;' : '?');
+                    $navigation_item['url'] = $breadcrumb_step['url'].$sep.api_get_cidreq();
+                } else {
+                    $navigation_item['url'] = '#';
+                }
+                $breadcrumb_step['title'] = cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
+                $breadcrumb_step['title'] = Security::remove_XSS($navigation_item['title']);
+                $navigation_right[] = $breadcrumb_step;
+            }
+        }
+    }
 
 
     // part 3: The tool itself. If we are on the course homepage we do not want to display the title of the course because this
@@ -513,7 +544,6 @@ function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
 
     foreach ($navigation as $index => $navigation_info) {
         if (!empty($navigation_info['title'])) {
-
             if ($navigation_info['url'] == '#') {
                 $final_navigation[$index] = $navigation_info['title'];
             } else {
@@ -568,6 +598,13 @@ function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
             $lis.= Display::tag('li', $view_as_student_link, array('id' => 'view_as_link','class' => 'pull-right'));
         }
         
+        if (!empty($navigation_right)) {            
+            foreach($navigation_right as $item){
+                $extra_class = isset($item['class']) ? $item['class'] : null;
+                $lis.= Display::tag('li', $item['title'], array('class' => $extra_class.' pull-right'));    
+            }
+        }
+        
         if (!empty($lis)) {
             $html .= Display::tag('ul', $lis, array('class'=>'breadcrumb'));
         }

+ 4 - 4
main/inc/lib/course_home.lib.php

@@ -770,7 +770,7 @@ class CourseHome {
                 switch($theme) {
                     case 'activity_big':
                         $data = '';
-                        $html .=  '<div class="span4">';
+                        $html .=  '<div class="span4 course-tool">';
                         $image = (substr($item['tool']['image'], 0, strpos($item['tool']['image'], '.'))).'.png';
                         $image = Display::return_icon($image, $item['name'], array('id'=>'toolimage_'.$item['tool']['id']), ICON_SIZE_BIG, false);
                         $data .= Display::url($image , $item['url_params']['href'], $item['url_params']);
@@ -780,7 +780,7 @@ class CourseHome {
 
                         break;
                     case 'activity':
-                        $html .=  '<div class="offset2 span4">';
+                        $html .=  '<div class="offset2 span4 course-tool">';
                             $html .=  $item['extra'];
                             $html .=  $item['visibility'];
                             $html .=  $item['icon'];
@@ -791,7 +791,7 @@ class CourseHome {
                         if ($i == 0) {
                             $html .=  '<ul>';
                         }
-                        $html .=  '<li>';
+                        $html .=  '<li class="course-tool">';
                             $html .=  $item['extra'];
                             $html .=  $item['visibility'];
                             $html .=  $item['icon'];
@@ -1047,4 +1047,4 @@ class CourseHome {
         }
         return $html;
     }
-}
+}

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

@@ -677,7 +677,7 @@ class Database {
         //@todo remove this before the stable release
         
         //Check if the table contains a c_ (means a course id)
-        if (strpos($query, 'c_')) {	
+        if (api_get_setting('server_type')==='test' && strpos($query, 'c_')) {
         	//Check if the table contains inner joins 
         	if (     
                 strpos($query, 'assoc_handle') === false &&

+ 12 - 2
main/inc/lib/display.lib.php

@@ -49,12 +49,13 @@ class Display {
      * Displays the reduced page header (without banner)
      */
     public static function display_reduced_header() {        
-        global $show_learnpath;
+        global $show_learnpath, $tool_name;
         self::$global_template = new Template($tool_name, false, false, $show_learnpath);        
         echo self::$global_template ->show_header_template();        
     }
     
     public static function display_no_header() {        
+        global $tool_name;
         $disable_js_and_css_files = true;
         self::$global_template = new Template($tool_name, false, false, $show_learnpath);        
         //echo self::$global_template->show_header_template();        
@@ -855,7 +856,8 @@ class Display {
         
         //Default row quantity
         if (!isset($extra_params['rowList'])) {
-            $extra_params['rowList'] = array(50, 100, 200);
+            $extra_params['rowList'] = array(20, 50, 100, 500, 1000);
+            //$extra_params['rowList'] = array(20, 50, 100, 500, 1000, 2000, 5000, 10000);
         }
         
         $json = '';
@@ -1317,6 +1319,14 @@ class Display {
         return self::page_header($title, $second_title, 'h4');
     }
     
+    public static function page_subheader2($title, $second_title = null) {
+        return self::page_header($title, $second_title, 'h3');
+    }
+    
+    public static function page_subheader3($title, $second_title = null) {
+        return self::page_header($title, $second_title, 'h4');
+    }
+    
     public static function description($list) {
         $html = null;
         if (!empty($list)) {

+ 3 - 5
main/inc/lib/document.lib.php

@@ -1190,11 +1190,9 @@ class DocumentManager {
             $file_type = 'file';
         }
 
-        $sql  = "SELECT visibility FROM $docTable d, $propTable ip
-        		 WHERE 	d.c_id  = $course_id  AND
-        		 		ip.c_id = $course_id AND
-        				d.id = ip.ref AND
-        				ip.tool = '".TOOL_DOCUMENT."' $condition AND
+        $sql = "SELECT visibility FROM $docTable d INNER JOIN $propTable ip
+                ON (d.id = ip.ref AND d.c_id  = $course_id  AND ip.c_id = $course_id)
+        		 WHERE ip.tool = '" . TOOL_DOCUMENT . "' $condition AND
         				filetype = '$file_type' AND locate(concat(path,'/'),'".$doc_path."/')=1";
 
         $result = Database::query($sql);

+ 6 - 1
main/inc/lib/fckeditor/fckeditor.php

@@ -58,7 +58,12 @@ function FCKeditor_IsCompatibleBrowser()
     }
     else if ( strpos($sAgent, 'Gecko/') !== false )
     {
-        $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ;
+        $iVersion = substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ;
+        // Special fix for Firefox 17 and followers - see #5752
+        if ( preg_match('/^\d{2,3}\.\d{1,4}\s/', $iVersion) ) {
+          return true;
+        }
+        $iVersion = (int)$iVersion;
         return ($iVersion >= 20030210) ;
     }
     else if ( strpos($sAgent, 'Opera/') !== false )

+ 8 - 7
main/inc/lib/fckeditor/toolbars/default/test_category.php

@@ -1,10 +1,11 @@
 <?php
-	$config['ToolbarSets']['Normal'] = array(	
-	array('Style','FontFormat','FontName','FontSize'),
-  '/',
-	array('Bold','Italic','Underline'),
-  array('SpecialChar', 'mimetex'),
-  array('OrderedList','UnorderedList','-','Outdent','Indent','-','TextColor','BGColor'),
-	array('JustifyLeft','JustifyCenter','JustifyRight','-','Source')
+
+$config['ToolbarSets']['Normal'] = array(
+    array('Style', 'FontFormat', 'FontName', 'FontSize'),
+    '/',
+    array('Bold', 'Italic', 'Underline'),
+    array('SpecialChar', 'mimetex'),
+    array('OrderedList', 'UnorderedList', '-', 'Outdent', 'Indent', '-', 'TextColor', 'BGColor'),
+    array('JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'Source')
 );
 ?>

+ 1 - 1
main/inc/lib/fckeditor/toolbars/default/test_description.php

@@ -1,6 +1,6 @@
 <?php
 // Chamilo LMS
-// See license terms in chamilo/documentation/license.txt
+// See license terms in license.txt
 
 // Training tools
 // Test description

+ 1 - 1
main/inc/lib/fckeditor/toolbars/extended/forum.php

@@ -23,7 +23,7 @@ else{
 $config['ToolbarSets']['Normal'] = array(
 	array('Save','NewPage','Templates','-','PasteWord'),
 	array('Undo','Redo'),
-	array('Link','Image','flvPlayer','Flash','MP3','TableOC','mimetex','asciimath','asciisvg'),
+	array('Link','Image','flvPlayer','EmbedMovies', 'YouTube', 'Flash','MP3','TableOC','mimetex','asciimath','asciisvg'),
 	array('UnorderedList','OrderedList','Rule'),
 	array('Abbr'),
 	array('JustifyLeft','JustifyCenter','JustifyFull'),

+ 1 - 1
main/inc/lib/fckeditor/toolbars/extended/forum_student.php

@@ -23,7 +23,7 @@ else{
 $config['ToolbarSets']['Normal'] = array(
 	array('Save','NewPage','Templates','-','PasteWord'),
 	array('Undo','Redo'),
-	array('Link','Image','flvPlayer','Flash','MP3','TableOC','mimetex','asciimath','asciisvg'),
+	array('Link','Image','flvPlayer','EmbedMovies', 'YouTube', 'Flash','MP3','TableOC','mimetex','asciimath','asciisvg'),
 	array('UnorderedList','OrderedList','Rule'),
 	array('JustifyLeft','JustifyCenter','JustifyFull'),
 	array('FontFormat','FontName','FontSize','Bold','Italic','Underline','TextColor','BGColor'),

+ 3 - 4
main/inc/lib/fckeditor/toolbars/extended/test_proposed_answer.php

@@ -1,6 +1,6 @@
 <?php
 // Chamilo LMS
-// See license terms in chamilo/documentation/license.txt
+// See license terms in license.txt
 
 // Training tools
 // Test, proposed answer to a question
@@ -13,8 +13,7 @@
 // Hide/show SpellCheck buttom
 if ((api_get_setting('allow_spellcheck') == 'true')) {
 	$VSpellCheck='SpellCheck';
-}
-else{
+} else {
 	$VSpellCheck='';	
 }
 
@@ -26,7 +25,7 @@ $config['ToolbarSets']['Normal'] = array(
 	array('Image','flvPlayer','Flash','MP3','mimetex','asciimath','asciisvg'),
 	array('TableOC'),
 	array('Bold'),
-	array('FitWindow')	
+	array('Source','FitWindow')	
 );
 
 // This is the visible toolbar set when the editor is maximized.

+ 1 - 1
main/inc/lib/fckeditor/toolbars/extended/test_question_description.php

@@ -26,7 +26,7 @@ $config['ToolbarSets']['Normal'] = array(
    	array('UnorderedList','OrderedList','Rule'),
 	array('JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'),
 	array('FontFormat','FontName','FontSize','Bold','Italic','Underline','TextColor','BGColor'),
-	array('FitWindow')
+	array('Source', 'FitWindow')
 );
 
 // This is the visible toolbar set when the editor is maximized.

+ 170 - 39
main/inc/lib/groupmanager.lib.php

@@ -79,18 +79,9 @@ class GroupManager {
 	 */
 	public static function get_group_list ($category = null, $course_code = null) {		
 		$my_user_id = api_get_user_id();		
-		
-		/*
-		if ($course_code != null) {
-			$course_info = Database :: get_course_info($course_code);
-			$course_db = $course_info['database'];
-		} else {
-			$my_course_code=api_get_course_id();
-		}
-		*/
+	
 		$course_info 		= api_get_course_info($course_code);		
-		$course_id 			= $course_info['real_id'];								
-		$table_course 		= Database :: get_main_table(TABLE_MAIN_COURSE);
+		$course_id 			= $course_info['real_id'];		
 		$table_group_user 	= Database :: get_course_table(TABLE_GROUP_USER);
 		$table_group 		= Database :: get_course_table(TABLE_GROUP);
 
@@ -117,10 +108,10 @@ class GroupManager {
 						g.self_unregistration_allowed,
 						g.session_id,
 						ug.user_id is_member						
-					FROM ".$table_group." g
-					LEFT JOIN ".$table_group_user." ug
+					FROM $table_group g
+					LEFT JOIN $table_group_user ug
 					ON (ug.group_id = g.id AND ug.user_id = '".api_get_user_id()."' AND ug.c_id = $course_id AND g.c_id = $course_id)";
-		} elseif ($my_status_of_user_in_course==STUDENT || $is_student_in_session===true || $_SESSION['studentview'] == 'studentview') {
+		} elseif ($my_status_of_user_in_course==STUDENT || $is_student_in_session  ===true || $_SESSION['studentview'] == 'studentview') {
 			$sql = "SELECT g.id,
 						g.name,
 						g.description,
@@ -131,8 +122,8 @@ class GroupManager {
 						g.self_unregistration_allowed,
 						g.session_id,
 						ug.user_id is_member						
-					FROM ".$table_group." g
-					LEFT JOIN ".$table_group_user." ug
+					FROM $table_group g
+					LEFT JOIN $table_group_user ug
 					ON (ug.group_id = g.id AND ug.user_id = '".api_get_user_id()."' AND ug.c_id = $course_id AND g.c_id = $course_id)";			
 		}
 				
@@ -162,15 +153,8 @@ class GroupManager {
 		$groups = array();
 		$thisGroup= array();
         while ($thisGroup = Database::fetch_array($groupList)) {
-            /*if ($thisGroup['category_id'] == self::VIRTUAL_COURSE_CATEGORY) {
-                $sql = "SELECT title FROM $table_course WHERE code = '".$thisGroup['name']."'";
-                $obj = Database::fetch_object(Database::query($sql));
-                $thisGroup['name'] = $obj->title;
-            }*/
-
             $thisGroup['number_of_members'] = count(GroupManager::get_subscribed_users($thisGroup['id']));
-            //$thisGroup['number_of_members'] = GroupManager::get_subscribed_users($category);
-
+            
             if ($thisGroup['session_id']!=0) {
                 $sql_session = 'SELECT name FROM '.Database::get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$thisGroup['session_id'];
                 $rs_session = Database::query($sql_session);
@@ -197,16 +181,19 @@ class GroupManager {
         
         $session_id = api_get_session_id();
         $course_id  = api_get_course_int_id();
-        
-		$currentCourseRepository = $_course['path'];
+       	$currentCourseRepository = $_course['path'];
 		
 		$category = self :: get_category($category_id);
 
 		if (intval($places) == 0) {
 			//if the amount of users per group is not filled in, use the setting from the category
 			$places = $category['max_student'];
-		}
-        
+		} else {
+            if ($places > $category['max_student'] && $category['max_student'] != 0) {
+                $places = $category['max_student'];
+            } 
+        } 
+         
 		 $sql = "INSERT INTO ".$table_group." SET
 				c_id = $course_id , 
 				category_id='".Database::escape_string($category_id)."', 
@@ -346,18 +333,15 @@ class GroupManager {
 	 */
 	public static function create_class_groups ($category_id) {
 		global $_course;
-		$classes = ClassManager::get_classes_in_course($_course['sysCode']);
+        $options['where'] = array(" usergroup.course_id = ? " =>  api_get_real_course_id());
+        $obj = new UserGroup();	 
+        $classes = $obj->get_usergroup_in_course($options);		
 		$group_ids = array();
 		foreach($classes as $index => $class)
 		{
-			$users = ClassManager::get_users($class['id']);
-			$group_id = self::create_group($class['name'],$category_id,0,count($users));
-			$user_ids = array();
-			foreach($users as $index_user => $user)
-			{
-				$user_ids[] = $user['user_id'];
-			}
-			self::subscribe_users($user_ids,$group_id);
+		    $users_ids = $obj->get_users_by_usergroup($class['id']);
+			$group_id = self::create_group($class['name'],$category_id,0,count($users_ids));
+			self::subscribe_users($users_ids,$group_id);
 			$group_ids[] = $group_id;
 		}
 		return $group_ids;
@@ -498,7 +482,12 @@ class GroupManager {
 		$table_forum = Database :: get_course_table(TABLE_FORUM);
 		//$forum_id = get_forums_of_group($group_id);
 		$group_id = Database::escape_string($group_id);
-		$course_id = api_get_course_int_id();
+        $category = self::get_category_from_group($group_id);
+        if ($maximum_number_of_students > $category['max_student'] && $category['max_student'] != 0) {
+            $maximum_number_of_students = $category['max_student'];
+        }
+        $course_id = api_get_course_int_id();
+        
 		$sql = "UPDATE ".$table_group."
 					SET name='".Database::escape_string(trim($name))."',
 					doc_state = '".Database::escape_string($doc_state)."',
@@ -1691,7 +1680,149 @@ class GroupManager {
         //$complete_user_list = self :: filter_only_students($complete_user_list);
         //now sort by # of group left
         $complete_user_list = TableSort :: sort_table($complete_user_list, 'number_groups_left', SORT_DESC);           
-        return $complete_user_list;    
+        return $complete_user_list;        
+    }
+    
+    static function process_groups($group_list, $category_id = null) {
+        global $origin, $charset;
+        $category_id = intval($category_id);
+        
+        $totalRegistered = 0;
+        $group_data = array();
+        $user_info = api_get_user_info();
+        $session_id = api_get_session_id();
+        $user_id = $user_info['user_id'];
+        
+        $orig = isset($origin) ? $origin : null;
+        
+        foreach ($group_list as $this_group) {
+
+            // Validacion when belongs to a session
+            $session_img = api_get_session_image($this_group['session_id'], $user_info['status']);
+
+            // All the tutors of this group
+            $tutorsids_of_group = GroupManager::get_subscribed_tutors($this_group['id'], true);
+
+            // Create a new table-row
+            $row = array ();
+            // Checkbox
+            if (api_is_allowed_to_edit(false,true) && count($group_list) > 1) {
+                $row[] = $this_group['id'];
+            }
+
+            // Group name
+            if ((api_is_allowed_to_edit(false, true) ||
+                    in_array($user_id, $tutorsids_of_group) ||
+                    $this_group['is_member'] ||
+                    GroupManager::user_has_access($user_id, $this_group['id'], GroupManager::GROUP_TOOL_FORUM) ||
+                    GroupManager::user_has_access($user_id, $this_group['id'], GroupManager::GROUP_TOOL_DOCUMENTS) ||
+                    GroupManager::user_has_access($user_id, $this_group['id'], GroupManager::GROUP_TOOL_CALENDAR) ||
+                    GroupManager::user_has_access($user_id, $this_group['id'], GroupManager::GROUP_TOOL_ANNOUNCEMENT) ||
+                    GroupManager::user_has_access($user_id, $this_group['id'], GroupManager::GROUP_TOOL_WORK) ||
+                    GroupManager::user_has_access($user_id, $this_group['id'], GroupManager::GROUP_TOOL_WIKI))
+                    && !(api_is_course_coach() && intval($this_group['session_id']) != $session_id)) {
+                
+                $group_name = '<a href="group_space.php?cidReq='.api_get_course_id().'&amp;origin='.$orig.'&amp;gidReq='.$this_group['id'].'">'.Security::remove_XSS($this_group['name']).'</a> ';
+                if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) {
+                    $group_name .= Display::label(get_lang('OneMyGroups'), 'success');
+                } elseif ($this_group['is_member']) {
+                    $group_name .= Display::label(get_lang('MyGroup'), 'success');
+                }
+                
+                if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
+                    $group_name .= ' ('.$this_group['session_name'].')';
+                }
+                $group_name .= $session_img;
+                $row[] = $group_name.'<br />'.stripslashes(trim($this_group['description']));
+            } else {
+                $row[] = $this_group['name'].'<br />'.stripslashes(trim($this_group['description']));
+            }                      
+
+            // Tutor name
+            $tutor_info = null;
+
+            if (count($tutorsids_of_group) > 0) {
+                foreach ($tutorsids_of_group as $tutor_id) {
+                    $tutor = api_get_user_info($tutor_id);
+                    $username = api_htmlentities(sprintf(get_lang('LoginX'), $tutor['username']), ENT_QUOTES);
+                    if (api_get_setting('show_email_addresses') == 'true') {
+                        $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title'=>$username)).', ';
+                    } else {
+                        if (api_is_allowed_to_edit()) {
+                            $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title'=>$username)).', ';
+                        } else {
+                            $tutor_info .= Display::tag('span', api_get_person_name($tutor['firstName'], $tutor['lastName']), array('title'=>$username)).', ';
+                        }
+                    }
+                }
+            }
+            $tutor_info = api_substr($tutor_info, 0, api_strlen($tutor_info) - 2);
+            $row[] = $tutor_info;
+
+            // Max number of members in group
+            $max_members = ($this_group['maximum_number_of_members'] == GroupManager::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / '.$this_group['maximum_number_of_members']);
+
+            // Number of members in group
+            $row[] = $this_group['number_of_members'].$max_members;
+
+            // Self-registration / unregistration
+            if (!api_is_allowed_to_edit(false, true)) {
+                if (GroupManager :: is_self_registration_allowed($user_id, $this_group['id'])) {
+                    $row[] = '<a class = "btn" href="group.php?'.api_get_cidreq().'&category='.$category_id.'&amp;action=self_reg&amp;group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."'".')) return false;">'.get_lang('GroupSelfRegInf').'</a>';
+                } elseif (GroupManager :: is_self_unregistration_allowed($user_id, $this_group['id'])) {
+                    $row[] = '<a class = "btn" href="group.php?'.api_get_cidreq().'&category='.$category_id.'&amp;action=self_unreg&amp;group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."'".')) return false;">'.get_lang('GroupSelfUnRegInf').'</a>';
+                } else {
+                    $row[] = '-';
+                }
+            }
+
+            // Edit-links
+            if (api_is_allowed_to_edit(false, true)  && !(api_is_course_coach() && intval($this_group['session_id']) != $session_id)) {
+                $edit_actions = '<a href="group_edit.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'"  title="'.get_lang('Edit').'">'.Display::return_icon('edit.png', get_lang('EditGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';								
+                $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&amp;action=empty_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('EmptyGroup').'">'.
+                    Display::return_icon('clean.png',get_lang('EmptyGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';				
+                $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&amp;action=fill_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('FillGroup').'">'.
+                    Display::return_icon('fill.png',get_lang('FillGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
+                $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&amp;action=delete_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'">'.
+                    Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
+                $row[] = $edit_actions;
+            }
+            if (!empty($this_group['nbMember'])) {
+                $totalRegistered = $totalRegistered + $this_group['nbMember'];
+            }
+            $group_data[] = $row;
+        } // end loop
         
+        if (isset($_GET['show_all'])) {
+            $paging_options = array('per_page' => count($group_data));
+        } else {
+            $paging_options = array ();
+        }
+        
+        $table = new SortableTableFromArrayConfig($group_data, 1, 20, 'group_category_'.$category_id);
+        //$my_cat = isset($_GET['category']) ? Security::remove_XSS($_GET['category']) : null;
+        $table->set_additional_parameters(array('category' => $category_id));
+        $column = 0;
+        if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) {
+            $table->set_header($column++, '', false);
+        }
+        $table->set_header($column++, get_lang('Groups'));
+        $table->set_header($column++, get_lang('GroupTutor'));
+        $table->set_header($column++, get_lang('Registered'), false);
+
+        if (!api_is_allowed_to_edit(false, true)) { // If self-registration allowed
+            $table->set_header($column++, get_lang('GroupSelfRegistration'), false);
+        }        
+        if (api_is_allowed_to_edit(false, true)) { // Only for course administrator
+            $table->set_header($column++, get_lang('Modify'), false);
+            $form_actions = array();
+            $form_actions['fill_selected'] = get_lang('FillGroup');
+            $form_actions['empty_selected'] = get_lang('EmptyGroup');
+            $form_actions['delete_selected'] = get_lang('Delete');
+            if (count($group_list) > 1) {
+                $table->set_form_actions($form_actions, 'group');
+            }
+        }
+        $table->display();
     }
 }

+ 5 - 1
main/inc/lib/javascript/jquery.frameready.js

@@ -239,7 +239,11 @@ jQuery.isFrameReady = function(fn){
                                     var ele=fd.createElement('script');
                                     ele.setAttribute('id', id);
                                     ele.setAttribute('src', s.src);
-                                    fd.getElementsByTagName("body")[0].appendChild(ele);
+                                    
+                                    if (fd.getElementsByTagName("body") && fd.getElementsByTagName("body")[0]) {
+                                        fd.getElementsByTagName("body")[0].appendChild(ele);
+                                    }
+                                    
                                     frs.loadInit[i] = true;
                                     break;
                                 case "stylesheet" :

+ 14 - 8
main/inc/lib/link.lib.php

@@ -124,6 +124,8 @@ function addlinkcategory($type) {
 				require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
 				require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
 				require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
+                
+                $course_int_id = api_get_course_int_id();
 
 				$courseid = api_get_course_id();
 				$specific_fields = get_specific_field_list();
@@ -165,8 +167,8 @@ function addlinkcategory($type) {
 				// Add category name if set.
 				if (isset ($_POST['selectcategory']) && $selectcategory > 0) {
 					$table_link_category = Database :: get_course_table(TABLE_LINK_CATEGORY);
-					$sql_cat = 'SELECT * FROM %s WHERE id=%d LIMIT 1';
-					$sql_cat = sprintf($sql_cat, $table_link_category, (int) $selectcategory);
+					$sql_cat = 'SELECT * FROM %s WHERE id=%d AND c_id = %d LIMIT 1';
+					$sql_cat = sprintf($sql_cat, $table_link_category, (int) $selectcategory, $course_int_id);
 					$result = Database :: query($sql_cat);
 					if (Database :: num_rows($result) == 1) {
 						$row = Database :: fetch_array($result);
@@ -186,7 +188,7 @@ function addlinkcategory($type) {
 					$tbl_se_ref = Database :: get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
 					$sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did)
 					                        VALUES (NULL , \'%s\', \'%s\', %s, %s)';
-					$sql = sprintf($sql, $tbl_se_ref, api_get_course_int_id(), $courseid, TOOL_LINK, $link_id, $did);
+					$sql = sprintf($sql, $tbl_se_ref, $course_int_id, $courseid, TOOL_LINK, $link_id, $did);
 					Database :: query($sql);
 				}
 			}
@@ -438,6 +440,9 @@ function editlinkcategory($type) {
 			// Update search enchine and its values table if enabled.
 			if (api_get_setting('search_enabled') == 'true') {
 				$link_id = intval($_POST['id']);
+                
+                $course_int_id = api_get_course_int_id();
+                
 				$course_id = api_get_course_id();
 				$link_url = Database :: escape_string($_POST['urllink']);
 				$link_title = Database :: escape_string($_POST['title']);
@@ -495,8 +500,8 @@ function editlinkcategory($type) {
 					// Add category name if set.
 					if (isset ($_POST['selectcategory']) && $selectcategory > 0) {
 						$table_link_category = Database :: get_course_table(TABLE_LINK_CATEGORY);
-						$sql_cat = 'SELECT * FROM %s WHERE id=%d LIMIT 1';
-						$sql_cat = sprintf($sql_cat, $table_link_category, (int) $selectcategory);
+						$sql_cat = 'SELECT * FROM %s WHERE id=%d and c_id = %d LIMIT 1';
+						$sql_cat = sprintf($sql_cat, $table_link_category, (int) $selectcategory, $course_int_id);
 						$result = Database :: query($sql_cat);
 						if (Database :: num_rows($result) == 1) {
 							$row = Database :: fetch_array($result);
@@ -519,7 +524,7 @@ function editlinkcategory($type) {
 						Database :: query($sql);
 						$sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did)
 						        VALUES (NULL , \'%s\', \'%s\', %s, %s)';
-						$sql = sprintf($sql, $tbl_se_ref, api_get_course_int_id(), $course_id, TOOL_LINK, $link_id, $did);
+						$sql = sprintf($sql, $tbl_se_ref, $course_int_id, $course_id, TOOL_LINK, $link_id, $did);
 						Database :: query($sql);
 					}
 				}
@@ -544,7 +549,8 @@ function editlinkcategory($type) {
 
 		// This is used to put the modified info of the category-form into the database.
 		if ($submit_category) {
-			$sql = "UPDATE " . $tbl_categories . " SET category_title='" . Database :: escape_string($_POST['category_title']) . "', description='" . Database :: escape_string($_POST['description']) . "'
+			$sql = "UPDATE " . $tbl_categories . " 
+                    SET category_title='" . Database :: escape_string($_POST['category_title']) . "', description='" . Database :: escape_string($_POST['description']) . "'
 			        WHERE c_id = $course_id AND id='" . Database :: escape_string($_POST['id']) . "'";
 			Database :: query($sql);
 			Display :: display_confirmation_message(get_lang('CategoryModded'));
@@ -809,7 +815,7 @@ function get_cat($catname) {
 		return $row['id']; // Several categories with same name: take the first.
 	}
 
-	$result = Database :: query("SELECT MAX(display_order) FROM " . $tbl_categories);
+	$result = Database :: query("SELECT MAX(display_order) FROM " . $tbl_categories." WHERE c_id = $course_id ");
 	list ($max_order) = Database :: fetch_row($result);
 	Database :: query("INSERT INTO " . $tbl_categories . " (c_id, category_title, description, display_order)
 					   VALUES (".$course_id.", '" . Database::escape_string($catname) . "','','" . ($max_order +1) . "')");

+ 26 - 11
main/inc/lib/main_api.lib.php

@@ -1037,6 +1037,7 @@ function api_get_user_courses($userid, $fetch_session = true) {
 
 /**
  * Formats user information into a standard array
+ * This function should be only used inside api_get_user_info()
  *
  * @param array Non-standard user array
  * @return array Standard user array
@@ -2649,9 +2650,10 @@ function api_display_debug_info($debug_info) {
  * this particular course.
  * Optionally checking for tutor and coach roles here allows us to use the
  * student_view feature altogether with these roles as well.
- * @param bool      Whether to check if the user has the tutor role
- * @param bool      Whether to check if the user has the coach role
- * @param bool      Whether to check if the user has the session coach role
+ * @param bool  Whether to check if the user has the tutor role
+ * @param bool  Whether to check if the user has the coach role
+ * @param bool  Whether to check if the user has the session coach role
+ * @param bool  check the student view or not
  *
  * @author Roan Embrechts
  * @author Patrick Cool
@@ -2659,7 +2661,7 @@ function api_display_debug_info($debug_info) {
  * @return boolean, true: the user has the rights to edit, false: he does not
  */
 
-function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach = false) {
+function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach = false, $check_student_view = true) {
 
     $my_session_id 				= api_get_session_id();
     $is_allowed_coach_to_edit 	= api_is_coach();
@@ -2668,7 +2670,7 @@ function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach =
     //Admins can edit anything
     if (api_is_platform_admin(false)) {
         //The student preview was on
-        if (isset($_SESSION['studentview']) && $_SESSION['studentview'] == "studentview") {
+        if ($check_student_view && isset($_SESSION['studentview']) && $_SESSION['studentview'] == "studentview") {
             return false;
         } else {
             return true;
@@ -2710,9 +2712,15 @@ function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach =
             } else {
                 $is_allowed = false;
             }
-            $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
+            if ($check_student_view) {
+                $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
+            }
         } else {
-            $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
+            if ($check_student_view) {
+                $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
+            } else {
+                $is_allowed = $is_courseAdmin;   
+            }
         }
         return $is_allowed;
     } else {
@@ -2889,7 +2897,13 @@ function api_not_found($print_headers = false) {
  * @version dokeos 1.8, August 2006
  */
 function api_not_allowed($print_headers = false, $message = null) {
-    Header::response_code(403);
+    if (api_get_setting('sso_authentication') === 'true') {
+        global $osso;
+        if ($osso) {
+            $osso->logout();
+        }
+    }
+    Header::response_code(403);    
     $home_url   = api_get_path(WEB_PATH);
     $user_id    = api_get_user_id();
     $course     = api_get_course_id();
@@ -2925,7 +2939,7 @@ function api_not_allowed($print_headers = false, $message = null) {
     $tpl = new Template(null, $show_headers, $show_headers);
     $tpl->assign('content', $msg);
 
-    if (($user_id!=0 && !api_is_anonymous()) && (!isset($course) || $course == -1) && empty($_GET['cidReq'])) {
+    if (($user_id!=0 && !api_is_anonymous()) && (!isset($course) || $course == -1) && empty($_GET['cidReq'])) {        
         // if the access is not authorized and there is some login information
         // but the cidReq is not found, assume we are missing course data and send the user
         // to the user_portal
@@ -2934,13 +2948,14 @@ function api_not_allowed($print_headers = false, $message = null) {
     }
 
     if (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE)) {
+        
         //only display form and return to the previous URL if there was a course ID included
-        if ($user_id!=0 && !api_is_anonymous()) {
+        if ($user_id != 0 && !api_is_anonymous()) {
             //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
             $tpl->assign('content', $msg);
             $tpl->display_one_col_template();
             exit;
-        }
+        }       
 
         // If the user has no user ID, then his session has expired
         $action = api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']);

+ 1 - 1
main/inc/lib/plugin.class.php

@@ -392,6 +392,6 @@ class Plugin {
      * @param array Values sent back from the course configuration script
      * @return void
      */
-    private function course_settings_updated($values = array()) {
+    public function course_settings_updated($values = array()) {
     }
 }

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

@@ -686,7 +686,7 @@ class SocialManager extends UserManager {
                 // reduce image
                 $name = $user_info['complete_name'];
                 $status_icon = Display::span('', array('class' => 'online_user_in_text'));
-                //$user_status = $user_info['status'] == 1 ? Display::return_icon('teacher.png', get_lang('Teacher'), array('height' => '22px', 'width' => '22px')) : null;
+                $user_status = $user_info['status'] == 1 ? Display::span('', array('class' => 'teacher_online')) : Display::span('', array('class' => 'student_online'));
                 
                 if ($image_array['file'] == 'unknown.jpg' || !file_exists($image_array['dir'].$image_array['file'])) {
                     $friends_profile['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_180_100.jpg';                                                                             

+ 27 - 2
main/inc/lib/template.lib.php

@@ -592,11 +592,14 @@ class Template {
         
         //Profile link
         if (api_get_setting('allow_social_tool') == 'true') {
-            $profile_link = '<a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">'.get_lang('Profile').'</a>';
+            $profile_url = api_get_path(WEB_CODE_PATH).'social/home.php';
+            $profile_link = Display::url(get_lang('Profile'), $profile_url);
         } else {
-            $profile_link = '<a href="'.api_get_path(WEB_CODE_PATH).'auth/profile.php">'.get_lang('Profile').'</a>';
+            $profile_url = api_get_path(WEB_CODE_PATH).'auth/profile.php';            
+            $profile_link = Display::url(get_lang('Profile'), $profile_url);
         }
         $this->assign('profile_link', $profile_link);
+        $this->assign('profile_url', $profile_url);
         
         //Message link
         $message_link = null;
@@ -613,6 +616,28 @@ class Template {
         $menu = return_menu();
         $this->assign('menu', $menu);
         
+        //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);
+        }
+
+        $total_invitations = 0;
+        if (api_get_setting('allow_social_tool')=='true') {
+            $number_of_new_messages_of_friend   = SocialManager::get_message_number_invitation_by_user_id(api_get_user_id());
+            $group_pending_invitations = GroupPortalManager::get_groups_by_user(api_get_user_id(), GROUP_USER_PERMISSION_PENDING_INVITATION,false);
+            $group_pending_invitations = 0;
+            if (!empty($group_pending_invitations )) {
+                $group_pending_invitations = count($group_pending_invitations);
+            }
+            $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) : null);    
+                
+        $this->assign('user_notifications', $total_invitations);
         //Breadcrumb        
         $breadcrumb = return_breadcrumb($interbreadcrumb, $language_file, $nameTools);
         $this->assign('breadcrumb', $breadcrumb);

+ 5 - 8
main/inc/lib/tracking.lib.php

@@ -565,12 +565,9 @@ class Tracking {
 			// count the number of learning paths
 			$lp_id = array();
 			while ($row_lp = Database::fetch_array($res_count_lp,'ASSOC')) {
-				//$visibility = api_get_item_visibility($a_course, TOOL_LEARNPATH, $row_lp['id'], $session_id);
-				//  if ($visibility == 1) {
 				$lp_id[] = $row_lp['id'];
-				//}
-				}
-				$count_lp = count($lp_id);
+			}
+			$count_lp = count($lp_id);
 
 				$avg_progress = 0;
 				//if there is at least one learning path and one student
@@ -3664,8 +3661,8 @@ class TrackingCourseLog {
                 $user_row[]= $user['firstname'];
                 $user_row[]= $user['lastname'];
             }
-            $user_row[]= $user['username']; // hubr
-            $user_row[]= $user['time']; //3           
+            $user_row[]= $user['username'];
+            $user_row[]= $user['time'];           
             $user_row[]= $user['average_progress'];            
             $user_row[]= $user['exercise_progress'];
             
@@ -3674,7 +3671,7 @@ class TrackingCourseLog {
         
             $user_row[]= $user['student_score'];
             $user_row[]= $user['count_assignments'];
-            $user_row[]= $user['count_messages']; //8
+            $user_row[]= $user['count_messages'];
             
             if (empty($session_id)) {
                 $user_row[]= $user['survey'];

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