Browse Source

Merge branch '1.9.x' of https://github.com/chamilo/chamilo-lms into 9089

Conflicts:
	main/inc/lib/extra_field.lib.php
	main/inc/lib/extra_field_value.lib.php
Angel Fernando Quiroz Campos 10 years ago
parent
commit
0addfabe74
100 changed files with 4478 additions and 3112 deletions
  1. 2 1
      composer.json
  2. 140 32
      composer.lock
  3. 0 1
      main/admin/access_url_check_user_session.php
  4. 2 0
      main/admin/access_url_edit.php
  5. 6 4
      main/admin/add_sessions_to_promotion.php
  6. 13 22
      main/admin/add_sessions_to_usergroup.php
  7. 25 21
      main/admin/add_users_to_session.php
  8. 25 1
      main/admin/course_edit.php
  9. 68 28
      main/admin/course_list.php
  10. 3 2
      main/admin/course_request_accepted.php
  11. 8 6
      main/admin/dashboard_add_courses_to_user.php
  12. 7 5
      main/admin/dashboard_add_sessions_to_user.php
  13. 74 0
      main/admin/export_certificates.php
  14. 58 14
      main/admin/extra_fields.php
  15. 2 2
      main/admin/group_add.php
  16. 1 1
      main/admin/group_list.php
  17. 3 2
      main/admin/resume_session.php
  18. 9 4
      main/admin/session_course_edit.php
  19. 89 47
      main/admin/sub_language.class.php
  20. 76 56
      main/admin/sub_language.php
  21. 9 10
      main/admin/sub_language_add.php
  22. 14 14
      main/admin/user_fields_add.php
  23. 76 52
      main/admin/user_list.php
  24. 29 10
      main/attendance/attendance_calendar.php
  25. 53 9
      main/attendance/attendance_controller.php
  26. 12 2
      main/attendance/attendance_list.php
  27. 20 7
      main/attendance/attendance_sheet.php
  28. 11 0
      main/attendance/calendar_logins.php
  29. 12 4
      main/attendance/index.php
  30. 0 1
      main/attendance/layout.php
  31. 2 3
      main/calendar/agenda.lib.php
  32. 45 45
      main/calendar/allagendas.php
  33. 3 7
      main/calendar/ical_export.php
  34. 2 5
      main/calendar/print.php
  35. 95 39
      main/course_home/activity.php
  36. 15 12
      main/course_home/course_home.php
  37. 54 14
      main/course_info/infocours.php
  38. 28 20
      main/course_progress/thematic_controller.php
  39. 14 5
      main/coursecopy/classes/CourseArchiver.class.php
  40. 88 84
      main/coursecopy/classes/CourseBuilder.class.php
  41. 37 7
      main/coursecopy/classes/CourseCopyLearnpath.class.php
  42. 2 1
      main/coursecopy/classes/CourseCopyTestCategory.php
  43. 7 4
      main/coursecopy/classes/CourseDescription.class.php
  44. 2 2
      main/coursecopy/copy_course_session.php
  45. 119 0
      main/cron/hosting_total_size_limit.php
  46. 103 27
      main/cron/import_csv.php
  47. 4 7
      main/cron/user_import/client.php
  48. 1 0
      main/css/base.css
  49. 37 14
      main/document/document.inc.php
  50. 5 2
      main/document/slideshow.php
  51. 1 0
      main/document/upload.php
  52. 4 2
      main/dropbox/index.php
  53. 76 29
      main/exercice/exercice.php
  54. 361 330
      main/exercice/exercise.lib.php
  55. 2 2
      main/exercice/hotspot_savescore.inc.php
  56. 3 6
      main/exercice/hotspot_updatescore.inc.php
  57. 22 12
      main/exercice/savescores.php
  58. 10 8
      main/exercice/showinframes.php
  59. 7 3
      main/forum/editpost.php
  60. 118 87
      main/forum/forumfunction.inc.php
  61. 3 6
      main/forum/forumsearch.php
  62. 4 10
      main/forum/iframe_thread.php
  63. 43 37
      main/forum/index.php
  64. 3 2
      main/forum/newthread.php
  65. 8 3
      main/forum/reply.php
  66. 26 18
      main/forum/viewforum.php
  67. 4 3
      main/forum/viewforumcategory.php
  68. 19 14
      main/forum/viewthread.php
  69. 18 4
      main/gradebook/gradebook.php
  70. 9 7
      main/gradebook/gradebook_add_cat.php
  71. 17 13
      main/gradebook/gradebook_add_eval.php
  72. 16 11
      main/gradebook/gradebook_add_link.php
  73. 13 7
      main/gradebook/gradebook_add_link_select_course.php
  74. 14 4
      main/gradebook/gradebook_add_result.php
  75. 56 51
      main/gradebook/gradebook_display_certificate.php
  76. 6 5
      main/gradebook/gradebook_edit_all.php
  77. 53 9
      main/gradebook/gradebook_flatview.php
  78. 43 7
      main/gradebook/gradebook_view_result.php
  79. 38 17
      main/gradebook/index.php
  80. 33 17
      main/gradebook/lib/be/abstractlink.class.php
  81. 150 145
      main/gradebook/lib/be/attendancelink.class.php
  82. 172 86
      main/gradebook/lib/be/category.class.php
  83. 39 42
      main/gradebook/lib/be/dropboxlink.class.php
  84. 1 1
      main/gradebook/lib/be/evallink.class.php
  85. 286 285
      main/gradebook/lib/be/evaluation.class.php
  86. 63 68
      main/gradebook/lib/be/exerciselink.class.php
  87. 197 179
      main/gradebook/lib/be/forumthreadlink.class.php
  88. 2 5
      main/gradebook/lib/be/gradebookitem.class.php
  89. 141 126
      main/gradebook/lib/be/learnpathlink.class.php
  90. 54 54
      main/gradebook/lib/be/linkfactory.class.php
  91. 12 16
      main/gradebook/lib/be/result.class.php
  92. 221 179
      main/gradebook/lib/be/studentpublicationlink.class.php
  93. 152 125
      main/gradebook/lib/be/surveylink.class.php
  94. 30 32
      main/gradebook/lib/fe/catform.class.php
  95. 24 27
      main/gradebook/lib/fe/dataform.class.php
  96. 107 71
      main/gradebook/lib/fe/displaygradebook.php
  97. 8 14
      main/gradebook/lib/fe/evalform.class.php
  98. 117 117
      main/gradebook/lib/fe/exportgradebook.php
  99. 16 16
      main/gradebook/lib/fe/flatviewtable.class.php
  100. 146 144
      main/gradebook/lib/fe/gradebooktable.class.php

+ 2 - 1
composer.json

@@ -5,6 +5,7 @@
         "toin0u/digitalocean": "~1.4",
         "twig/twig": "1.*",
         "michelf/php-markdown": "1.4.1",
-        "emojione/emojione": "1.3.0"
+        "emojione/emojione": "1.3.0",
+        "zendframework/zend-config": "2.3.3"
     }
 }

+ 140 - 32
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
         "This file is @generated automatically"
     ],
-    "hash": "3de2d83995130ea086a473db7a35a0a9",
+    "hash": "1abe77cf0b8752805b4ac0e3cde352b0",
     "packages": [
         {
             "name": "alchemy/binary-driver",
@@ -482,16 +482,16 @@
         },
         {
             "name": "sabre/vobject",
-            "version": "3.3.3",
+            "version": "3.3.4",
             "source": {
                 "type": "git",
                 "url": "https://github.com/fruux/sabre-vobject.git",
-                "reference": "de508f160e811c09b5e651909eb20b9e058a043c"
+                "reference": "e7cbc59a7a77325dfa32924865e1802c9216a3e0"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/fruux/sabre-vobject/zipball/de508f160e811c09b5e651909eb20b9e058a043c",
-                "reference": "de508f160e811c09b5e651909eb20b9e058a043c",
+                "url": "https://api.github.com/repos/fruux/sabre-vobject/zipball/e7cbc59a7a77325dfa32924865e1802c9216a3e0",
+                "reference": "e7cbc59a7a77325dfa32924865e1802c9216a3e0",
                 "shasum": ""
             },
             "require": {
@@ -544,21 +544,21 @@
                 "jCard",
                 "vCard"
             ],
-            "time": "2014-10-09 15:59:25"
+            "time": "2014-11-19 22:15:24"
         },
         {
             "name": "symfony/console",
-            "version": "v2.5.6",
+            "version": "v2.6.1",
             "target-dir": "Symfony/Component/Console",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/Console.git",
-                "reference": "6f177fca24200a5b97aef5ce7a5c98124a0f0db0"
+                "reference": "ef825fd9f809d275926547c9e57cbf14968793e8"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/Console/zipball/6f177fca24200a5b97aef5ce7a5c98124a0f0db0",
-                "reference": "6f177fca24200a5b97aef5ce7a5c98124a0f0db0",
+                "url": "https://api.github.com/repos/symfony/Console/zipball/ef825fd9f809d275926547c9e57cbf14968793e8",
+                "reference": "ef825fd9f809d275926547c9e57cbf14968793e8",
                 "shasum": ""
             },
             "require": {
@@ -566,16 +566,18 @@
             },
             "require-dev": {
                 "psr/log": "~1.0",
-                "symfony/event-dispatcher": "~2.1"
+                "symfony/event-dispatcher": "~2.1",
+                "symfony/process": "~2.1"
             },
             "suggest": {
                 "psr/log": "For using the console logger",
-                "symfony/event-dispatcher": ""
+                "symfony/event-dispatcher": "",
+                "symfony/process": ""
             },
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "2.5-dev"
+                    "dev-master": "2.6-dev"
                 }
             },
             "autoload": {
@@ -599,21 +601,21 @@
             ],
             "description": "Symfony Console Component",
             "homepage": "http://symfony.com",
-            "time": "2014-10-05 13:57:04"
+            "time": "2014-12-02 20:19:20"
         },
         {
             "name": "symfony/filesystem",
-            "version": "v2.5.6",
+            "version": "v2.6.1",
             "target-dir": "Symfony/Component/Filesystem",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/Filesystem.git",
-                "reference": "4e62fab0060a826561c78b665925b37c870c45f5"
+                "reference": "ff6efc95256cb33031933729e68b01d720b5436b"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/Filesystem/zipball/4e62fab0060a826561c78b665925b37c870c45f5",
-                "reference": "4e62fab0060a826561c78b665925b37c870c45f5",
+                "url": "https://api.github.com/repos/symfony/Filesystem/zipball/ff6efc95256cb33031933729e68b01d720b5436b",
+                "reference": "ff6efc95256cb33031933729e68b01d720b5436b",
                 "shasum": ""
             },
             "require": {
@@ -622,7 +624,7 @@
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "2.5-dev"
+                    "dev-master": "2.6-dev"
                 }
             },
             "autoload": {
@@ -646,21 +648,21 @@
             ],
             "description": "Symfony Filesystem Component",
             "homepage": "http://symfony.com",
-            "time": "2014-09-22 09:14:18"
+            "time": "2014-12-02 20:19:20"
         },
         {
             "name": "symfony/process",
-            "version": "v2.5.6",
+            "version": "v2.6.1",
             "target-dir": "Symfony/Component/Process",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/Process.git",
-                "reference": "9bbacbb3a7a27b17c0d51e2f126f59e0e588ad3a"
+                "reference": "bf0c9bd625f13b0b0bbe39919225cf145dfb935a"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/Process/zipball/9bbacbb3a7a27b17c0d51e2f126f59e0e588ad3a",
-                "reference": "9bbacbb3a7a27b17c0d51e2f126f59e0e588ad3a",
+                "url": "https://api.github.com/repos/symfony/Process/zipball/bf0c9bd625f13b0b0bbe39919225cf145dfb935a",
+                "reference": "bf0c9bd625f13b0b0bbe39919225cf145dfb935a",
                 "shasum": ""
             },
             "require": {
@@ -669,7 +671,7 @@
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "2.5-dev"
+                    "dev-master": "2.6-dev"
                 }
             },
             "autoload": {
@@ -693,21 +695,21 @@
             ],
             "description": "Symfony Process Component",
             "homepage": "http://symfony.com",
-            "time": "2014-10-01 05:50:18"
+            "time": "2014-12-02 20:19:20"
         },
         {
             "name": "symfony/yaml",
-            "version": "v2.5.6",
+            "version": "v2.6.1",
             "target-dir": "Symfony/Component/Yaml",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/Yaml.git",
-                "reference": "2d9f527449cabfa8543dd7fa3a466d6ae83d6726"
+                "reference": "3346fc090a3eb6b53d408db2903b241af51dcb20"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/Yaml/zipball/2d9f527449cabfa8543dd7fa3a466d6ae83d6726",
-                "reference": "2d9f527449cabfa8543dd7fa3a466d6ae83d6726",
+                "url": "https://api.github.com/repos/symfony/Yaml/zipball/3346fc090a3eb6b53d408db2903b241af51dcb20",
+                "reference": "3346fc090a3eb6b53d408db2903b241af51dcb20",
                 "shasum": ""
             },
             "require": {
@@ -716,7 +718,7 @@
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "2.5-dev"
+                    "dev-master": "2.6-dev"
                 }
             },
             "autoload": {
@@ -740,7 +742,7 @@
             ],
             "description": "Symfony Yaml Component",
             "homepage": "http://symfony.com",
-            "time": "2014-10-01 05:50:18"
+            "time": "2014-12-02 20:19:20"
         },
         {
             "name": "toin0u/digitalocean",
@@ -918,6 +920,112 @@
                 "templating"
             ],
             "time": "2014-10-17 12:53:44"
+        },
+        {
+            "name": "zendframework/zend-config",
+            "version": "2.3.3",
+            "target-dir": "Zend/Config",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/zendframework/Component_ZendConfig.git",
+                "reference": "a9ad512e1482461a5b500ee3fcf2d06ec9c7c7e8"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/zendframework/Component_ZendConfig/zipball/a9ad512e1482461a5b500ee3fcf2d06ec9c7c7e8",
+                "reference": "a9ad512e1482461a5b500ee3fcf2d06ec9c7c7e8",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.23",
+                "zendframework/zend-stdlib": "self.version"
+            },
+            "require-dev": {
+                "zendframework/zend-filter": "self.version",
+                "zendframework/zend-i18n": "self.version",
+                "zendframework/zend-json": "self.version",
+                "zendframework/zend-servicemanager": "self.version"
+            },
+            "suggest": {
+                "zendframework/zend-filter": "Zend\\Filter component",
+                "zendframework/zend-i18n": "Zend\\I18n component",
+                "zendframework/zend-json": "Zend\\Json to use the Json reader or writer classes",
+                "zendframework/zend-servicemanager": "Zend\\ServiceManager for use with the Config Factory to retrieve reader and writer instances"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.3-dev",
+                    "dev-develop": "2.4-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Zend\\Config\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "description": "provides a nested object property based user interface for accessing this configuration data within application code",
+            "homepage": "https://github.com/zendframework/zf2",
+            "keywords": [
+                "config",
+                "zf2"
+            ],
+            "time": "2014-09-16 22:58:11"
+        },
+        {
+            "name": "zendframework/zend-stdlib",
+            "version": "2.3.3",
+            "target-dir": "Zend/Stdlib",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/zendframework/Component_ZendStdlib.git",
+                "reference": "fa33e6647f830d0d2a1cb451efcdfe1bb9a66c33"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/zendframework/Component_ZendStdlib/zipball/fa33e6647f830d0d2a1cb451efcdfe1bb9a66c33",
+                "reference": "fa33e6647f830d0d2a1cb451efcdfe1bb9a66c33",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.23"
+            },
+            "require-dev": {
+                "zendframework/zend-eventmanager": "self.version",
+                "zendframework/zend-serializer": "self.version",
+                "zendframework/zend-servicemanager": "self.version"
+            },
+            "suggest": {
+                "zendframework/zend-eventmanager": "To support aggregate hydrator usage",
+                "zendframework/zend-serializer": "Zend\\Serializer component",
+                "zendframework/zend-servicemanager": "To support hydrator plugin manager usage"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.3-dev",
+                    "dev-develop": "2.4-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Zend\\Stdlib\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "homepage": "https://github.com/zendframework/zf2",
+            "keywords": [
+                "stdlib",
+                "zf2"
+            ],
+            "time": "2014-09-16 22:58:11"
         }
     ],
     "packages-dev": [],

+ 0 - 1
main/admin/access_url_check_user_session.php

@@ -56,7 +56,6 @@ $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' O
 
 $session_list = SessionManager::get_sessions_list();
 
-
 $html = '';
 $show_users_with_problems = isset($_REQUEST['show_users_with_problems']) && $_REQUEST['show_users_with_problems'] == 1 ? true : false;
 if ($show_users_with_problems) {

+ 2 - 0
main/admin/access_url_edit.php

@@ -159,3 +159,5 @@ $form->addElement('file','url_image_3','URL Image 3 (PNG)');
 // Submit button
 $form->addElement('style_submit_button', 'submit', $submit_name, 'class="add"');
 $form->display();
+
+Display::display_footer();

+ 6 - 4
main/admin/add_sessions_to_promotion.php

@@ -93,7 +93,7 @@ if (isset($_POST['form_sent']) && $_POST['form_sent']) {
 }
 
 $promotion_data = $promotion->get($id);
-$session_list   = SessionManager::get_sessions_list(array(), array('name'));
+$session_list = SessionManager::get_sessions_list(array(), array('name'));
 $session_not_in_promotion = $session_in_promotion= array();
 
 if (!empty($session_list)) {
@@ -126,17 +126,19 @@ function search_sessions($needle, $type)
         $needle = Database::escape_string($needle);
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
 
-        $session_list = SessionManager::get_sessions_list(array('s.name LIKE' => "$needle%"));
+        $session_list = SessionManager::get_sessions_list(
+            array('s.name' => array('operator' => 'LIKE', 'value' => "$needle%"))
+        );
         $return .= '<select id="session_not_in_promotion" name="session_not_in_promotion_name[]" multiple="multiple" size="15" style="width:360px;">';
-        foreach ($session_list as $row ) {
+        foreach ($session_list as $row) {
             if (!in_array($row['id'], array_keys($session_in_promotion))) {
                 $return .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
             }
         }
         $return .= '</select>';
         $xajax_response -> addAssign('ajax_list_multiple','innerHTML',api_utf8_encode($return));
-
     }
+
     return $xajax_response;
 }
 $xajax->processRequests();

+ 13 - 22
main/admin/add_sessions_to_usergroup.php

@@ -98,7 +98,7 @@ if (isset($_POST['form_sent']) && $_POST['form_sent']) {
         $elements_posted = array();
     }
     if ($form_sent == 1) {
-        //added a parameter to send emails when registering a user        
+        //added a parameter to send emails when registering a user
         $usergroup->subscribe_sessions_to_usergroup($id, $elements_posted);
         header('Location: usergroups.php');
         exit;
@@ -145,9 +145,13 @@ function search_sessions($needle,$type) {
                 $order_clause.
                 ' LIMIT 11';*/
         } else if ($type == 'searchbox') {
-            $session_list = SessionManager::get_sessions_list(array('s.name LIKE' => "%$needle%"));
+            $session_list = SessionManager::get_sessions_list(
+                array('s.name' => array('operator' => 'LIKE', 'value' => "%$needle%"))
+            );
         } else {
-            $session_list = SessionManager::get_sessions_list(array('s.name LIKE' => "$needle%"));
+            $session_list = SessionManager::get_sessions_list(
+                array('s.name' => array('operator' => 'LIKE', 'value' => "$needle%"))
+            );
         }
         $i=0;
         if ($type=='single') {
@@ -189,13 +193,10 @@ if ($add_type == 'multiple') {
 }
 
 echo '<div class="actions">';
-echo '<a href="usergroups.php">'.Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>'; 
+echo '<a href="usergroups.php">'.Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '<a href="javascript://" class="advanced_parameters" style="margin-top: 8px" onclick="display_advanced_search();"><span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).' '.get_lang('AdvancedSearch').'</span></a>';
 echo '</div>';
-
-?>
-
-<?php echo '<div id="advancedSearch" style="display: none">'. get_lang('SearchSessions'); ?> :
+echo '<div id="advancedSearch" style="display: none">'. get_lang('SearchSessions'); ?> :
      <input name="SearchSession" onchange = "xajax_search_sessions(this.value,'searchbox')" onkeyup="this.onchange()">
      </div>
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?id=<?php echo $id; if(!empty($_GET['add'])) echo '&add=true' ; ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?>>
@@ -262,8 +263,8 @@ if(!empty($errorMsg)) {
 <tr>
   <td align="center">
   <div id="content_source">
-      <?php           
-      if (!($add_type=='multiple')) {        
+      <?php
+      if (!($add_type=='multiple')) {
         ?>
         <input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,'single')" />
         <div id="ajax_list_users_single"></div>
@@ -313,9 +314,7 @@ if(!empty($errorMsg)) {
 </form>
 
 <script type="text/javascript">
-<!--
-function moveItem(origin , destination){
-
+function moveItem(origin , destination) {
     for(var i = 0 ; i<origin.options.length ; i++) {
         if(origin.options[i].selected) {
             destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
@@ -325,11 +324,9 @@ function moveItem(origin , destination){
     }
     destination.selectedIndex = -1;
     sortOptions(destination.options);
-
 }
 
 function sortOptions(options) {
-
     newOptions = new Array();
     for (i = 0 ; i<options.length ; i++)
         newOptions[i] = options[i];
@@ -338,7 +335,6 @@ function sortOptions(options) {
     options.length = 0;
     for(i = 0 ; i < newOptions.length ; i++)
         options[i] = newOptions[i];
-
 }
 
 function mysort(a, b){
@@ -358,10 +354,8 @@ function valide(){
     document.forms.formulaire.submit();
 }
 
-function loadUsersInSelect(select){
-
+function loadUsersInSelect(select) {
     var xhr_object = null;
-
     if(window.XMLHttpRequest) // Firefox
         xhr_object = new XMLHttpRequest();
     else if(window.ActiveXObject) // Internet Explorer
@@ -370,10 +364,7 @@ function loadUsersInSelect(select){
     alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
 
     xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
     xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
     nosessionUsers = makepost(document.getElementById('elements_not_in'));
     sessionUsers = makepost(document.getElementById('elements_in'));
     nosessionClasses = makepost(document.getElementById('origin_classes'));

+ 25 - 21
main/admin/add_users_to_session.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
 *	@package chamilo.admin
 */
@@ -82,12 +83,9 @@ function search_users($needle, $type)
 
         // xajax send utf8 datas... datas in db can be non-utf8 datas
         $charset = api_get_system_encoding();
-        $needle = Database::escape_string($needle);
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
-
+        $needle = Database::escape_string($needle);
         $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-
-
         $showOfficialCode = false;
         global $_configuration;
         if (isset($_configuration['order_user_list_by_official_code']) &&
@@ -117,7 +115,6 @@ function search_users($needle, $type)
                 $cond_user_id = ' AND user.user_id NOT IN('.implode(",",$user_ids).')';
             }
         }
-
         switch ($type) {
             case 'single':
                 // search users where username or firstname or lastname begins likes $needle
@@ -128,14 +125,19 @@ function search_users($needle, $type)
                                 username LIKE "'.$needle.'%" OR
                                 firstname LIKE "'.$needle.'%" OR
                                 lastname LIKE "'.$needle.'%"
-                            ) AND user.status<>6 AND user.status<>'.DRH.''.
+                            ) AND
+                            user.status <> 6 AND
+                            user.status <> '.DRH.''.
                         $order_clause.'
                         LIMIT 11';
                 break;
             case 'multiple':
                 $sql = 'SELECT user.user_id, username, lastname, firstname, official_code
                         FROM '.$tbl_user.' user
-                        WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user.status<>'.DRH.' AND user.status<>6 '.$cond_user_id.
+                        WHERE
+                            '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND
+                            user.status <> '.DRH.' AND
+                            user.status <> 6 '.$cond_user_id.
                         $order_clause;
                 break;
             case 'any_session':
@@ -154,7 +156,7 @@ function search_users($needle, $type)
             $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
             $access_url_id = api_get_current_access_url_id();
             if ($access_url_id != -1) {
-                switch($type) {
+                switch ($type) {
                     case 'single':
                         $sql = 'SELECT user.user_id, username, lastname, firstname, official_code
                         FROM '.$tbl_user.' user
@@ -165,7 +167,8 @@ function search_users($needle, $type)
                                 username LIKE "'.$needle.'%" OR
                                 firstname LIKE "'.$needle.'%" OR
                                 lastname LIKE "'.$needle.'%"
-                            ) AND user.status<>6 AND user.status<>'.DRH.' '.
+                            ) AND user.status<>6 AND
+                            user.status<>'.DRH.' '.
                         $order_clause.
                         ' LIMIT 11';
                         break;
@@ -195,7 +198,7 @@ function search_users($needle, $type)
                 }
             }
         }
-
+        //echo Database::fixQuery($sql);
         $rs = Database::query($sql);
         $i = 0;
         if ($type=='single') {
@@ -219,19 +222,18 @@ function search_users($needle, $type)
             global $nosessionUsersList;
             $return .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
             while ($user = Database :: fetch_array($rs)) {
-
                 $person_name = api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].') '.$user['official_code'];
                 if ($showOfficialCode) {
                     $officialCode = !empty($user['official_code']) ? $user['official_code'].' - ' : '? - ';
                     $person_name = $officialCode.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')';
                 }
-
 	            $return .= '<option value="'.$user['user_id'].'">'.$person_name.' </option>';
 			}
 			$return .= '</select>';
 			$xajax_response -> addAssign('ajax_list_users_multiple','innerHTML',api_utf8_encode($return));
 		}
 	}
+
 	return $xajax_response;
 }
 
@@ -284,11 +286,11 @@ function change_select(val) {
 }
 </script>';
 
-$form_sent=0;
-$errorMsg=$firstLetterUser=$firstLetterSession='';
-$UserList=$SessionList=array();
-$sessions=array();
-$noPHP_SELF=true;
+$form_sent = 0;
+$errorMsg = $firstLetterUser = $firstLetterSession = '';
+$UserList = $SessionList = array();
+$sessions = array();
+$noPHP_SELF = true;
 
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     $form_sent             = $_POST['form_sent'];
@@ -330,7 +332,8 @@ if ($ajax_search) {
     $sql = "SELECT user_id, lastname, firstname, username, id_session, official_code
             FROM $tbl_user u
             INNER JOIN $tbl_session_rel_user
-                ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+                ON $tbl_session_rel_user.id_user = u.user_id AND
+                $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
                 AND $tbl_session_rel_user.id_session = ".intval($id_session)."
             WHERE u.status<>".DRH." AND u.status<>6
             $order_clause";
@@ -342,7 +345,8 @@ if ($ajax_search) {
             $sql="SELECT u.user_id, lastname, firstname, username, id_session, official_code
             FROM $tbl_user u
             INNER JOIN $tbl_session_rel_user
-                ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+                ON $tbl_session_rel_user.id_user = u.user_id AND
+                $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
                 AND $tbl_session_rel_user.id_session = ".intval($id_session)."
             INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
             WHERE access_url_id = $access_url_id AND u.status<>".DRH." AND u.status<>6
@@ -438,8 +442,8 @@ if ($ajax_search) {
         }
     }
 
-    $result   = Database::query($sql);
-    $users    = Database::store_result($result,'ASSOC');
+    $result = Database::query($sql);
+    $users = Database::store_result($result,'ASSOC');
     foreach ($users as $uid => $user) {
         if ($user['id_session'] != $id_session) {
             $nosessionUsersList[$user['user_id']] = array(

+ 25 - 1
main/admin/course_edit.php

@@ -273,6 +273,31 @@ $form->setDefaults($course);
 // Validate form
 if ($form->validate()) {
     $course = $form->getSubmitValues();
+
+    $visibility = $course['visibility'];
+
+    global $_configuration;
+    $urlId = api_get_current_access_url_id();
+    if (isset($_configuration[$urlId]) &&
+        isset($_configuration[$urlId]['hosting_limit_active_courses']) &&
+        $_configuration[$urlId]['hosting_limit_active_courses'] > 0
+    ) {
+        // Check if
+        if ($course_info['visibility'] == COURSE_VISIBILITY_HIDDEN &&
+            $visibility != $course_info['visibility']
+        ) {
+            $num = CourseManager::countActiveCourses($urlId);
+            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
+                api_warn_hosting_contact('hosting_limit_active_courses');
+
+                api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
+
+                header('Location: course_list.php?action=show_msg&warn=' . urlencode(get_lang('PortalActiveCoursesLimitReached')));
+                exit;
+            }
+        }
+    }
+
     $course_code = $course['code'];
     $visual_code = $course['visual_code'];
     $visual_code = generate_course_code($visual_code);
@@ -317,7 +342,6 @@ if ($form->validate()) {
 	$course_language = $course['course_language'];
     $course['disk_quota'] = $course['disk_quota']*1024*1024;
 	$disk_quota = $course['disk_quota'];
-	$visibility = $course['visibility'];
 	$subscribe = $course['subscribe'];
 	$unsubscribe = $course['unsubscribe'];
 

+ 68 - 28
main/admin/course_list.php

@@ -23,36 +23,56 @@ $sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : null;
 /**
  * Get the number of courses which will be displayed
  */
-function get_number_of_courses() {
+function get_number_of_courses()
+{
     $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
     $sql = "SELECT COUNT(code) AS total_number_of_items FROM $course_table";
 
-    if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
+    if ((api_is_platform_admin() || api_is_session_admin()) &&
+        api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1
+    ) {
         $access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";
     }
 
     if (isset ($_GET['keyword'])) {
-        $keyword = Database::escape_string($_GET['keyword']);
-        $sql .= " WHERE (title LIKE '%".$keyword."%' OR code LIKE '%".$keyword."%' OR visual_code LIKE '%".$keyword."%')";
-    } elseif (isset ($_GET['keyword_code'])) {
-        $keyword_code = Database::escape_string($_GET['keyword_code']);
-        $keyword_title = Database::escape_string($_GET['keyword_title']);
-        $keyword_category = Database::escape_string($_GET['keyword_category']);
-        $keyword_language = Database::escape_string($_GET['keyword_language']);
-        $keyword_visibility = Database::escape_string($_GET['keyword_visibility']);
+        $keyword = Database::escape_string("%".$_GET['keyword']."%");
+        $sql .= " WHERE (
+                        title LIKE '".$keyword."' OR
+                        code LIKE '".$keyword."' OR
+                        visual_code LIKE '".$keyword."'
+                )
+        ";
+    } elseif (isset($_GET['keyword_code'])) {
+        $keyword_code = Database::escape_string("%".$_GET['keyword_code']."%");
+        $keyword_title = Database::escape_string("%".$_GET['keyword_title']."%");
+        $keyword_category = Database::escape_string("%".$_GET['keyword_category']."%");
+        $keyword_language = Database::escape_string("%".$_GET['keyword_language']."%");
+        $keyword_visibility = Database::escape_string("%".$_GET['keyword_visibility']."%");
         $keyword_subscribe = Database::escape_string($_GET['keyword_subscribe']);
         $keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
-        $sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
+
+        $sql .= " WHERE
+                    (code LIKE '".$keyword_code."' OR visual_code LIKE '".$keyword_code."') AND
+                    title LIKE '".$keyword_title."' AND
+                    category_code LIKE '".$keyword_category."' AND
+                    course_language LIKE '".$keyword_language."' AND
+                    visibility LIKE '".$keyword_visibility."' AND
+                    subscribe LIKE '".$keyword_subscribe."' AND
+                    unsubscribe LIKE '".$keyword_unsubscribe."'
+        ";
     }
 
     // adding the filter to see the user's only of the current access_url
-    if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
+    if ((api_is_platform_admin() || api_is_session_admin()) &&
+        api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1
+    ) {
         $sql.= " AND url_rel_course.access_url_id=".api_get_current_access_url_id();
     }
 
     $res = Database::query($sql);
     $obj = Database::fetch_object($res);
+
     return $obj->total_number_of_items;
 }
 
@@ -62,9 +82,11 @@ function get_number_of_courses() {
  * @param int $number_of_items
  * @param int $column
  * @param string $direction
+ *
  * @return array
  */
-function get_course_data($from, $number_of_items, $column, $direction) {
+function get_course_data($from, $number_of_items, $column, $direction)
+{
     $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
 
     $sql = "SELECT  code AS col0,
@@ -80,35 +102,52 @@ function get_course_data($from, $number_of_items, $column, $direction) {
                     visual_code
     		FROM $course_table";
 
-    if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
+    if ((api_is_platform_admin() || api_is_session_admin()) &&
+        api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1
+    ) {
         $access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";
     }
 
     if (isset ($_GET['keyword'])) {
-        $keyword = Database::escape_string(trim($_GET['keyword']));
-        $sql .= " WHERE (title LIKE '%".$keyword."%' OR code LIKE '%".$keyword."%' OR visual_code LIKE '%".$keyword."%' ) ";
-    } elseif (isset ($_GET['keyword_code'])) {
-        $keyword_code           = Database::escape_string($_GET['keyword_code']);
-        $keyword_title          = Database::escape_string($_GET['keyword_title']);
-        $keyword_category       = Database::escape_string($_GET['keyword_category']);
-        $keyword_language       = Database::escape_string($_GET['keyword_language']);
-        $keyword_visibility     = Database::escape_string($_GET['keyword_visibility']);
-        $keyword_subscribe      = Database::escape_string($_GET['keyword_subscribe']);
-        $keyword_unsubscribe    = Database::escape_string($_GET['keyword_unsubscribe']);
-        $sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
+        $keyword = Database::escape_string("%".trim($_GET['keyword'])."%");
+        $sql .= " WHERE (
+            title LIKE '".$keyword."' OR
+            code LIKE '".$keyword."' OR
+            visual_code LIKE '".$keyword."'
+        )
+        ";
+    } elseif (isset($_GET['keyword_code'])) {
+        $keyword_code = Database::escape_string("%".$_GET['keyword_code']."%");
+        $keyword_title = Database::escape_string("%".$_GET['keyword_title']."%");
+        $keyword_category = Database::escape_string("%".$_GET['keyword_category']."%");
+        $keyword_language = Database::escape_string("%".$_GET['keyword_language']."%");
+        $keyword_visibility = Database::escape_string("%".$_GET['keyword_visibility']."%");
+        $keyword_subscribe = Database::escape_string($_GET['keyword_subscribe']);
+        $keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
+
+        $sql .= " WHERE
+                (code LIKE '".$keyword_code."' OR visual_code LIKE '".$keyword_code."') AND
+                title LIKE '".$keyword_title."' AND
+                category_code LIKE '".$keyword_category."' AND
+                course_language LIKE '".$keyword_language."' AND
+                visibility LIKE '".$keyword_visibility."' AND
+                subscribe LIKE '".$keyword_subscribe."' AND
+                unsubscribe LIKE '".$keyword_unsubscribe."'";
     }
 
     // Adding the filter to see the user's only of the current access_url.
-    if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
+    if ((api_is_platform_admin() || api_is_session_admin()) &&
+        api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1
+    ) {
         $sql.= " AND url_rel_course.access_url_id=".api_get_current_access_url_id();
     }
 
     $sql .= " ORDER BY col$column $direction ";
-    $sql .= " LIMIT $from,$number_of_items";
+    $sql .= " LIMIT $from, $number_of_items";
 
     $res = Database::query($sql);
-    $courses = array ();
+    $courses = array();
     while ($course = Database::fetch_array($res)) {
         // Place colour icons in front of courses.
         $show_visual_code = $course['visual_code'] != $course[2] ? Display::label($course['visual_code'], 'info') : null;
@@ -118,6 +157,7 @@ function get_course_data($from, $number_of_items, $column, $direction) {
         $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]);
         $courses[] = $course_rem;
     }
+
     return $courses;
 }
 

+ 3 - 2
main/admin/course_request_accepted.php

@@ -92,8 +92,9 @@ function get_number_of_requests() {
 /**
  * Get course data to display
  */
-function get_request_data($from, $number_of_items, $column, $direction) {
-    $keyword = Database::escape_string(trim($_GET['keyword']));
+function get_request_data($from, $number_of_items, $column, $direction)
+{
+    $keyword = isset($_GET['keyword']) ? Database::escape_string(trim($_GET['keyword'])) : null;
     $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
 
     $sql = "SELECT id AS col0,

+ 8 - 6
main/admin/dashboard_add_courses_to_user.php

@@ -59,16 +59,17 @@ if (!api_is_platform_admin()) {
 	api_not_allowed(true);
 }
 
-function search_courses($needle,$type)
+function search_courses($needle, $type)
 {
-    global $_configuration, $tbl_course, $tbl_course_rel_user, $tbl_course_rel_access_url,$user_id;
+    global $_configuration, $tbl_course, $tbl_course_rel_access_url,$user_id;
 
     $xajax_response = new XajaxResponse();
     $return = '';
-    if(!empty($needle) && !empty($type)) {
+    if (!empty($needle) && !empty($type)) {
         // xajax send utf8 datas... datas in db can be non-utf8 datas
         $charset = api_get_system_encoding();
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
+		$needle = Database::escape_string($needle);
 
         $assigned_courses_to_hrm = CourseManager::get_courses_followed_by_drh($user_id);
         $assigned_courses_code = array_keys($assigned_courses_to_hrm);
@@ -190,9 +191,10 @@ if (count($assigned_courses_code) > 0) {
 }
 
 $needle = '%';
+$firstLetter = null;
 if (isset($_POST['firstLetterCourse'])) {
-	$needle = Database::escape_string($_POST['firstLetterCourse']);
-	$needle = "$needle%";
+	$firstLetter = $_POST['firstLetterCourse'];
+	$needle = Database::escape_string($firstLetter.'%');
 }
 
 if (api_is_multiple_url_enabled()) {
@@ -249,7 +251,7 @@ if(!empty($msg)) {
      <select name="firstLetterCourse" onchange = "xajax_search_courses(this.value,'multiple')">
       <option value="%">--</option>
       <?php
-      echo Display :: get_alphabet_options($_POST['firstLetterCourse']);
+      echo Display :: get_alphabet_options($firstLetter);
       ?>
      </select>
 </td>

+ 7 - 5
main/admin/dashboard_add_sessions_to_user.php

@@ -59,7 +59,7 @@ if (!api_is_platform_admin() && !api_is_session_admin()) {
     api_not_allowed(true);
 }
 
-function search_sessions($needle,$type)
+function search_sessions($needle, $type)
 {
     global $_configuration, $tbl_session_rel_access_url, $tbl_session, $user_id;
 
@@ -69,6 +69,7 @@ function search_sessions($needle,$type)
         // xajax send utf8 datas... datas in db can be non-utf8 datas
         $charset = api_get_system_encoding();
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
+        $needle = Database::escape_string($needle);
         $assigned_sessions_to_hrm = SessionManager::get_sessions_followed_by_drh($user_id);
         $assigned_sessions_id = array_keys($assigned_sessions_to_hrm);
 
@@ -93,6 +94,7 @@ function search_sessions($needle,$type)
         $return .= '</select>';
         $xajax_response->addAssign('ajax_list_sessions_multiple','innerHTML',api_utf8_encode($return));
     }
+
     return $xajax_response;
 }
 
@@ -192,8 +194,7 @@ if (count($assigned_sessions_id) > 0) {
 
 $needle = '%';
 if (!empty($firstLetterSession)) {
-    $needle = Database::escape_string($firstLetterSession);
-    $needle = "$needle%";
+    $needle = Database::escape_string($firstLetterSession.'%');
 }
 
 if (api_is_multiple_url_enabled()) {
@@ -222,7 +223,8 @@ $result	= Database::query($sql);
             <tr>
                 <td width="45%" align="center"><b><?php echo get_lang('SessionsListInPlatform') ?> :</b></td>
                 <td width="10%">&nbsp;</td>
-                <td align="center" width="45%"><b>
+                <td align="center" width="45%">
+                    <b>
                         <?php
                         if (UserManager::is_admin($user_id)) {
                             echo get_lang('AssignedSessionsListToPlatformAdministrator');
@@ -235,7 +237,7 @@ $result	= Database::query($sql);
                         : </b></td>
             </tr>
 
-            <?php if($add_type == 'multiple') { ?>
+            <?php if ($add_type == 'multiple') { ?>
                 <tr><td width="45%" align="center">
                         <?php echo get_lang('FirstLetterSession');?> :
                         <select name="firstLetterSession" onchange = "xajax_search_sessions(this.value, 'multiple')">

+ 74 - 0
main/admin/export_certificates.php

@@ -0,0 +1,74 @@
+<?php
+
+/* For licensing terms, see /license.txt */
+
+/**
+ *  @package chamilo.admin
+ */
+
+// Language files that need to be included.
+$language_file = array('admin');
+
+$cidReset = true;
+
+require_once '../inc/global.inc.php';
+
+require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
+
+Display::display_header(null);
+
+$form = new FormValidator('export_certificate');
+$courses = CourseManager::get_courses_list(0, 0, 'title');
+$options = array();
+foreach ($courses as $course) {
+    $options[$course['id']] = $course['title'];
+}
+$form->addElement('select', 'course', get_lang('Course'), $options);
+$form->addElement('file', 'file', get_lang('File'));
+$form->add_button('submit', get_lang('Submit'));
+$form->display();
+
+if ($form->validate()) {
+    $values = $form->getSubmitValues();
+    if (isset($_FILES['file']['tmp_name']) &&
+        !empty($_FILES['file']['tmp_name'])
+    ) {
+
+        $users = Import::csv_reader($_FILES['file']['tmp_name']);
+        $courseId = $values['course'];
+        $courseInfo = api_get_course_info_by_id($courseId);
+        $courseCode = $courseInfo['code'];
+
+        $cats = Category:: load(
+            null,
+            null,
+            $courseCode,
+            null,
+            null,
+            0,
+            false
+        );
+
+        if (isset($cats[0])) {
+            /** @var Category $cat */
+            $userList = array();
+            foreach ($users as $user) {
+                $userInfo = api_get_user_info_from_official_code(
+                    $user['official_code']
+                );
+                if (!empty($userInfo)) {
+                    $userList[] = $userInfo;
+                }
+            }
+
+            Category::exportAllCertificates(
+                $cat->get_id(),
+                $userList
+            );
+        }
+    }
+
+}
+
+Display :: display_footer();

+ 58 - 14
main/admin/extra_fields.php

@@ -118,16 +118,17 @@ switch ($action) {
         // The validation or display
         if ($form->validate()) {
             //if ($check) {
-                $values = $form->exportValues();
-                $res    = $obj->save($values);
-                if ($res) {
-                    Display::display_confirmation_message(get_lang('ItemAdded'));
-                }
+            $values = $form->exportValues();
+            $res    = $obj->save($values);
+            if ($res) {
+                Display::display_confirmation_message(get_lang('ItemAdded'));
+            }
             //}
             $obj->display();
         } else {
             echo '<div class="actions">';
-            echo '<a href="'.api_get_self().'?type='.$obj->type.'">'.Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
+            echo '<a href="'.api_get_self().'?type='.$obj->type.'">'.
+                Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
             echo '</div>';
             $form->addElement('hidden', 'sec_token');
             $form->setConstants(array('sec_token' => $token));
@@ -142,14 +143,15 @@ switch ($action) {
         // The validation or display
         if ($form->validate()) {
             //if ($check) {
-                $values = $form->exportValues();
-                $res    = $obj->update($values);
-                Display::display_confirmation_message(sprintf(get_lang('ItemUpdated'), $values['field_variable']), false);
+            $values = $form->exportValues();
+            $res    = $obj->update($values);
+            Display::display_confirmation_message(sprintf(get_lang('ItemUpdated'), $values['field_variable']), false);
             //}
             $obj->display();
         } else {
             echo '<div class="actions">';
-            echo '<a href="'.api_get_self().'?type='.$obj->type.'">'.Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
+            echo '<a href="'.api_get_self().'?type='.$obj->type.'">'.
+                Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
             echo '</div>';
             $form->addElement('hidden', 'sec_token');
             $form->setConstants(array('sec_token' => $token));
@@ -159,10 +161,10 @@ switch ($action) {
     case 'delete':
         // Action handling: delete
         //if ($check) {
-            $res = $obj->delete($_GET['id']);
-            if ($res) {
-                Display::display_confirmation_message(get_lang('ItemDeleted'));
-            }
+        $res = $obj->delete($_GET['id']);
+        if ($res) {
+            Display::display_confirmation_message(get_lang('ItemDeleted'));
+        }
         //}
         $obj->display();
         break;
@@ -207,6 +209,7 @@ CREATE TABLE IF NOT EXISTS lp_field_values(
     field_id int NOT NULL,
     field_value	text,
     comment VARCHAR(100) default '',
+    user_id int,
     tms DATETIME NOT NULL default '0000-00-00 00:00:00',
     PRIMARY KEY(id)
 );
@@ -215,4 +218,45 @@ ALTER TABLE lp_field_values ADD INDEX (lp_id, field_id);
 
 
 
+CREATE TABLE IF NOT EXISTS calendar_event_field(
+    id INT NOT NULL auto_increment,
+    field_type int NOT NULL DEFAULT 1,
+    field_variable	varchar(64) NOT NULL,
+    field_display_text	varchar(64),
+    field_default_value text,
+    field_order int,
+    field_visible tinyint default 0,
+    field_changeable tinyint default 0,
+    field_filter tinyint default 0,
+    tms	DATETIME NOT NULL default '0000-00-00 00:00:00',
+    PRIMARY KEY(id)
+);
+
+DROP TABLE IF EXISTS calendar_event_options;
+CREATE TABLE IF NOT EXISTS calendar_event_options (
+    id int NOT NULL auto_increment,
+    field_id int NOT NULL,
+    option_value text,
+    option_display_text varchar(64),
+    option_order int,
+    tms	DATETIME NOT NULL default '0000-00-00 00:00:00',
+    priority VARCHAR(255),
+    priority_message VARCHAR(255),
+    PRIMARY KEY (id)
+);
+
+DROP TABLE IF EXISTS calendar_event_values;
+CREATE TABLE IF NOT EXISTS calendar_event_values(
+    id bigint NOT NULL auto_increment,
+    calendar_event_id int unsigned NOT NULL,
+    user_id int,
+    field_id int NOT NULL,
+    field_value	text,
+    comment VARCHAR(100) default '',
+    tms DATETIME NOT NULL default '0000-00-00 00:00:00',
+    PRIMARY KEY(id)
+);
+
+
+
  */

+ 2 - 2
main/admin/group_add.php

@@ -1,5 +1,5 @@
 <?php
-/* For licensing terms, see /dokeos_license.txt */
+/* For licensing terms, see /license.txt */
 /**
 *	@package chamilo.admin
 */
@@ -169,4 +169,4 @@ if (!empty($message)) {
 $form->display();
 
 // Footer
-Display::display_footer();
+Display::display_footer();

+ 1 - 1
main/admin/group_list.php

@@ -1,6 +1,6 @@
 <?php
+/* For licensing terms, see /license.txt */
 
-/* For licensing terms, see /dokeos_license.txt */
 /**
   @author Bart Mollet
  * 	@package chamilo.admin

+ 3 - 2
main/admin/resume_session.php

@@ -13,7 +13,7 @@ require_once '../inc/global.inc.php';
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 
-$sessionId = isset($_GET['id_session']) ? $_GET['id_session'] : null;
+$sessionId = isset($_GET['id_session']) ? intval($_GET['id_session']) : null;
 
 if (empty($sessionId)) {
     api_not_allowed(true);
@@ -114,7 +114,8 @@ switch ($action) {
         }
 
         if (!empty($_GET['class'])) {
-            Database::query("DELETE FROM $tbl_session_rel_class WHERE session_id='$sessionId' AND class_id=".Database::escape_string($_GET['class']));
+            Database::query("DELETE FROM $tbl_session_rel_class
+                             WHERE session_id='$sessionId' AND class_id=".intval($_GET['class']));
             $nbr_affected_rows=Database::affected_rows();
             Database::query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$sessionId'");
         }

+ 9 - 4
main/admin/session_course_edit.php

@@ -12,7 +12,7 @@ require_once '../inc/global.inc.php';
 
 $id_session = intval($_GET['id_session']);
 SessionManager::protect_session_edit($id_session);
-$course_code = Database::escape_string($_GET['course_code']);
+$course_code = $_GET['course_code'];
 
 $formSent=0;
 $errorMsg='';
@@ -47,7 +47,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 
 	// get all tutor by course_code in the session
 	$sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user
-	        WHERE id_session = '$id_session' AND course_code = '$course_code' AND status = 2";
+	        WHERE id_session = '$id_session' AND course_code = '".Database::escape_string($course_code)."' AND status = 2";
 	$rs_coachs = Database::query($sql);
 
 	$coachs_course_session = array();
@@ -70,7 +70,12 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 		$array_intersect = array_diff($coachs_course_session,$id_coachs);
 
 		foreach ($array_intersect as $nocoach_user_id) {
-			$rs2 = SessionManager::set_coach_to_course_session($nocoach_user_id, $id_session, $course_code,true);
+			$rs2 = SessionManager::set_coach_to_course_session(
+				$nocoach_user_id,
+				$id_session,
+				$course_code,
+				true
+			);
 		}
 
 		header('Location: '.Security::remove_XSS($_GET['page']).'?id_session='.$id_session);
@@ -79,7 +84,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 	}
 } else {
 	$sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user
-	        WHERE id_session = '$id_session' AND course_code = '$course_code' AND status = 2 ";
+	        WHERE id_session = '$id_session' AND course_code = '".Database::escape_string($course_code)."' AND status = 2 ";
 	$rs = Database::query($sql);
 
 	if (Database::num_rows($rs) > 0) {

+ 89 - 47
main/admin/sub_language.class.php

@@ -1,26 +1,29 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
- * SubLanguageManager class definition file
+ * Class SubLanguageManager
  * @package chamilo.admin.sublanguage
  * @todo clean this lib and move to main/inc/lib
  */
-class SubLanguageManager {
-
-    private function __construct() {
-        //void
+class SubLanguageManager
+{
+    /**
+     * Constructor
+     */
+    public function __construct()
+    {
     }
 
     /**
      * Get all files of lang folder (forum.inc.php,gradebook.inc.php,notebook.inc.php)
      * @param String The lang path folder  (/var/www/my_lms/main/lang/spanish)
      * @param bool true if we only want the "subname" trad4all instead of  trad4all.inc.php
-     * @return Array All file of lang folder
      *
+     * @return Array All file of lang folder
      */
-    public static function get_lang_folder_files_list($path, $only_main_name = false) {
+    public static function get_lang_folder_files_list($path, $only_main_name = false)
+    {
         $content_dir = array();
         if (is_dir($path)) {
             if ($dh = opendir($path)) {
@@ -46,9 +49,11 @@ class SubLanguageManager {
      * @param Integer The sub language id
      * @return Array All information about sub-language
      */
-    public static function get_all_information_of_sub_language($parent_id, $sub_language_id) {
+    public static function get_all_information_of_sub_language($parent_id, $sub_language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql = 'SELECT * FROM ' . $tbl_admin_languages . ' WHERE parent_id="' . Database::escape_string($parent_id) . '" AND id="' . Database::escape_string($sub_language_id) . '"';
+        $sql = 'SELECT * FROM ' . $tbl_admin_languages . '
+                WHERE parent_id="' . Database::escape_string($parent_id) . '" AND id="' . Database::escape_string($sub_language_id) . '"';
         $rs = Database::query($sql);
         $all_information = array();
         while ($row = Database::fetch_array($rs, 'ASSOC')) {
@@ -62,7 +67,8 @@ class SubLanguageManager {
      * @param Integer The parent id(Language father id)
      * @return Array All information about language
      */
-    public static function get_all_information_of_language($parent_id) {
+    public static function get_all_information_of_language($parent_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $sql = 'SELECT * FROM ' . $tbl_admin_languages . ' WHERE id = "' . intval($parent_id) . '"';
         $rs = Database::query($sql);
@@ -79,7 +85,8 @@ class SubLanguageManager {
      * @patam Bool Whether we want to remove the '$' prefix in the results or not
      * @return Array Contains all information of chamilo file
      */
-    public static function get_all_language_variable_in_file($system_path_file, $get_as_string_index = false) {
+    public static function get_all_language_variable_in_file($system_path_file, $get_as_string_index = false)
+    {
         $res_list = array();
         if (!is_readable($system_path_file)) {
             return $res_list;
@@ -97,6 +104,7 @@ class SubLanguageManager {
             }
             $res_list[$var] = $val;
         }
+
         return $res_list;
     }
 
@@ -105,8 +113,8 @@ class SubLanguageManager {
      * @param String The chamilo path file (/var/www/chamilo/main/lang/spanish/gradebook.inc.php)
      * @return bool
      */
-    public static function add_file_in_language_directory($system_path_file) {
-        $return_value = false;
+    public static function add_file_in_language_directory($system_path_file)
+    {
         $return_value = @file_put_contents($system_path_file, '<?php' . PHP_EOL);
         return $return_value;
     }
@@ -118,7 +126,8 @@ class SubLanguageManager {
      * @param String The language variable
      * @return Boolean True on success, False on error
      */
-    public static function write_data_in_file($path_file, $new_term, $new_variable) {
+    public static function write_data_in_file($path_file, $new_term, $new_variable)
+    {
         $return_value = false;
         $new_data = $new_variable . '=' . $new_term;
         $resource = @fopen($path_file, "a");
@@ -131,15 +140,17 @@ class SubLanguageManager {
             }
             fclose($resource);
         }
+
         return $return_value;
     }
 
     /**
      * Add directory for sub-language
-     * @param String The sub-language directory ( e.g. 'spanish_corporate' )
+     * @param string $sub_language_dir The sub-language directory ( e.g. 'spanish_corporate' )
      * @return boolean  True on success, false on failure
      */
-    public static function add_language_directory($sub_language_dir) {
+    public static function add_language_directory($sub_language_dir)
+    {
         if (empty($sub_language_dir)) {
             return false;
         }
@@ -153,15 +164,17 @@ class SubLanguageManager {
     /**
      * Delete sub-language.
      * In order to avoid deletion of main laguages, we check the existence of a parent
-     * @param Integer The parent id
+     * @param int The parent id
      * @return bool    True on success, false on error
      */
-    public static function remove_sub_language($parent_id, $sub_language_id) {
+    public static function remove_sub_language($parent_id, $sub_language_id)
+    {
         if (empty($parent_id) or (intval($parent_id) != $parent_id) or empty($sub_language_id) or (intval($sub_language_id) != $sub_language_id)) {
             return false;
         }
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql = 'SELECT dokeos_folder FROM ' . $tbl_admin_languages . ' WHERE parent_id = ' . $parent_id . ' and id = ' . $sub_language_id;
+        $sql = 'SELECT dokeos_folder FROM ' . $tbl_admin_languages . '
+                WHERE parent_id = ' . $parent_id . ' and id = ' . $sub_language_id;
         $res = Database::query($sql);
         if ($res === false or Database::num_rows($res) < 1) {
             return false;
@@ -171,8 +184,10 @@ class SubLanguageManager {
         if ($res === false) {
             return false;
         } //can't delete dir, so do not delete language record
-        $sql = 'DELETE FROM ' . $tbl_admin_languages . ' WHERE id="' . Database::escape_string($sub_language_id) . '" ';
+        $sql = 'DELETE FROM ' . $tbl_admin_languages . '
+                WHERE id="' . Database::escape_string($sub_language_id) . '" ';
         $res = Database::query($sql);
+
         return $res;
     }
 
@@ -181,7 +196,8 @@ class SubLanguageManager {
      * @param String The sub-language path directory ( e.g. 'spanish_corporate'' )
      * @return boolean  True on success, false on failure
      */
-    public static function remove_language_directory($sub_language_dir) {
+    public static function remove_language_directory($sub_language_dir)
+    {
         if (empty($sub_language_dir)) {
             return false;
         }
@@ -204,10 +220,11 @@ class SubLanguageManager {
 
     /**
      * check if language exist by id
-     * @param Integer The language id
-     * @return Boolean
+     * @param int $language_id
+     * @return bool
      */
-    public static function check_if_exist_language_by_id($language_id) {
+    public static function check_if_exist_language_by_id($language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $sql = 'SELECT count(*) as count FROM ' . $tbl_admin_languages . ' WHERE id="' . intval($language_id) . '"';
         $rs = Database::query($sql);
@@ -219,7 +236,6 @@ class SubLanguageManager {
             }
         } else {
             return false;
-            ;
         }
     }
 
@@ -228,7 +244,8 @@ class SubLanguageManager {
      * @param Integer The language id
      * @return String The original name of language
      */
-    public static function get_name_of_language_by_id($language_id) {
+    public static function get_name_of_language_by_id($language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $sql = 'SELECT original_name FROM ' . $tbl_admin_languages . ' WHERE id="' . Database::escape_string($language_id) . '"';
         $rs = Database::query($sql);
@@ -244,9 +261,11 @@ class SubLanguageManager {
      * @param Integer The language id
      * @return Boolean
      */
-    public static function check_if_language_is_sub_language($language_id) {
+    public static function check_if_language_is_sub_language($language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql = 'SELECT count(*) AS count FROM ' . $tbl_admin_languages . ' WHERE id="' . Database::escape_string($language_id) . '" AND NOT ISNULL(parent_id)';
+        $sql = 'SELECT count(*) AS count FROM ' . $tbl_admin_languages . '
+                WHERE id="' . Database::escape_string($language_id) . '" AND NOT ISNULL(parent_id)';
         $rs = Database::query($sql);
 
         if (Database::num_rows($rs) > 0 && Database::result($rs, '0', 'count') == 1) {
@@ -255,11 +274,17 @@ class SubLanguageManager {
             return false;
         }
     }
-    
-    public static function check_if_language_is_used($language_id) {
-        $language_info = self::get_all_information_of_language($language_id);        
+
+    /**
+     * @param int $language_id
+     * @return bool
+     */
+    public static function check_if_language_is_used($language_id)
+    {
+        $language_info = self::get_all_information_of_language($language_id);
         $user_table = Database :: get_main_table(TABLE_MAIN_USER);
-        $sql = 'SELECT count(*) AS count FROM ' . $user_table . ' WHERE language ="' . Database::escape_string($language_info['english_name']).'"';
+        $sql = 'SELECT count(*) AS count FROM ' . $user_table . '
+                WHERE language ="' . Database::escape_string($language_info['english_name']).'"';
         $rs = Database::query($sql);
         if (Database::num_rows($rs) > 0 && Database::result($rs, '0', 'count') >= 1) {
             return true;
@@ -273,9 +298,11 @@ class SubLanguageManager {
      * @param Integer The language id
      * @return Boolean
      */
-    public static function check_if_language_is_father($language_id) {
+    public static function check_if_language_is_father($language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql = 'SELECT count(*) AS count FROM ' . $tbl_admin_languages . ' WHERE parent_id="' . Database::escape_string($language_id) . '" AND NOT ISNULL(parent_id);';
+        $sql = 'SELECT count(*) AS count FROM ' . $tbl_admin_languages . '
+                WHERE parent_id="' . Database::escape_string($language_id) . '" AND NOT ISNULL(parent_id);';
         $rs = Database::query($sql);
 
         if (Database::num_rows($rs) > 0 && Database::result($rs, '0', 'count') == 1) {
@@ -290,7 +317,8 @@ class SubLanguageManager {
      * @param Integer The language id
      * @return void()
      */
-    public static function make_unavailable_language($language_id) {
+    public static function make_unavailable_language($language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $sql_make_unavailable = "UPDATE $tbl_admin_languages SET available='0' WHERE id='" . Database::escape_string($language_id) . "'";
         $result = Database::query($sql_make_unavailable);
@@ -302,7 +330,8 @@ class SubLanguageManager {
      * @param Integer The language id
      * @return void
      */
-    public static function make_available_language($language_id) {
+    public static function make_available_language($language_id)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $sql_make_available = "UPDATE $tbl_admin_languages SET available='1' WHERE id='" . Database::escape_string($language_id) . "'";
         $result = Database::query($sql_make_available);
@@ -314,7 +343,8 @@ class SubLanguageManager {
      * @param Integer The language id
      * @return bool
      */
-    public static function set_platform_language($language_id) {
+    public static function set_platform_language($language_id)
+    {
         if (empty($language_id) or (intval($language_id) != $language_id)) {
             return false;
         }
@@ -326,6 +356,7 @@ class SubLanguageManager {
         $sql_update_2 = "UPDATE " . $tbl_settings_current . " SET selected_value='" . $lang['english_name'] . "' WHERE variable='platformLanguage'";
         $result_2 = Database::query($sql_update_2);
         event_system(LOG_PLATFORM_LANGUAGE_CHANGE, LOG_PLATFORM_LANGUAGE, $lang['english_name']);
+
         return $result_2 !== false;
     }
 
@@ -333,7 +364,8 @@ class SubLanguageManager {
      * Get platform language ID
      * @return     int     The platform language ID
      */
-    public static function get_platform_language_id() {
+    public static function get_platform_language_id()
+    {
         $name = api_get_setting('platformLanguage');
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $sql = "SELECT id FROM " . $tbl_admin_languages . " WHERE english_name ='$name'";
@@ -345,16 +377,22 @@ class SubLanguageManager {
         return $row['id'];
     }
 
-    /*
+    /**
      * Get parent language path (or null if no parent)
      * @param    string  Children language path
      * @return   string  Parent language path or null
      */
-    public static function get_parent_language_path($language_path) {
+    public static function get_parent_language_path($language_path)
+    {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $tbl_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-        $sql_update = "SELECT dokeos_folder FROM " . $tbl_admin_languages . " WHERE id=(SELECT parent_id FROM " . $tbl_admin_languages . " WHERE dokeos_folder = '" . Database::escape_string($language_path) . "')";
-        $result = Database::query($sql_update);
+        $sql = "SELECT dokeos_folder
+                FROM " . $tbl_admin_languages . "
+                WHERE id = (
+                    SELECT parent_id FROM " . $tbl_admin_languages . "
+                    WHERE dokeos_folder = '" . Database::escape_string($language_path) . "'
+                )
+                ";
+        $result = Database::query($sql);
         if (Database::num_rows($result) == 0) {
             return null;
         }
@@ -367,7 +405,8 @@ class SubLanguageManager {
      * @param   string  $isocode The language isocode (en, es, fr, zh-TW, etc)
      * @return  mixed  English name of the matching language, or false if no active language could be found
      */
-    public static function getLanguageFromIsocode($isocode) {
+    public static function getLanguageFromIsocode($isocode)
+    {
         $isocode = Database::escape_string($isocode);
         $adminLanguagesTable = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         // select language - if case several languages match, get the last (more recent) one
@@ -384,12 +423,14 @@ class SubLanguageManager {
         $row = Database::fetch_assoc($res);
         return $row['english_name'];
     }
+
     /**
      * Get best language in browser preferences
      * @param   string  $preferences The browser-configured language preferences (e.g. "en,es;q=0.7;en-us;q=0.3", etc)
      * @return  mixed  English name of the matching language, or false if no active language could be found
      */
-    public static function getLanguageFromBrowserPreference($preferences) {
+    public static function getLanguageFromBrowserPreference($preferences)
+    {
         if (empty($preferences)) {
             return false;
         }
@@ -408,6 +449,7 @@ class SubLanguageManager {
                 }
             }
         }
+
         return false;
     }
-}
+}

+ 76 - 56
main/admin/sub_language.php

@@ -4,9 +4,7 @@
  * Script for sub-language administration
  * @package chamilo.admin.sub_language
  */
-/**
- * Init section
- */
+
 // name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
@@ -18,14 +16,13 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 $htmlHeadXtra[] ='<script type="text/javascript">
  $(document).ready(function() {
-
 	$(".save").click(function() {
 		button_name=$(this).attr("name");
 		button_array=button_name.split("|");
 		button_name=button_array[1];
 		file_id=button_array[2];
 		is_variable_language="$"+button_name;
-			
+
 		is_new_language=$("#txtid_"+file_id+"_"+button_name).attr("value");
    		if (is_new_language=="undefined") {
 			is_new_language="_";
@@ -39,19 +36,19 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 				type: "POST",
 				url: "../admin/sub_language_ajax.inc.php",
 				data: "new_language="+is_new_language+"&variable_language="+is_variable_language+"&file_id="+file_id+"&id="+'.intval($_REQUEST['id']).'+"&sub="+'.intval($_REQUEST['sub_language_id']).',
-				success: function(datos) { 	
+				success: function(datos) {
 					if (datos == "1") {
 						$("#div_message_information_id").html("<div class=\"confirmation-message\">'.get_lang('TheNewWordHasBeenAdded').'</div>");
 					} else {
 						$("#div_message_information_id").html("<div class=\"warning-message\">" + datos +"</div>");
 					}
-				} 
+				}
 			});
 		} else {
 			$("#div_message_information_id").html("<div class=\"error-message\">'.get_lang('FormHasErrorsPleaseComplete').'</div>");
 		}
 	});
- 		});
+});
 </script>';
 /**
  * Main code
@@ -66,15 +63,15 @@ $sublanguage_folder_error = false;
 
 if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 	$language_name              = SubLanguageManager::get_name_of_language_by_id ($_GET['id']);
-	$sub_language_name          = SubLanguageManager::get_name_of_language_by_id ($_GET['sub_language_id']);	
+	$sub_language_name          = SubLanguageManager::get_name_of_language_by_id ($_GET['sub_language_id']);
 	$all_data_of_language       = SubLanguageManager::get_all_information_of_language($_GET['id']);
 	$all_data_of_sublanguage    = SubLanguageManager::get_all_information_of_language($_GET['sub_language_id']);
-	$sub_language_file          = api_get_path(SYS_LANG_PATH).$all_data_of_sublanguage['dokeos_folder'];		
-	
+	$sub_language_file          = api_get_path(SYS_LANG_PATH).$all_data_of_sublanguage['dokeos_folder'];
+
 	if (!file_exists($sub_language_file) || !is_writable($sub_language_file)) {
-	    $sublanguage_folder_error = $sub_language_file.' '.get_lang('IsNotWritable');
-	}		
-	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {		
+		$sublanguage_folder_error = $sub_language_file.' '.get_lang('IsNotWritable');
+	}
+	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {
 		$language_id_exist = true;
 	} else {
 		$language_id_exist = false;
@@ -98,14 +95,14 @@ echo $language_name;
 echo '</div>';
 
 if (!empty($_SESSION['msg'])) {
-    echo $_SESSION['msg'];
-    unset($_SESSION['msg']);
+	echo $_SESSION['msg'];
+	unset($_SESSION['msg']);
 } else {
-    echo '<br />';
+	echo '<br />';
 }
 
 $txt_search_word = Security::remove_XSS($_REQUEST['txt_search_word']);
-$html.='<div style="float:left" class="actions">';
+$html ='<div style="float:left" class="actions">';
 $html.='<form style="float:left"  id="Searchlanguage" name="Searchlanguage" method="GET" action="sub_language.php">';
 $html.='&nbsp;'.get_lang('OriginalName').'&nbsp; :&nbsp;';
 
@@ -118,21 +115,27 @@ $html.='</div>';
 echo $html;
 echo '<br /><br /><br />';
 if (!empty($sublanguage_folder_error)) {
-    Display::display_warning_message($sublanguage_folder_error);
+	Display::display_warning_message($sublanguage_folder_error);
 }
 echo '<div id="div_message_information_id">&nbsp;</div>';
 
 /**
  * Search a term in the language
- * @param string the term to search
- * @param bool the search will include the variable definition of the term
- * @param bool the search will include the english language variables
- * @param bool the search will include the parent language variables of the sub language
- * @param bool the search will include the sub language variables
+ * @param string $term the term to search
+ * @param bool $search_in_variable the search will include the variable definition of the term
+ * @param bool $search_in_english the search will include the english language variables
+ * @param bool $search_in_parent the search will include the parent language variables of the sub language
+ * @param bool $search_in_sub_language the search will include the sub language variables
  * @author Julio Montoya
  *
  */
-function search_language_term($term, $search_in_variable = true , $search_in_english = true, $search_in_parent = true, $search_in_sub_language= true) {
+function search_language_term(
+	$term,
+	$search_in_variable = true,
+	$search_in_english = true,
+	$search_in_parent = true,
+	$search_in_sub_language = true
+) {
 	//These the $_REQUEST['id'] and the $_REQUEST['sub_language_id'] variables are process in global.inc.php (LOAD LANGUAGE FILES SECTION)
 	/*
 		These 4 arrays are set in global.inc.php with the condition that will be load from sub_language.php or sub_language_ajax.inc.php
@@ -141,15 +144,10 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 		$sub_language_array
 		$language_files_to_load
 	*/
-	//echo '<pre>';
-	// array with the list of files to load i.e trad4fall, notification, etc set in global.inc.php
-
 	global $language_files_to_load, $sub_language_array, $english_language_array, $parent_language_array;
 	$language_files_to_load_keys = array_flip($language_files_to_load);
 	$array_to_search = $parent_language_array;
 	$list_info = array();
-	//echo '<pre>';
-	//print_r($language_files_to_load);
 	$term='/'.Security::remove_XSS(trim($_REQUEST['txt_search_word'])).'/i';
 	//@todo optimize this foreach
 	foreach ($language_files_to_load as $lang_file) {
@@ -182,10 +180,14 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 					$obj_text='<textarea rows="10" cols="40" name="txt|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$language_files_to_load_keys[$lang_file].'_'.$parent_name_variable.'" >'.$sub_language_name_variable.'</textarea>';
 					$obj_button='<button class="save" type="button" name="btn|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$parent_name_variable.'"  />'.get_lang('Save').'</button>';
 
-					$list_info[]=array($lang_file.'.inc.php',
-									   $parent_name_variable,
-									   $english_name_variable,
-									   $parent_variable_value,$obj_text,$obj_button);
+					$list_info[] = array(
+						$lang_file . '.inc.php',
+						$parent_name_variable,
+						$english_name_variable,
+						$parent_variable_value,
+						$obj_text,
+						$obj_button
+					);
 				}
 			}
 		}
@@ -197,7 +199,7 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 				if (is_array($variable_value)) {
 					continue;
 				}
-				
+
 				if (is_array($variable_value))
 					echo $lang_file;
 				$founded = false;
@@ -220,25 +222,36 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 
 				if ($founded) {
 					//loading variable from the english array
-					$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
-					$parent_variable_value 		= $parent_language_array[$lang_file][$name_variable];
+					$sub_language_name_variable = null;
+					if (isset($sub_language_array[$lang_file][$name_variable])) {
+						$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
+					}
+					$parent_variable_value = null;
+					if (isset($parent_language_array[$lang_file][$name_variable])) {
+						$parent_variable_value = $parent_language_array[$lang_file][$name_variable];
+					}
 					//config buttons
-					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$language_files_to_load_keys[$lang_file].'_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$language_files_to_load_keys[$lang_file].'_'.$name_variable.'" >'.
+						$sub_language_name_variable.'
+						</textarea>';
 					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';
 
 					//loading variable from the english array
 					$english_name_variable = $english_language_array[$lang_file][$name_variable];
 
-					$list_info[]=array($lang_file.'.inc.php',
-									   $name_variable,
-									   $english_name_variable,
-									   $parent_variable_value,$obj_text,$obj_button);
+					$list_info[] = array(
+						$lang_file . '.inc.php',
+						$name_variable,
+						$english_name_variable,
+						$parent_variable_value,
+						$obj_text,
+						$obj_button
+					);
 				}
 			}
 		}
 
-
-		//search in sub language
+		// Search in sub language
 		if ($search_in_sub_language) {
 			$variables = $sub_language_array[$lang_file];
 			foreach ($variables as $name_variable =>$variable_value) {
@@ -254,7 +267,7 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 				if ($founded) {
 					//loading variable from the english array
 					$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
-					$parent_variable_value 		= $parent_language_array[$lang_file][$name_variable];
+					$parent_variable_value = $parent_language_array[$lang_file][$name_variable];
 					//config buttons
 					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$language_files_to_load_keys[$lang_file].'_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';
 					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';
@@ -262,9 +275,9 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 					//loading variable from the english array
 					$english_name_variable = $english_language_array[$lang_file][$name_variable];
 					$list_info[]=array($lang_file.'.inc.php',
-									   $name_variable,
-									   $english_name_variable,
-									   $parent_variable_value,$obj_text,$obj_button);
+						$name_variable,
+						$english_name_variable,
+						$parent_variable_value,$obj_text,$obj_button);
 				}
 			}
 		}
@@ -273,21 +286,29 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 	$list_info = array_unique_dimensional($list_info);
 	return $list_info;
 }
-/**
- * Output
- */
-//allow see data in sortetable
+
+// Allow see data in sort table
+$list_info = array();
 if (isset($_REQUEST['txt_search_word'])) {
 	//@todo fix to accept a char with 1 char
 	if (strlen(trim($_REQUEST['txt_search_word']))>2) {
-		$list_info = search_language_term($_REQUEST['txt_search_word'],true, true, true,true);
+		$list_info = search_language_term(
+			$_REQUEST['txt_search_word'],
+			true,
+			true,
+			true,
+			true
+		);
 	}
 }
 
-$parameters=array('id'=>intval($_GET['id']),'sub_language_id'=>intval($_GET['sub_language_id']),'txt_search_word'=> $txt_search_word);
+$parameters = array(
+	'id' => intval($_GET['id']),
+	'sub_language_id' => intval($_GET['sub_language_id']),
+	'txt_search_word' => $txt_search_word
+);
 $table = new SortableTableFromArrayConfig($list_info, 1,20,'data_info');
 $table->set_additional_parameters($parameters);
-//$table->set_header(0, '');
 $table->set_header(0, get_lang('LanguageFile'));
 $table->set_header(1, get_lang('LanguageVariable'));
 $table->set_header(2, get_lang('EnglishName'));
@@ -296,5 +317,4 @@ $table->set_header(4, get_lang('SubLanguage'),false);
 $table->set_header(5, get_lang('Edit'),false);
 $table->display();
 
-/*	FOOTER	*/
 Display :: display_footer();

+ 9 - 10
main/admin/sub_language_add.php

@@ -1,12 +1,11 @@
 <?php
-/* For licensing terms, see /dokeos_license.txt */
+/* For licensing terms, see /license.txt */
+
 /**
  * This script allows for the addition of sub-languages
  * @package chamilo.admin
  */
-/**
- * Initialization section
- */
+
 // name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
@@ -41,7 +40,7 @@ function add_sub_language ($original_name,$english_name,$isocode,$sublanguage_av
     $isocode                = Database::escape_string($isocode);
     $sublanguage_available  = Database::escape_string($sublanguage_available);
     $parent_id              = Database::escape_string($parent_id);
-    
+
     $sql='INSERT INTO '.$tbl_admin_languages.'(original_name,english_name,isocode,dokeos_folder,available,parent_id) VALUES ("'.$original_name.'","'.$english_name.'","'.$isocode.'","'.$english_name.'","'.$sublanguage_available.'","'.$parent_id.'")';
     $res = Database::query($sql);
     if ($res === false) {
@@ -86,14 +85,14 @@ function check_if_language_exist ($original_name, $english_name, $isocode, $subl
 		$has_error=true;
 		$message_information['english_name']=true;
 	}
-	
-	$iso_list = api_get_platform_isocodes();	
+
+	$iso_list = api_get_platform_isocodes();
 	$iso_list = array_values($iso_list);
-	
+
 	if (!in_array($isocode, $iso_list)) {
 		$has_error=true;
 		$message_information['isocode']=true;
-	}	
+	}
 	if ($has_error===true) {
 		$message_information['execute_add']=false;
 	}
@@ -217,7 +216,7 @@ if (isset($_POST['SubmitAddNewLanguage'])) {
 			$english_name=str_replace(' ','_',$english_name);
                         //Fixes BT#1636
                         $english_name=api_strtolower($english_name);
-            
+
 			$isocode=str_replace(' ','_',$isocode);
 			$str_info='<br/>'.get_lang('OriginalName').' : '.$original_name.'<br/>'.get_lang('EnglishName').' : '.$english_name.'<br/>'.get_lang('PlatformCharsetTitle').' : '.$isocode;
 

+ 14 - 14
main/admin/user_fields_add.php

@@ -1,5 +1,5 @@
 <?php
-/* For licensing terms, see /dokeos_license.txt */
+/* For licensing terms, see /license.txt */
 /**
 *	@package chamilo.admin
 */
@@ -18,7 +18,7 @@ api_protect_admin_script();
 
 $htmlHeadXtra[] = '<script>
 function change_image_user_field (image_value) {
-	
+
 	if (image_value==1) {
 		document.getElementById(\'options\').style.display = \'none\';
 		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
@@ -33,19 +33,19 @@ function change_image_user_field (image_value) {
 
 	} else if (image_value==3) {
 		document.getElementById(\'options\').style.display = \'block\';
-		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';				
+		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'))."'".');
 
 	} else if (image_value==4) {
 		document.getElementById(\'options\').style.display = \'block\';
-		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';		
+		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'))."'".');
 
 	} else if (image_value==5) {
 		document.getElementById(\'options\').style.display = \'block\';
-		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';		
+		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'))."'".');
 
@@ -56,13 +56,13 @@ function change_image_user_field (image_value) {
 
 	} else if (image_value==7) {
 		document.getElementById(\'options\').style.display = \'none\';
-		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';		
+		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'))."'".');
 
 	} else if (image_value==8) {
 		document.getElementById(\'options\').style.display = \'block\';
-		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';			
+		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'))."'".');
 
@@ -81,7 +81,7 @@ function change_image_user_field (image_value) {
 	}
 }
 
-function advanced_parameters() {			
+function advanced_parameters() {
 	if(document.getElementById(\'options\').style.display == \'none\') {
 		document.getElementById(\'options\').style.display = \'block\';
 		document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
@@ -125,7 +125,7 @@ $form->addRule('fieldtype', get_lang('ThisFieldIsRequired'), 'required');
 
 //Advanced parameters
 $form -> addElement('advanced_settings','<a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><div style="vertical-align:top;" ><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'</div></span></a>');
-//When edit, the combobox displey the field type displeyed else none 	
+//When edit, the combobox displey the field type displeyed else none
 if ( (isset($_GET['action']) && $_GET['action'] == 'edit') && in_array($_GET['field_type'],array(3,4,5,8))) {
 	$form -> addElement('html','<div id="options" style="display:block">');
 } else {
@@ -180,7 +180,7 @@ $form->setDefaults($defaults);
 if(isset($_GET['field_id']) && !empty($_GET['field_id'])) {
 	$class="save";
 	$text=get_lang('buttonEditUserField');
-} else { 
+} else {
 	$class="add";
 	$text=get_lang('buttonAddUserField');
 }
@@ -190,11 +190,11 @@ $form->addElement('html','</div>');
 $form->addElement('style_submit_button', 'submit',$text, 'class='.$class.'');
 // Validate form
 if( $form->validate()) {
-	$check = Security::check_token('post'); 
+	$check = Security::check_token('post');
 	if($check) {
 		$field = $form->exportValues();
-		$fieldlabel = empty($field['fieldlabel'])?$field['fieldtitle']:$field['fieldlabel'];		
-		$fieldlabel = trim(strtolower(str_replace(" ","_",$fieldlabel)));	
+		$fieldlabel = empty($field['fieldlabel'])?$field['fieldtitle']:$field['fieldlabel'];
+		$fieldlabel = trim(strtolower(str_replace(" ","_",$fieldlabel)));
 		$fieldtype = $field['fieldtype'];
 		$fieldtitle = $field['fieldtitle'];
 		$fielddefault = $field['fielddefaultvalue'];
@@ -261,4 +261,4 @@ if(!empty($defaults['fieldtype'])) {
 echo '</div>';
 
 // footer
-Display::display_footer();
+Display::display_footer();

+ 76 - 52
main/admin/user_list.php

@@ -95,11 +95,11 @@ function active_user(element_div) {
 	}
 }
 
-function clear_course_list (div_course) {
+function clear_course_list(div_course) {
 	$("div#"+div_course).html("&nbsp;");
 	$("div#"+div_course).hide("");
 }
-function clear_session_list (div_session) {
+function clear_session_list(div_session) {
 	$("div#"+div_session).html("&nbsp;");
 	$("div#"+div_session).hide("");
 }
@@ -115,7 +115,6 @@ function display_advanced_search_form () {
 }
 
 $(document).ready(function() {
-
     var select_val = $("#input_select_extra_data").val();
     if ( document.getElementById(\'extra_data_text\')) {
 
@@ -159,7 +158,6 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 if ($action == 'login_as') {
     $check = Security::check_token('get');
-
     if (isset($_GET['user_id']) && api_can_login_as($_GET['user_id']) && $check) {
         login_user($_GET['user_id']);
     } else {
@@ -174,7 +172,7 @@ api_protect_admin_script(true);
  * Prepares the shared SQL query for the user table.
  * See get_user_data() and get_number_of_users().
  *
- * @param boolean Whether to count, or get data
+ * @param boolean $is_count Whether to count, or get data
  * @return string SQL query
  */
 function prepare_user_sql_query($is_count) {
@@ -187,16 +185,21 @@ function prepare_user_sql_query($is_count) {
     } else {
         $sql .= "SELECT u.user_id AS col0, u.official_code AS col2, ";
 
-        if (api_is_western_name_order())
+        if (api_is_western_name_order()) {
             $sql .= "u.firstname AS col3, u.lastname AS col4, ";
-        else
+        } else {
             $sql .= "u.lastname AS col3, u.firstname AS col4, ";
+        }
 
-        $sql .= "u.username AS col5, u.email AS col6, ".
-                    "u.status AS col7, u.active AS col8, ".
-                    "u.user_id AS col9, u.registration_date AS col10, ".
-                    "u.expiration_date AS exp, u.password ".
-                    "FROM $user_table u";
+        $sql .= " u.username AS col5,
+                    u.email AS col6,
+                    u.status AS col7,
+                    u.active AS col8,
+                    u.user_id AS col9,
+                    u.registration_date AS col10,
+                    u.expiration_date AS exp,
+                    u.password
+                FROM $user_table u";
     }
 
     // adding the filter to see the user's only of the current access_url
@@ -205,18 +208,29 @@ function prepare_user_sql_query($is_count) {
         $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
     }
 
-    foreach ($_GET as $key => $value) {
-        /* Because this query uses LIKE very liberally we need to escape
-         * LIKE wildcards, concretely "_" and "%". This is only relevant
-         * for *LIKE* statements.
-         *
-         * See: http://stackoverflow.com/a/3683868 */
-
-        // Remove buggy whitespaces and escape for both SQL and LIKE.
-        if ($key == "keyword_status")
-            $$key = Database::escape_string(trim($value));
-        else
-            $$key = Database::escape_sql_wildcards(Database::escape_string(trim($value)));
+    $keywordList = array(
+        'keyword_firstname',
+        'keyword_lastname',
+        'keyword_username',
+        'keyword_email',
+        'keyword_officialcode',
+        'keyword_status',
+        'keyword_active',
+        'check_easy_passwords'
+    );
+
+    $keywordListValues = array();
+    $atLeastOne = false;
+    foreach ($keywordList as $keyword) {
+        $keywordListValues[$keyword] = null;
+        if (isset($_GET[$keyword]) && !empty($_GET[$keyword])) {
+            $keywordListValues[$keyword] = $_GET[$keyword];
+            $atLeastOne = true;
+        }
+    }
+
+    if ($atLeastOne == false) {
+        $keywordListValues = array();
     }
 
     if (isset($keyword_extra_data) && !empty($keyword_extra_data)) {
@@ -225,40 +239,47 @@ function prepare_user_sql_query($is_count) {
         $sql.= " INNER JOIN user_field_values ufv ON u.user_id=ufv.user_id AND ufv.field_id=$field_id ";
     }
 
-    if (isset($keyword)) {
-        $sql .= " WHERE (".
-                    "u.firstname LIKE '%". $keyword ."%' ".
-                    "OR u.lastname LIKE '%". $keyword ."%' ".
-                    "OR concat(u.firstname,' ',u.lastname) LIKE '%". $keyword ."%' ".
-                    "OR concat(u.lastname,' ',u.firstname) LIKE '%". $keyword ."%' ".
-                    "OR u.username LIKE '%". $keyword ."%' ".
-                    "OR u.official_code LIKE '%". $keyword ."%' ".
-                    "OR u.email LIKE '%". $keyword ."%')";
-    } elseif (isset($keyword_firstname)) {
+    if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
+        $keywordFiltered = Database::escape_string("%". $_GET['keyword'] ."%");
+        $sql .= " WHERE (
+                    u.firstname LIKE '$keywordFiltered' OR
+                    u.lastname LIKE '$keywordFiltered' OR
+                    concat(u.firstname, ' ', u.lastname) LIKE '$keywordFiltered' OR
+                    concat(u.lastname,' ',u.firstname) LIKE '$keywordFiltered' OR
+                    u.username LIKE '$keywordFiltered' OR
+                    u.official_code LIKE '$keywordFiltered' OR
+                    u.email LIKE '$keywordFiltered'
+                )
+        ";
+    } elseif (isset($keywordListValues) && !empty($keywordListValues)) {
         $query_admin_table = '';
         $keyword_admin = '';
 
-        if ($keyword_status == SESSIONADMIN) {
-           $keyword_status = '%';
+        if (isset($keywordListValues['keyword_status']) &&
+            $keywordListValues['keyword_status'] == PLATFORM_ADMIN
+        ) {
            $query_admin_table = " , $admin_table a ";
            $keyword_admin = ' AND a.user_id = u.user_id ';
+            $keywordListValues['keyword_status'] = '%';
         }
 
         $keyword_extra_value = '';
-
         if (isset($keyword_extra_data) && !empty($keyword_extra_data) &&
             !empty($keyword_extra_data_text)) {
             $keyword_extra_value = " AND ufv.field_value LIKE '%".trim($keyword_extra_data_text)."%' ";
         }
 
-        $sql .= " $query_admin_table ".
-                "WHERE (u.firstname LIKE '%". $keyword_firstname ."%' ".
-                    "AND u.lastname LIKE '%". $keyword_lastname ."%' ".
-                    "AND u.username LIKE '%". $keyword_username ."%' ".
-                    "AND u.email LIKE '%". $keyword_email ."%' ".
-                    "AND u.official_code LIKE '%". $keyword_officialcode ."%' ".
-                    "AND u.status LIKE '$keyword_status' ".
-                    "$keyword_admin $keyword_extra_value";
+        $sql .= " $query_admin_table
+                WHERE (
+                    u.firstname LIKE '". Database::escape_string("%".$keywordListValues['keyword_firstname']."%")."' AND
+                    u.lastname LIKE '". Database::escape_string("%".$keywordListValues['keyword_lastname']."%")."' AND
+                    u.username LIKE '". Database::escape_string("%".$keywordListValues['keyword_username']."%")."' AND
+                    u.email LIKE '". Database::escape_string("%".$keywordListValues['keyword_email']."%")."' AND
+                    u.official_code LIKE '". Database::escape_string("%".$keywordListValues['keyword_officialcode']."%")."' AND
+                    u.status LIKE '".Database::escape_string($keywordListValues['keyword_status'])."'
+                    $keyword_admin
+                    $keyword_extra_value
+                ";
 
         if (isset($keyword_active) && !isset($keyword_inactive)) {
             $sql .= " AND u.active='1'";
@@ -270,7 +291,8 @@ function prepare_user_sql_query($is_count) {
 
     // adding the filter to see the user's only of the current access_url
     if ((api_is_platform_admin() || api_is_session_admin())
-        && api_get_multiple_access_url()) {
+        && api_get_multiple_access_url()
+    ) {
         $sql .= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
     }
 
@@ -388,7 +410,7 @@ function login_user($user_id) {
  * @see SortableTable#get_total_number_of_items()
  */
 function get_number_of_users() {
-    $sql = prepare_user_sql_query (true);
+    $sql = prepare_user_sql_query(true);
 
     $res = Database::query($sql);
     $obj = Database::fetch_object($res);
@@ -404,7 +426,7 @@ function get_number_of_users() {
  * @see SortableTable#get_table_data($from)
  */
 function get_user_data($from, $number_of_items, $column, $direction) {
-    $sql = prepare_user_sql_query (false);
+    $sql = prepare_user_sql_query(false);
 
     $checkPassStrength = isset($_GET['check_easy_passwords']) && $_GET['check_easy_passwords'] == 1 ? true : false;
 
@@ -732,7 +754,8 @@ $form->addElement(
 $actions  = '';
 if (api_is_platform_admin()) {
 	$actions .= '<span style="float:right;">'.
-		 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('new_user.png',get_lang('AddUsers'),'',ICON_SIZE_MEDIUM).'</a>'.
+		 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.
+         Display::return_icon('new_user.png',get_lang('AddUsers'),'',ICON_SIZE_MEDIUM).'</a>'.
 		 '</span>';
 }
 $actions .= $form->return_form();
@@ -790,8 +813,10 @@ $status_options['%'] = get_lang('All');
 $status_options[STUDENT] = get_lang('Student');
 $status_options[COURSEMANAGER] = get_lang('Teacher');
 $status_options[DRH] = get_lang('Drh');
-$status_options[SESSIONADMIN] = get_lang('Administrator');
-$form->addElement('select','keyword_status',get_lang('Profile'),$status_options, array('style'=>'margin-left:17px'));
+$status_options[SESSIONADMIN] = get_lang('SessionsAdmin');
+$status_options[PLATFORM_ADMIN] = get_lang('Administrator');
+
+$form->addElement('select','keyword_status',get_lang('Profile'), $status_options, array('style'=>'margin-left:17px'));
 $form->addElement('html', '</td></tr>');
 $form->addElement('html', '<tr><td>');
 $active_group = array();
@@ -881,7 +906,6 @@ if ($table->get_total_number_of_items() == 0) {
 
     if (api_get_multiple_access_url() && isset($_REQUEST['keyword'])) {
         $keyword = Database::escape_string($_REQUEST['keyword']);
-        //$conditions = array('firstname' => $keyword, 'lastname' => $keyword, 'username' => $keyword);
         $conditions = array('username' => $keyword);
         $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');
         if (!empty($user_list)) {

+ 29 - 10
main/attendance/attendance_calendar.php

@@ -20,9 +20,11 @@ if (!$is_locked_attendance || api_is_platform_admin()) {
         echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_list&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('back.png',get_lang('AttendanceCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
     } else {
         echo '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('back.png',get_lang('AttendanceSheet'),'',ICON_SIZE_MEDIUM).'</a>';
-
-        echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_add&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('add.png',get_lang('AddDateAndTime'),'',ICON_SIZE_MEDIUM).'</a>';
-        echo '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDeleteAllDates').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=calendar_all_delete&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('clean.png',get_lang('CleanCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
+        if (api_is_allowed_to_edit()) {
+            echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_add&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('add.png',get_lang('AddDateAndTime'),'',ICON_SIZE_MEDIUM).'</a>';
+            echo '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDeleteAllDates').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=calendar_all_delete&attendance_id='.$attendance_id.$param_gradebook.'">'.
+                Display::return_icon('clean.png',get_lang('CleanCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
+        }
     }
     echo '</div>';
 }
@@ -48,7 +50,12 @@ if ($error_checkdate) {
 
 if (isset($action) && $action == 'calendar_add') {
     // calendar add form
-    $form = new FormValidator('attendance_calendar_add','POST','index.php?action=calendar_add&attendance_id='.$attendance_id.$param_gradebook.'&'.api_get_cidreq(),'');
+    $form = new FormValidator(
+        'attendance_calendar_add',
+        'POST',
+        'index.php?action=calendar_add&attendance_id=' . $attendance_id . $param_gradebook . '&' . api_get_cidreq(),
+        ''
+    );
     $form->addElement('header', get_lang('AddADateTime'));
     $form->addElement('date_time_picker', 'date_time');
     $defaults['date_time'] = date('Y-m-d H:i', api_strtotime(api_get_local_time()));
@@ -93,10 +100,17 @@ if (isset($action) && $action == 'calendar_add') {
     if (!empty($attendance_calendar)) {
         foreach ($attendance_calendar as $calendar) {
             echo '<div class="attendance-calendar-row">';
-            if ((isset($action) && $action == 'calendar_edit') && (isset($calendar_id) && $calendar_id == $calendar['id'])) {
+            if ((isset($action) && $action == 'calendar_edit') &&
+                (isset($calendar_id) && $calendar_id == $calendar['id'])
+            ) {
                 // calendar edit form
                 echo '<div class="attendance-calendar-edit">';
-                $form = new FormValidator('attendance_calendar_edit','POST','index.php?action=calendar_edit&attendance_id='.$attendance_id.'&calendar_id='.$calendar_id.'&'.api_get_cidreq().$param_gradebook,'');
+                $form = new FormValidator(
+                    'attendance_calendar_edit',
+                    'POST',
+                    'index.php?action=calendar_edit&attendance_id=' . $attendance_id . '&calendar_id=' . $calendar_id . '&' . api_get_cidreq() . $param_gradebook,
+                    ''
+                );
                 $form->addElement('date_time_picker', 'date_time', '', array('form_name'=>'attendance_calendar_edit'), 5);
                 $defaults['date_time'] = $calendar['date_time'];
                 $form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"');
@@ -107,10 +121,15 @@ if (isset($action) && $action == 'calendar_add') {
             } else {
                 echo Display::return_icon('lp_calendar_event.png', get_lang('DateTime')).' '.substr($calendar['date_time'], 0, strlen($calendar['date_time'])- 3) .'&nbsp;';
                 if (!$is_locked_attendance || api_is_platform_admin()) {
-                    echo '<span style="margin-left:20px;">';
-                    echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_edit&calendar_id='.intval($calendar['id']).'&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('edit.png', get_lang('Edit'), array('style'=>'vertical-align:middle'), ICON_SIZE_SMALL).'</a>&nbsp;';
-                    echo '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDelete').'\')) return false;" href="index.php?'.api_get_cidreq().$param_gradebook.'&action=calendar_delete&calendar_id='.intval($calendar['id']).'&attendance_id='.$attendance_id.'">'.Display::return_icon('delete.png', get_lang('Delete'), array('style'=>'vertical-align:middle'), ICON_SIZE_SMALL).'</a>';
-                    echo '</span>';
+                    if (api_is_allowed_to_edit()) {
+                        echo '<span style="margin-left:20px;">';
+                        echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_edit&calendar_id='.intval($calendar['id']).'&attendance_id='.$attendance_id.$param_gradebook.'">'.
+                            Display::return_icon('edit.png', get_lang('Edit'), array('style'=>'vertical-align:middle'), ICON_SIZE_SMALL).'</a>&nbsp;';
+                        echo '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDelete').'\')) return false;" href="index.php?'.api_get_cidreq().$param_gradebook.'&action=calendar_delete&calendar_id='.intval($calendar['id']).'&attendance_id='.$attendance_id.'">'.
+                            Display::return_icon('delete.png', get_lang('Delete'), array('style'=>'vertical-align:middle'), ICON_SIZE_SMALL).'</a>';
+                        echo '</span>';
+                    }
+
                 }
             }
             echo '</div>';

+ 53 - 9
main/attendance/attendance_controller.php

@@ -212,10 +212,12 @@ class AttendanceController
     }
 
     /**
-     * It's used for controlling attendace sheet (list, add),
+     * It's used for controlling attendance sheet (list, add),
      * render to attendance_sheet view
-     * @param string action
-     * @param int	 attendance id
+     * @param string $action
+     * @param int	 $attendance_id
+     * @param int $student_id
+     * @param bool $edit
      */
     public function attendance_sheet($action, $attendance_id, $student_id = 0, $edit = true)
     {
@@ -230,8 +232,14 @@ class AttendanceController
             $filter_type = $_REQUEST['filter'];
         }
 
+        $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+            api_get_user_id(),
+            api_get_course_info()
+        );
+
         if ($edit == true) {
-            if (api_is_allowed_to_edit(null, true)) {
+
+            if (api_is_allowed_to_edit(null, true) || $isDrhOfCourse) {
                 $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id);
             }
         } else {
@@ -242,11 +250,12 @@ class AttendanceController
             }
 
             if (api_is_allowed_to_edit(null, true) ||
-                api_is_coach(api_get_session_id(), api_get_course_id())
+                api_is_coach(api_get_session_id(), api_get_course_id()) ||
+                $isDrhOfCourse
             ) {
-                $data['users_presence']  = $attendance->get_users_attendance_sheet($attendance_id);
+                $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id);
             } else {
-                $data['users_presence']  = $attendance->get_users_attendance_sheet($attendance_id, $user_id);
+                $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id, $user_id);
             }
 
             $data['faults']  = $attendance->get_faults_of_user($user_id, $attendance_id);
@@ -257,7 +266,6 @@ class AttendanceController
         $data['next_attendance_calendar_datetime'] = $attendance->get_next_attendance_calendar_datetime($attendance_id);
 
         if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {
-
             if (isset($_POST['hidden_input'])) {
                 foreach ($_POST['hidden_input'] as $cal_id) {
                     $users_present = array();
@@ -528,10 +536,46 @@ class AttendanceController
             'pdf_teachers' => $teacherName,
             'pdf_course_category' => $courseCategory['name'],
             'format' => 'A4-L',
-            'orientation' =>    'L'
+            'orientation' => 'L'
         );
 
         Export::export_html_to_pdf($content, $params);
         exit;
     }
+
+    /**
+     * Gets attendace base in the table:
+     * TABLE_STATISTIC_TRACK_E_COURSE_ACCESS
+     * @throws ViewException
+     */
+    public function calendarLogins()
+    {
+        $form = new FormValidator(
+            'search',
+            'post',
+            api_get_self().'?'.api_get_cidreq().'&action=calendar_logins'
+        );
+        $form->addDateRangePicker('range', get_lang('Range'));
+        $form->add_button('submit', get_lang('submit'));
+        $table = null;
+
+        if ($form->validate()) {
+            $values = $form->getSubmitValues();
+
+            $startDate = api_get_utc_datetime($values['range_start']);
+            $endDate = api_get_utc_datetime($values['range_end']);
+
+            $attendance = new Attendance();
+            $table = $attendance->getAttendanceLogins($startDate, $endDate);
+        }
+
+        $data = array(
+            'form' => $form->return_form(),
+            'table' => $table
+        );
+        $this->view->set_data($data);
+        $this->view->set_layout('layout');
+        $this->view->set_template('calendar_logins');
+        $this->view->render();
+    }
 }

+ 12 - 2
main/attendance/attendance_list.php

@@ -16,7 +16,12 @@ if (api_is_allowed_to_edit(null, true)) {
         $param_gradebook = '&gradebook='.Security::remove_XSS($_SESSION['gradebook']);
     }
     echo '<div class="actions">';
-    echo '<a href="index.php?'.api_get_cidreq().$param_gradebook.'&action=attendance_add">'.Display::return_icon('new_attendance_list.png',get_lang('CreateANewAttendance'),'',ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="index.php?'.api_get_cidreq().$param_gradebook.'&action=attendance_add">'.
+        Display::return_icon('new_attendance_list.png',get_lang('CreateANewAttendance'),'',ICON_SIZE_MEDIUM).'</a>';
+
+    echo '<a href="index.php?'.api_get_cidreq().$param_gradebook.'&action=calendar_logins">'.
+        Display::return_icon('attendance_list.png',get_lang('Logins'),'',ICON_SIZE_MEDIUM).'</a>';
+
     echo '</div>';
 }
 $attendance = new Attendance();
@@ -25,7 +30,12 @@ if ($attendance->get_number_of_attendances() == 0) {
     $attendance->set_description(get_lang('Attendances'));
     $attendance->attendance_add();
 }
-$table = new SortableTable('attendance_list', array('Attendance', 'get_number_of_attendances'), array('Attendance', 'get_attendance_data'), $default_column);
+$table = new SortableTable(
+    'attendance_list',
+    array('Attendance', 'get_number_of_attendances'),
+    array('Attendance', 'get_attendance_data'),
+    $default_column
+);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, '', false, array('style'=>'width:20px;'));
 $table->set_header(1, get_lang('Name'), true );

+ 20 - 7
main/attendance/attendance_sheet.php

@@ -8,23 +8,36 @@
  * @package chamilo.attendance
  */
 
-// protect a course script
+// Protect a course script
 api_protect_course_script(true);
 
+$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+    api_get_user_id(),
+    api_get_course_info()
+);
+
 if (api_is_allowed_to_edit(null, true) ||
-    api_is_coach(api_get_session_id(), api_get_course_id())
+    api_is_coach(api_get_session_id(), api_get_course_id()) ||
+    $isDrhOfCourse
 ) {
     $param_gradebook = '';
     if (isset($_SESSION['gradebook'])) {
         $param_gradebook = '&gradebook='.$_SESSION['gradebook'];
     }
 
-    $form = new FormValidator('filter', 'post', 'index.php?action=attendance_sheet_list&'.api_get_cidreq().$param_gradebook.'&attendance_id='.$attendance_id, null, array('class' => 'form-search pull-left'));
+    $form = new FormValidator(
+        'filter',
+        'post',
+        'index.php?action=attendance_sheet_list&' . api_get_cidreq() . $param_gradebook . '&attendance_id=' . $attendance_id,
+        null,
+        array('class' => 'form-search pull-left')
+    );
+
     $values = array(
-        'all'           => get_lang('All'),
-        'today'         => get_lang('Today'),
-        'all_done'      => get_lang('AllDone'),
-        'all_not_done'  => get_lang('AllNotDone')
+        'all' => get_lang('All'),
+        'today' => get_lang('Today'),
+        'all_done' => get_lang('AllDone'),
+        'all_not_done' => get_lang('AllNotDone')
     );
     $today = api_convert_and_format_date(null, DATE_FORMAT_SHORT);
     $exists_attendance_today = false;

+ 11 - 0
main/attendance/calendar_logins.php

@@ -0,0 +1,11 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+// See AttendanceController::calendarLogins function
+echo '<div class="actions">';
+echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_list='.$param_gradebook.'">'.
+    Display::return_icon('back.png',get_lang('AttendanceCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '</div>';
+
+echo $form;
+echo $table;

+ 12 - 4
main/attendance/index.php

@@ -48,7 +48,8 @@ $actions = array(
     'attendance_delete_select',
     'attendance_restore',
     'attendance_sheet_export_to_pdf',
-    'attendance_sheet_list_no_edit'
+    'attendance_sheet_list_no_edit',
+    'calendar_logins'
 );
 
 $actions_calendar = array(
@@ -92,7 +93,7 @@ $attendance = new Attendance();
 
 // attendance controller object
 $attendance_controller = new AttendanceController();
-
+$attendance_data = array();
 // get attendance data
 if (!empty($attendance_id)) {
     // attendance data by id
@@ -205,8 +206,10 @@ if (api_is_drh() && isset($_GET['student_id'])) {
     $student_id = intval($_GET['student_id']);
     $student_param = '&student_id='.$student_id;
     $student_info = api_get_user_info($student_id);
-    $student_name = api_get_person_name($student_info['firstname'], $student_info['lastname']);
-    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$student_id, 'name' => $student_name);
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$student_id,
+        'name' => $student_info['complete_name']
+    );
 }
 if (!empty($gradebook)) {
     $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'gradebook/index.php', 'name' => get_lang('ToolGradebook'));
@@ -301,6 +304,11 @@ switch ($action) {
     case 'calendar_list' :
         $attendance_controller->attendance_calendar($action, $attendance_id, $calendar_id);
         break;
+    case 'calendar_logins':
+        if (api_is_allowed_to_edit(null, true)) {
+            $attendance_controller->calendarLogins();
+        }
+        break;
     default :
         $attendance_controller->attendance_list();
 }

+ 0 - 1
main/attendance/layout.php

@@ -10,7 +10,6 @@
 // protect a course script
 api_protect_course_script(true);
 
-
 // Header
 $tool = TOOL_ATTENDANCE;
 Display :: display_header('');

+ 2 - 3
main/calendar/agenda.lib.php

@@ -6,7 +6,6 @@
  *
  * @author: Julio Montoya <gugli100@gmail.com>
  */
-
 class Agenda
 {
     public $events = array();
@@ -19,7 +18,7 @@ class Agenda
     public $course;
 
     /**
-     *
+     * Constructor
      */
     public function __construct()
     {
@@ -2347,7 +2346,7 @@ class Agenda
             $messages = implode('<br /> ', $messages);
         } else {
             $messages = get_lang('NoAgendaItems');
-                    
+
         }
 
         return $messages;

+ 45 - 45
main/calendar/allagendas.php

@@ -2,12 +2,12 @@
 /* For licensing terms, see /license.txt */
 
 /**
- * 
+ *
  * Get the all events by session/course
- * @author Julio Montoya cleaning code, chamilo code style changes, all agenda feature work with courses and sessions, only admins and rrhh users can see this page 
- * 
- *  
- * @author Carlos Brolo First code submittion  
+ * @author Julio Montoya cleaning code, chamilo code style changes,
+ * all agenda feature work with courses and sessions,
+ * only admins and rrhh users can see this page
+ * @author Carlos Brolo First code submittion
  */
 
 // name of the language file that needs to be included
@@ -56,7 +56,7 @@ if (!empty ($course_path)) {
 // showing the header
 Display::display_header(get_lang('MyAgenda'));
 
-function display_mymonthcalendar_2($agendaitems, $month, $year, $weekdaynames=array(), $monthName, $session_id) {	
+function display_mymonthcalendar_2($agendaitems, $month, $year, $weekdaynames=array(), $monthName, $session_id) {
 	global $DaysShort, $course_path;
 	//Handle leap year
 	$numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
@@ -108,22 +108,22 @@ function display_mymonthcalendar_2($agendaitems, $month, $year, $weekdaynames=ar
 	echo "</table>\n";
 }
 
-function get_agenda_items_by_course_list($course_list, $month, $year, $session_id = 0) {	
+function get_agenda_items_by_course_list($course_list, $month, $year, $session_id = 0) {
 	global $setting_agenda_link;
 	//echo $sql  = 'SELECT name FROM chamilo_main.class WHERE name = "'.$grado.'" ORDER BY name ASC';
 	//$result = Database::query($sql);
 	//while ($row = Database::fetch_array($result, 'ASSOC')) {
-	
-	$agendaitems = array ();	
+
+	$agendaitems = array ();
 	$course_name_list = array();
 	foreach ($course_list as $course) {
-		
+
 		$db_name		= $course['db_name'];
 		$code			= $course['code'];
 		$title			= $course['title'];
-		$course_name_list[] = $title;		
+		$course_name_list[] = $title;
 		//$sql2  = 'SELECT code, db_name, title FROM chamilo_main.course WHERE category_code = "'.$course_name.'" ';
-//		$courses_dbs = Database::query($sql2);		
+//		$courses_dbs = Database::query($sql2);
 
 		$items = array ();
 		// $courses_dbs = array();
@@ -132,8 +132,8 @@ function get_agenda_items_by_course_list($course_list, $month, $year, $session_i
 		//$db_name 	= $row2['db_name'];
 		//$code 		= $row2['code'];
 		//$title 		= $row2['title'];
-		//echo "<center><h2>".$db_name."</h2></center>";		
-		
+		//echo "<center><h2>".$db_name."</h2></center>";
+
 		//databases of the courses
 		$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA, $db_name);
 		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $db_name);
@@ -143,9 +143,9 @@ function get_agenda_items_by_course_list($course_list, $month, $year, $session_i
 		$session_condition = '';
 		if ($session_id != 0) {
 			$session_id = intval($session_id);
-			$session_condition = "AND session_id = $session_id"; 
+			$session_condition = "AND session_id = $session_id";
 		}
-		
+
 		$sqlquery = "SELECT	DISTINCT agenda.*, item_property.*
 						FROM ".$TABLEAGENDA." agenda,
 							 ".$TABLE_ITEMPROPERTY." item_property
@@ -155,11 +155,11 @@ function get_agenda_items_by_course_list($course_list, $month, $year, $session_i
 						AND item_property.tool='".TOOL_CALENDAR_EVENT."'
 						AND item_property.visibility='1' $session_condition
 						GROUP BY agenda.id
-						ORDER BY start_date ";		
+						ORDER BY start_date ";
 		$result = Database::query($sqlquery);
 		while ($item = Database::fetch_array($result,'ASSOC')) {
 			//taking the day
-			$agendaday = date("j",strtotime($item['start_date']));				
+			$agendaday = date("j",strtotime($item['start_date']));
 			if(!isset($items[$agendaday])){$items[$agendaday]=array();}
 			//taking the time
 			$time = date("H:i",strtotime($item['start_date']));
@@ -174,12 +174,12 @@ function get_agenda_items_by_course_list($course_list, $month, $year, $session_i
 			if(!isset($items[$agendaday][$item['start_date']])) {
 				$items[$agendaday][$item['start_date']] = '';
 			}
-			
+
 			$items[$agendaday][$item['start_date']] .= "".get_lang('StartTimeWindow')."&nbsp;<i>".$time."</i>"."&nbsp;-&nbsp;".get_lang("EndTimeWindow")."&nbsp;<i>".$end_time."</i>&nbsp;";
 			$items[$agendaday][$item['start_date']] .= '<br />'."<b><a href=\"$URL\" title=\"".Security::remove_XSS($title)."\">".$agenda_link."</a> </b> ".Security::remove_XSS($item['title'])."<br /> ";
 			$items[$agendaday][$item['start_date']] .= '<br/>';
 		}
-		
+
 		if (is_array($items) && count($items) > 0) {
 			while (list ($agendaday, $tmpitems) = each($items)) {
 				if(!isset($agendaitems[$agendaday])) {
@@ -253,25 +253,25 @@ $my_session_id = intval($_GET['session']);
 $my_course_list = array();
 
 if(!empty($my_session_id)) {
-	$_SESSION['my_course_list'] = array();	
+	$_SESSION['my_course_list'] = array();
 	$my_course_list = array();
 } else {
-	$my_course_list = $_SESSION['my_course_list'];	
+	$my_course_list = $_SESSION['my_course_list'];
 	$my_course_list_keys = array_keys($my_course_list);
-	if (!in_array($my_course_id, $my_course_list_keys)) {	
+	if (!in_array($my_course_id, $my_course_list_keys)) {
 		$course_info = api_get_course_info_by_id($my_course_id);
-		$_SESSION['my_course_list'][$my_course_id] = $course_info;	
+		$_SESSION['my_course_list'][$my_course_id] = $course_info;
 		$my_course_list = $_SESSION['my_course_list'];
 		//echo $my_course_id.'added ';
 	}
-	
+
 	if (isset($_GET['delete_course_option'])) {
-		$course_id_to_delete = intval($_GET['delete_course_option']);	
-		unset($_SESSION['my_course_list'][$course_id_to_delete]);	
+		$course_id_to_delete = intval($_GET['delete_course_option']);
+		unset($_SESSION['my_course_list'][$course_id_to_delete]);
 		$my_course_list = $_SESSION['my_course_list'];
 	}
 	//clean the array
-	$my_course_list = array_filter($my_course_list);	
+	$my_course_list = array_filter($my_course_list);
 }
 
 /* 	OUTPUT	*/
@@ -309,24 +309,24 @@ if (isset ($_user['user_id'])) {
 
 	if (api_is_platform_admin()) {
 		$courses  = array();
-		$sessions = SessionManager::get_sessions_list();		
-		
+		$sessions = SessionManager::get_sessions_list();
+
 	} elseif(api_is_drh()) {
-		$courses  = CourseManager::get_courses_followed_by_drh(api_get_user_id());		
+		$courses  = CourseManager::get_courses_followed_by_drh(api_get_user_id());
 		$sessions = SessionManager::get_sessions_followed_by_drh(api_get_user_id());
 	}
 
 	echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
 	echo '<tr>';
-	
+
 	// output: the small calendar item on the left and the view / add links
 	echo '<td width="220" valign="top">';
-		
+
 		echo '<br />';
 		if (count($courses) > 0) {
 			echo '<h1>'.get_lang('SelectACourse').'</h1>';
-			
-			foreach ($courses as $row_course) {	
+
+			foreach ($courses as $row_course) {
 				$course_code = $row_course['id'];
 				$title = $row_course['title'];
 				$my_course_list_keys = array_keys($my_course_list);
@@ -339,37 +339,37 @@ if (isset ($_user['user_id'])) {
 		}
 		if (count($sessions) > 0) {
 			echo '<h1>'.get_lang('SelectASession').'</h1>';
-			foreach ($sessions as $session) {			
+			foreach ($sessions as $session) {
 				$id = $session['id'];
 				$name = $session['name'];
-				echo '<a href="allagendas.php?session='.$id.'">'.$name.'</a><br />'; 
+				echo '<a href="allagendas.php?session='.$id.'">'.$name.'</a><br />';
 			}
 		}
 	echo '</td>';
-		
+
 	// the divider
 	// OlivierB : the image has a white background, which causes trouble if the portal has another background color. Image should be transparent. ----> echo "<td width=\"20\" background=\"../img/verticalruler.gif\">&nbsp;</td>";
 	echo "<td width=\"20\">&nbsp;</td>";
 	// the main area: day, week, month view
 	echo '<td valign="top">';
-	
+
 	//@todo hardcoding option
 	$process = 'month_view';
-	
+
 	switch ($process) {
 		case "month_view" :
 			$session_id = 0;
 			//By courses
 			if (is_array($my_course_list) && count($my_course_list) > 0) {
-				$course_list = $my_course_list;				
+				$course_list = $my_course_list;
 			} else {
 				//session
 				$course_list = SessionManager::get_course_list_by_session_id($my_session_id);
-				$session_id = $my_session_id;				
-				echo '<h1>'.$sessions[$session_id]['name'].'</h1>';					
+				$session_id = $my_session_id;
+				echo '<h1>'.$sessions[$session_id]['name'].'</h1>';
 			}
 			if (is_array($course_list) && count($course_list) > 0) {
-				
+
 				$agendaitems = get_agenda_items_by_course_list($course_list, $month, $year, $session_id);
 				//$agendaitems = get_global_agenda_items($agendaitems, $day, $month, $year, $week, "month_view");
 				display_mymonthcalendar_2($agendaitems, $month, $year, array(), $monthName, $session_id);
@@ -380,4 +380,4 @@ if (isset ($_user['user_id'])) {
 	}
 }
 echo "</td></tr></table>";
-Display :: display_footer();
+Display :: display_footer();

+ 3 - 7
main/calendar/ical_export.php

@@ -3,10 +3,6 @@
 /**
  * This file exclusively export calendar items to iCal or similar formats
  * @author Yannick Warnier <yannick.warnier@dokeos.com>
- * See copyright information in the Dokeos root directory, dokeos_license.txt
- */
-/**
- * Initialisation
  */
 // name of the language file that needs to be included
 $language_file = 'agenda';
@@ -53,7 +49,7 @@ $event = $agenda->get_event($id);
 
 if (!empty($event)) {
 	define('ICAL_LANG',api_get_language_isocode());
-	
+
     $ical = new vcalendar();
     $ical->setConfig('unique_id',api_get_path(WEB_PATH));
     $ical->setProperty( 'method', 'PUBLISH' );
@@ -136,8 +132,8 @@ if (!empty($event)) {
         default:
             header('location:'.Security::remove_XSS($_SERVER['HTTP_REFERER']));
             die();
-    }	
+    }
 } else {
 	header('location:'.Security::remove_XSS($_SERVER['HTTP_REFERER']));
 	die();
-}
+}

+ 2 - 5
main/calendar/print.php

@@ -1,12 +1,9 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * See copyright information in the Dokeos root directory, dokeos_license.txt
  * @package chamilo.calendar
  */
-/**
- * Code
- */
+
 // name of the language file that needs to be included
 $language_file = 'agenda';
 $id=$_GET['id'];
@@ -68,4 +65,4 @@ while($row=Database::fetch_array($result)) {
 	<input type="button" value="<?php echo api_htmlentities(get_lang('Print'), ENT_QUOTES); ?>" onClick="javascript: window.print();" />
 	</center>
 </body>
-</html>
+</html>

+ 95 - 39
main/course_home/activity.php

@@ -20,37 +20,37 @@ $session_id = api_get_session_id();
 //	MAIN CODE
 
 if (api_is_allowed_to_edit(null, true)) {
-	// HIDE
-	if (!empty($_GET['hide'])) {
-		$sql = "UPDATE $tool_table SET visibility=0 WHERE c_id = $course_id AND id=".$id;
-		Database::query($sql);
-		$show_message = Display::return_message(get_lang('ToolIsNowHidden'), 'confirmation');
-	} elseif (!empty($_GET['restore'])) {
-		// visibility 0,2 -> 1
-		// REACTIVATE
-		$sql = "UPDATE $tool_table SET visibility=1 WHERE c_id = $course_id AND id=".$id;
-		Database::query($sql);
-		//$show_message = Display::return_message(get_lang('ToolIsNowVisible'),'confirmation');
-	}
+    // HIDE
+    if (!empty($_GET['hide'])) {
+        $sql = "UPDATE $tool_table SET visibility=0 WHERE c_id = $course_id AND id=".$id;
+        Database::query($sql);
+        $show_message = Display::return_message(get_lang('ToolIsNowHidden'), 'confirmation');
+    } elseif (!empty($_GET['restore'])) {
+        // visibility 0,2 -> 1
+        // REACTIVATE
+        $sql = "UPDATE $tool_table SET visibility=1 WHERE c_id = $course_id AND id=".$id;
+        Database::query($sql);
+        //$show_message = Display::return_message(get_lang('ToolIsNowVisible'),'confirmation');
+    }
 }
 
 // Work with data post askable by admin of course
 if (api_is_platform_admin()) {
-	// Show message to confirm that a tool it to be hidden from available tools
-	// visibility 0,1->2
-	if (!empty($_GET['askDelete'])) {
+    // Show message to confirm that a tool it to be hidden from available tools
+    // visibility 0,1->2
+    if (!empty($_GET['askDelete'])) {
         $content .='<div id="toolhide">'.get_lang('DelLk').'<br />&nbsp;&nbsp;&nbsp;
             <a href="'.api_get_self().'">'.get_lang('No').'</a>&nbsp;|&nbsp;
             <a href="'.api_get_self().'?delete=yes&id='.$id.'">'.get_lang('Yes').'</a>
         </div>';
-	} elseif (isset($_GET['delete']) && $_GET['delete']) {
+    } elseif (isset($_GET['delete']) && $_GET['delete']) {
         /*
         * Process hiding a tools from available tools.
         */
-		//where $id is set?
-		$id = intval($id);
-		Database::query("DELETE FROM $tool_table WHERE c_id = $course_id AND id='$id' AND added_tool=1");
-	}
+        //where $id is set?
+        $id = intval($id);
+        Database::query("DELETE FROM $tool_table WHERE c_id = $course_id AND id='$id' AND added_tool=1");
+    }
 }
 
 // Course legal
@@ -67,25 +67,25 @@ if ($enabled == 'true') {
 // Start of tools for CourseAdmins (teachers/tutors)
 
 if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
-	$content .=  '<div class="courseadminview" style="border:0px; margin-top: 0px;padding:0px;">
+    $content .=  '<div class="courseadminview" style="border:0px; margin-top: 0px;padding:0px;">
 		<div class="normal-message" id="id_normal_message" style="display:none">';
-			$content .=  '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
-			$content .=  get_lang('PleaseStandBy');
-            $content .=  '</div>
+    $content .=  '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
+    $content .=  get_lang('PleaseStandBy');
+    $content .=  '</div>
 		<div class="confirmation-message" id="id_confirmation_message" style="display:none"></div>
 	</div>';
 
     $content .= $pluginExtra;
 
-	if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
+    if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
         $content .= '<div class="courseadminview">
             <span class="viewcaption">'.get_lang('SessionData').'</span>
             <table class="course_activity_home">'.CourseHome::show_session_data($session_id).'
             </table>
         </div>';
-	}
+    }
     $my_list = CourseHome::get_tools_category(TOOL_AUTHORING);
-	$items = CourseHome::show_tools_category($my_list);
+    $items = CourseHome::show_tools_category($my_list);
     $content .= return_block(get_lang('Authoring'),  $items, 'course-tools-author');
 
     $my_list = CourseHome::get_tools_category(TOOL_INTERACTION);
@@ -101,13 +101,13 @@ if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, tr
 
 } elseif (api_is_coach()) {
     $content .= $pluginExtra;
-	if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
-		$content .= '<div class="row">
+    if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
+        $content .= '<div class="row">
 			<span class="viewcaption">'.get_lang('SessionData').'</span>
 			<table class="course_activity_home">';
-				$content .= CourseHome::show_session_data($session_id);
-             $content .=  '</table></div>';
-	}
+        $content .= CourseHome::show_session_data($session_id);
+        $content .=  '</table></div>';
+    }
 
     $content .=  '<div class="row">';
     $my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
@@ -127,21 +127,77 @@ if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, tr
                     $onlyMaintenanceList[] = $item;
                 }
             }
-            
+
             $items = CourseHome::show_tools_category($onlyMaintenanceList);
             $content .= return_block(get_lang('Administration'), $items);
         }
     }
 } else {
-	$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
-	if (count($my_list) > 0) {
+    $tools = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
+
+    $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+        api_get_user_id(),
+        api_get_course_info()
+    );
+
+    // Force user icon for DRH
+    if ($isDrhOfCourse) {
+        $addUserTool = true;
+        foreach ($tools as $tool) {
+            if ($tool['name'] == 'user') {
+                $addUserTool = false;
+                break;
+            }
+        }
+
+        if ($addUserTool) {
+            $tools[] = array(
+                'c_id' => api_get_course_int_id(),
+                'name' => 'user',
+                'link' => 'user/user.php',
+                'image' => 'members.gif',
+                'visibility' => '1',
+                'admin' => '0',
+                'address' => 'squaregrey.gif',
+                'added_tool' => '0',
+                'target' => '_self',
+                'category' => 'interaction',
+                'session_id' => api_get_session_id()
+            );
+        }
+    }
+
+    if (count($tools) > 0) {
+        $content .= '<div class="row">';
+        $content .= CourseHome::show_tools_category($tools);
+        $content .= '</div>';
+    }
+
+    if ($isDrhOfCourse) {
+        $drhTool = CourseHome::get_tools_category(TOOL_DRH);
         $content .= '<div class="row">';
-        $content .= CourseHome::show_tools_category($my_list);
+        $content .= CourseHome::show_tools_category($drhTool);
         $content .= '</div>';
-	}
+    }
 }
 
-function return_block($title, $content, $class) {
-    $html = '<div class="row course-title-tools"><div class="span12"><div class="page-header"><h3>'.$title.'</h3></div></div></div><div class="row '.$class.'">'.$content.'</div>';
+/**
+ * @param string $title
+ * @param string $content
+ * @param string $class
+ *
+ * @return string
+ */
+function return_block($title, $content, $class = null)
+{
+    $html = '<div class="row course-title-tools">
+                <div class="span12">
+                    <div class="page-header">
+                        <h3>'.$title.'</h3>
+                    </div>
+                </div>
+            </div>
+            <div class="row '.$class.'">'.$content.'</div>';
+
     return $html;
 }

+ 15 - 12
main/course_home/course_home.php

@@ -127,18 +127,18 @@ $this_section = SECTION_COURSES;
 
 /*	Constants */
 
-define('TOOL_PUBLIC',                   'Public');
-define('TOOL_PUBLIC_BUT_HIDDEN',        'PublicButHide');
-define('TOOL_COURSE_ADMIN',             'courseAdmin');
-define('TOOL_PLATFORM_ADMIN',           'platformAdmin');
-define('TOOL_AUTHORING',                'toolauthoring');
-define('TOOL_INTERACTION',              'toolinteraction');
-define('TOOL_COURSE_PLUGIN',            'toolcourseplugin'); //all plugins that can be enabled in courses
-define('TOOL_ADMIN',                    'tooladmin');
-define('TOOL_ADMIN_PLATFORM',           'tooladminplatform');
-
-define('TOOL_STUDENT_VIEW',              'toolstudentview');
-define('TOOL_ADMIN_VISIBLE',             'tooladminvisible');
+define('TOOL_PUBLIC', 'Public');
+define('TOOL_PUBLIC_BUT_HIDDEN', 'PublicButHide');
+define('TOOL_COURSE_ADMIN', 'courseAdmin');
+define('TOOL_PLATFORM_ADMIN', 'platformAdmin');
+define('TOOL_AUTHORING', 'toolauthoring');
+define('TOOL_INTERACTION', 'toolinteraction');
+define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
+define('TOOL_ADMIN', 'tooladmin');
+define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
+define('TOOL_DRH', 'tool_drh');
+define('TOOL_STUDENT_VIEW', 'toolstudentview');
+define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
 
 $user_id 		= api_get_user_id();
 $course_code 	= api_get_course_id();
@@ -279,4 +279,7 @@ $tpl->assign('course_code', $course_code);
 
 $tpl->display_one_col_template();
 Session::erase('_gid');
+// Deleting the objects
+Session::erase('oLP');
+Session::erase('lpobject');
 DocumentManager::removeGeneratedAudioTempFile();

+ 54 - 14
main/course_info/infocours.php

@@ -14,8 +14,6 @@
  * @package chamilo.course_info
  */
 
-/*	   INIT SECTION */
-
 // Language files that need to be included
 $language_file = array('create_course', 'course_info', 'admin', 'gradebook', 'document');
 require_once '../inc/global.inc.php';
@@ -32,20 +30,21 @@ require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
 
 api_protect_course_script(true);
 api_block_anonymous_users();
+$_course = api_get_course_info();
 
 /*	Constants and variables */
 define('MODULE_HELP_NAME', 'Settings');
 define('COURSE_CHANGE_PROPERTIES', 'COURSE_CHANGE_PROPERTIES');
 
-$currentCourseRepository    = $_course['path'];
-$is_allowedToEdit 			= $is_courseAdmin || $is_platformAdmin;
+$currentCourseRepository = $_course['path'];
+$is_allowedToEdit = $is_courseAdmin || $is_platformAdmin;
 
-$course_code 				= api_get_course_id();
-$course_access_settings 	= CourseManager :: get_access_settings($course_code);
+$course_code = api_get_course_id();
+$course_access_settings = CourseManager:: get_access_settings($course_code);
 
 //LOGIC FUNCTIONS
 function is_settings_editable() {
-	return isset($GLOBALS['course_info_is_editable']) && $GLOBALS['course_info_is_editable'];
+    return isset($GLOBALS['course_info_is_editable']) && $GLOBALS['course_info_is_editable'];
 }
 
 /* MAIN CODE */
@@ -60,10 +59,10 @@ if (api_get_setting('pdf_export_watermark_by_course') == 'true') {
         $show_delete_watermark_text_message = true;
     }
 }
-$tbl_user              = Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_admin             = Database :: get_main_table(TABLE_MAIN_ADMIN);
-$tbl_course_user       = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_course            = Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user = Database:: get_main_table(TABLE_MAIN_USER);
+$tbl_admin = Database:: get_main_table(TABLE_MAIN_ADMIN);
+$tbl_course_user = Database:: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_course = Database:: get_main_table(TABLE_MAIN_COURSE);
 
 $s_select_course_tutor_name = "SELECT tutor_name FROM $tbl_course WHERE code='$course_code'";
 $q_tutor = Database::query($s_select_course_tutor_name);
@@ -79,7 +78,7 @@ $q_result_titulars = Database::query($s_sql_course_titular);
 if (Database::num_rows($q_result_titulars) == 0) {
     $sql = "SELECT username, lastname, firstname FROM $tbl_user as user, $tbl_admin as admin
             WHERE admin.user_id=user.user_id ORDER BY ".$target_name." ASC";
-	$q_result_titulars = Database::query($sql);
+    $q_result_titulars = Database::query($sql);
 }
 
 $a_profs[0] = '-- '.get_lang('NoManager').' --';
@@ -115,7 +114,11 @@ if ($form->validate() && is_settings_editable()) {
     // update course picture
     $picture = $_FILES['picture'];
     if (!empty($picture['name'])) {
-        $picture_uri = CourseManager::update_course_picture($course_code, $picture['name'], $picture['tmp_name']);
+        $picture_uri = CourseManager::update_course_picture(
+            $course_code,
+            $picture['name'],
+            $picture['tmp_name']
+        );
     }
 }
 
@@ -147,6 +150,8 @@ $form->addElement('file', 'picture', get_lang('AddPicture'));
 $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
 $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 
+$form->addElement('checkbox', 'delete_picture', null, get_lang('DeletePicture'));
+
 if (api_get_setting('pdf_export_watermark_by_course') == 'true') {
     $url =  PDF::get_watermark($course_code);
     $form->add_textfield('pdf_export_watermark_text', get_lang('PDFExportWatermarkTextTitle'), false, array('size' => '60'));
@@ -413,6 +418,38 @@ $form->setDefaults($values);
 if ($form->validate() && is_settings_editable()) {
     $updateValues = $form->exportValues();
 
+    $visibility = $updateValues['visibility'];
+    $deletePicture = $updateValues['delete_picture'];
+
+    if ($deletePicture) {
+        CourseManager::deleteCoursePicture($course_code);
+    }
+
+    global $_configuration;
+    $urlId = api_get_current_access_url_id();
+    if (isset($_configuration[$urlId]) &&
+        isset($_configuration[$urlId]['hosting_limit_active_courses']) &&
+        $_configuration[$urlId]['hosting_limit_active_courses'] > 0
+    ) {
+        $courseInfo = api_get_course_info($course_code);
+
+        // Check if
+        if ($courseInfo['visibility'] == COURSE_VISIBILITY_HIDDEN &&
+            $visibility != $courseInfo['visibility']
+        ) {
+            $num = CourseManager::countActiveCourses($urlId);
+            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
+                api_warn_hosting_contact('hosting_limit_active_courses');
+
+                api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
+
+                $url = api_get_path(WEB_CODE_PATH).'course_info/infocours.php?action=course_active_warning&cidReq='.$course_code;
+                header("Location: $url");
+                exit;
+            }
+        }
+    }
+
     $pdf_export_watermark_path = isset($_FILES['pdf_export_watermark_path']) ? $_FILES['pdf_export_watermark_path'] : null;
 
     if (!empty($pdf_export_watermark_path['name'])) {
@@ -486,10 +523,13 @@ Display :: display_header($nameTools, MODULE_HELP_NAME);
 if ($show_delete_watermark_text_message) {
     Display :: display_normal_message(get_lang('FileDeleted'));
 }
-//api_display_tool_title($nameTools);
+
 if (isset($_GET['action']) && $_GET['action'] == 'show_message') {
     Display :: display_normal_message(get_lang('ModifDone'));
 }
+if (isset($_GET['action']) && $_GET['action'] == 'course_active_warning') {
+    Display :: display_warning_message(get_lang('PortalActiveCoursesLimitReached'));
+}
 
 echo '<script>
 $(function() {

+ 28 - 20
main/course_progress/thematic_controller.php

@@ -1,20 +1,20 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
- * This file contains class used like controller for thematic, it should be included inside a dispatcher file (e.g: index.php)
+ * Thematic Controller script.
+ * Prepares the common background variables to give to the scripts corresponding to
+ * the requested action
+ *
+ * This file contains class used like controller for thematic,
+ * it should be included inside a dispatcher file (e.g: index.php)
  *
- * !!! WARNING !!! : ALL DATES IN THIS MODULE ARE STORED IN UTC ! DO NOT CONVERT DURING THE TRANSITION FROM CHAMILO 1.8.x TO 2.0
+ * !!! WARNING !!! : ALL DATES IN THIS MODULE ARE STORED IN UTC !
+ * DO NOT CONVERT DURING THE TRANSITION FROM CHAMILO 1.8.x TO 2.0
  *
  * @author Christian Fasanando <christian1827@gmail.com>
  * @author Julio Montoya <gugli100@gmail.com> token support improving UI
- * @package chamilo.course_progress
- */
-
-/**
- * Thematic Controller script. Prepares the common background variables to give to the scripts corresponding to
- * the requested action
+ *
  * @package chamilo.course_progress
  */
 class ThematicController
@@ -171,7 +171,11 @@ class ThematicController
                 case 'thematic_export_pdf':
                     $list = $thematic->get_thematic_list();
                     $table = array();
-                    $table[] = array(get_lang('Thematic'), get_lang('ThematicPlan'), get_lang('ThematicAdvance'));
+                    $table[] = array(
+                        get_lang('Thematic'),
+                        get_lang('ThematicPlan'),
+                        get_lang('ThematicAdvance')
+                    );
                     foreach ($list as $theme) {
                         $data = $thematic->get_thematic_plan_data($theme['id']);
                         $plan_html = null;
@@ -260,29 +264,30 @@ class ThematicController
 
     /**
      * This method is used for thematic plan control (update, insert or listing)
-     * @param 	string	Action
+     * @param 	string	$action
      * render to thematic_plan.php
      */
     public function thematic_plan($action)
     {
         $thematic = new Thematic();
-
         $data = array();
         $error = false;
-
         if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {
             if (isset($_POST['action']) && ($_POST['action'] == 'thematic_plan_add' || $_POST['action'] == 'thematic_plan_edit')) {
                 if (isset($_POST['title'])) {
                     if ($_POST['thematic_plan_token'] == $_SESSION['thematic_plan_token']) {
                         if (api_is_allowed_to_edit(null, true)) {
-
                             $title_list = $_REQUEST['title'];
-                            //$description_list   = $_REQUEST['desc'];
                             $description_list = $_REQUEST['description'];
                             $description_type = $_REQUEST['description_type'];
                             for ($i = 1; $i < count($title_list) + 1; $i++) {
-                                $thematic->set_thematic_plan_attributes($_REQUEST['thematic_id'], $title_list[$i], $description_list[$i], $description_type[$i]);
-                                $affected_rows = $thematic->thematic_plan_save();
+                                $thematic->set_thematic_plan_attributes(
+                                    $_REQUEST['thematic_id'],
+                                    $title_list[$i],
+                                    $description_list[$i],
+                                    $description_type[$i]
+                                );
+                                $thematic->thematic_plan_save();
                             }
                             unset($_SESSION['thematic_plan_token']);
                             $data['message'] = 'ok';
@@ -292,6 +297,7 @@ class ThematicController
                             $saveRedirect.= 'thematic_plan_save_message=ok';
 
                             header("Location: $saveRedirect");
+                            exit;
                         }
                         $data['action'] = 'thematic_plan_list';
                     }
@@ -360,8 +366,9 @@ class ThematicController
 
     /**
      * This method is used for thematic advance control (update, insert or listing)
-     * @param 	string	$action
      * render to thematic_advance.php
+     * @param 	string	$action
+     *
      */
     public function thematic_advance($action)
      {
@@ -400,7 +407,9 @@ class ThematicController
                     exit;
                 }
 
-                if (($_REQUEST['start_date_type'] == 1 && empty($_REQUEST['start_date_by_attendance'])) || (!empty($_REQUEST['duration_in_hours']) && !is_numeric($_REQUEST['duration_in_hours']))) {
+                if (($_REQUEST['start_date_type'] == 1 && empty($_REQUEST['start_date_by_attendance'])) ||
+                    (!empty($_REQUEST['duration_in_hours']) && !is_numeric($_REQUEST['duration_in_hours']))
+                ) {
                     if ($_REQUEST['start_date_type'] == 1 && empty($_REQUEST['start_date_by_attendance'])) {
                         $start_date_error = true;
                         $data['start_date_error'] = $start_date_error;
@@ -488,5 +497,4 @@ class ThematicController
         $this->view->set_template('thematic_advance');
         $this->view->render();
     }
-
 }

+ 14 - 5
main/coursecopy/classes/CourseArchiver.class.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 require_once 'Course.class.php';
@@ -22,7 +21,10 @@ class CourseArchiver
         $dir = api_get_path(SYS_ARCHIVE_PATH);
         if ($handle = @ opendir($dir)) {
             while (($file = readdir($handle)) !== false) {
-                if ($file != "." && $file != ".." && strpos($file, 'CourseArchiver_') === 0 && is_dir($dir . '/' . $file)) {
+                if ($file != "." && $file != ".." &&
+                    strpos($file, 'CourseArchiver_') === 0 &&
+                    is_dir($dir . '/' . $file)
+                ) {
                     rmdirr($dir . '/' . $file);
                 }
             }
@@ -152,15 +154,20 @@ class CourseArchiver
                     $course_code = $file_parts[1];
                     $file_parts = explode('.', $file_parts[2]);
                     $date = $file_parts[0];
-                    $ext = $file_parts[1];
+                    $ext = isset($file_parts[1]) ? $file_parts[1] : null;
                     if ($ext == 'zip' && ($user_id != null && $owner_id == $user_id || $user_id == null)) {
                         $date = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2) . ' ' . substr($date, 9, 2) . ':' . substr($date, 11, 2) . ':' . substr($date, 13, 2);
-                        $backup_files[] = array('file' => $file, 'date' => $date, 'course_code' => $course_code);
+                        $backup_files[] = array(
+                            'file' => $file,
+                            'date' => $date,
+                            'course_code' => $course_code
+                        );
                     }
                 }
             }
             closedir($dir);
         }
+
         return $backup_files;
     }
 
@@ -174,8 +181,10 @@ class CourseArchiver
         $new_dir = api_get_path(SYS_ARCHIVE_PATH);
         if (is_dir($new_dir) && is_writable($new_dir)) {
             move_uploaded_file($file, api_get_path(SYS_ARCHIVE_PATH).$new_filename);
+
             return $new_filename;
         }
+
         return false;
     }
 
@@ -218,7 +227,7 @@ class CourseArchiver
             return new Course();
         }
         $course->backup_path = $unzip_dir;
+
         return $course;
     }
-
 }

+ 88 - 84
main/coursecopy/classes/CourseBuilder.class.php

@@ -29,13 +29,14 @@ require_once 'Work.class.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/question.class.php';
 
 /**
- * Class which can build a course-object from a Chamilo-course.
+ * Class CourseBuilder
+ * Builds a course-object from a Chamilo-course.
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package chamilo.backup
  */
 class CourseBuilder
 {
-    /** Course */
+    /** @var Course  */
     public $course;
 
     /* With this array you can filter the tools you want to be parsed by
@@ -67,8 +68,10 @@ class CourseBuilder
 
     /**
      * Create a new CourseBuilder
+     * @param string $type
+     * @param null $course
      */
-	public function __construct($type='', $course = null)
+    public function __construct($type='', $course = null)
     {
         $_course = api_get_course_info();
 
@@ -87,7 +90,6 @@ class CourseBuilder
     }
 
     /**
-     *
      * @param array $array
      */
     public function set_tools_to_build($array)
@@ -121,7 +123,7 @@ class CourseBuilder
      * @param bool     true if you want to get the elements that exists in the course and
      *                 in the session, (session_id = 0 or session_id = X)
      */
-	public function build($session_id = 0, $course_code = '', $with_base_content = false)
+    public function build($session_id = 0, $course_code = '', $with_base_content = false)
     {
         $table_link       = Database :: get_course_table(TABLE_LINKED_RESOURCES);
         $table_properties = Database :: get_course_table(TABLE_ITEM_PROPERTY);
@@ -467,7 +469,7 @@ class CourseBuilder
             //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
         } else {
             $sql = "SELECT * FROM $table_qui WHERE c_id = $course_id AND active >=0 AND session_id = 0";
-             //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
+            //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
         }
 
         $db_result = Database::query($sql);
@@ -747,11 +749,11 @@ class CourseBuilder
         $db_result = Database::query($sql);
         while ($obj = Database::fetch_object($db_result)) {
             $survey = new Survey($obj->survey_id, $obj->code,$obj->title,
-                                $obj->subtitle, $obj->author, $obj->lang,
-                                $obj->avail_from, $obj->avail_till, $obj->is_shared,
-                                $obj->template, $obj->intro, $obj->surveythanks,
-                                $obj->creation_date, $obj->invited, $obj->answered,
-                                $obj->invite_mail, $obj->reminder_mail);
+                $obj->subtitle, $obj->author, $obj->lang,
+                $obj->avail_from, $obj->avail_till, $obj->is_shared,
+                $obj->template, $obj->intro, $obj->surveythanks,
+                $obj->creation_date, $obj->invited, $obj->answered,
+                $obj->invite_mail, $obj->reminder_mail);
             $sql = 'SELECT * FROM '.$table_question.' WHERE c_id = '.$course_id.' AND survey_id = '.$obj->survey_id;
             $db_result2 = Database::query($sql);
             while ($obj2 = Database::fetch_object($db_result2)){
@@ -925,75 +927,75 @@ class CourseBuilder
 
         $db_result = Database::query($sql);
         if ($db_result)
-        while ($obj = Database::fetch_object($db_result)) {
-            $items = array();
-            $sql_items = "SELECT * FROM ".$table_item." WHERE c_id = '$course_id' AND lp_id = ".$obj->id;
-            $db_items = Database::query($sql_items);
-            while ($obj_item = Database::fetch_object($db_items)) {
-                $item['id']                   = $obj_item->id;
-                $item['item_type']            = $obj_item->item_type;
-                $item['ref']                = $obj_item->ref;
-                $item['title']                = $obj_item->title;
-                $item['description']        = $obj_item->description;
-                $item['path']                = $obj_item->path;
-                $item['min_score']            = $obj_item->min_score;
-                $item['max_score']            = $obj_item->max_score;
-                $item['mastery_score']        = $obj_item->mastery_score;
-                $item['parent_item_id']    = $obj_item->parent_item_id;
-                $item['previous_item_id']  = $obj_item->previous_item_id;
-                $item['next_item_id']        = $obj_item->next_item_id;
-                $item['display_order']     = $obj_item->display_order;
-                $item['prerequisite']       = $obj_item->prerequisite;
-                $item['parameters']        = $obj_item->parameters;
-                $item['launch_data']        = $obj_item->launch_data;
-                $item['audio']                = $obj_item->audio;
-                $items[] = $item;
-            }
+            while ($obj = Database::fetch_object($db_result)) {
+                $items = array();
+                $sql_items = "SELECT * FROM ".$table_item." WHERE c_id = '$course_id' AND lp_id = ".$obj->id;
+                $db_items = Database::query($sql_items);
+                while ($obj_item = Database::fetch_object($db_items)) {
+                    $item['id']                   = $obj_item->id;
+                    $item['item_type']            = $obj_item->item_type;
+                    $item['ref']                = $obj_item->ref;
+                    $item['title']                = $obj_item->title;
+                    $item['description']        = $obj_item->description;
+                    $item['path']                = $obj_item->path;
+                    $item['min_score']            = $obj_item->min_score;
+                    $item['max_score']            = $obj_item->max_score;
+                    $item['mastery_score']        = $obj_item->mastery_score;
+                    $item['parent_item_id']    = $obj_item->parent_item_id;
+                    $item['previous_item_id']  = $obj_item->previous_item_id;
+                    $item['next_item_id']        = $obj_item->next_item_id;
+                    $item['display_order']     = $obj_item->display_order;
+                    $item['prerequisite']       = $obj_item->prerequisite;
+                    $item['parameters']        = $obj_item->parameters;
+                    $item['launch_data']        = $obj_item->launch_data;
+                    $item['audio']                = $obj_item->audio;
+                    $items[] = $item;
+                }
 
-            $sql_tool = "SELECT id FROM $table_tool
+                $sql_tool = "SELECT id FROM $table_tool
                          WHERE
                             c_id = $course_id AND
                             (link LIKE '%lp_controller.php%lp_id=".$obj->id."%' AND image='scormbuilder.gif') AND
                             visibility = '1' ";
-            $db_tool = Database::query($sql_tool);
+                $db_tool = Database::query($sql_tool);
 
-            if (Database::num_rows($db_tool)) {
-                $visibility = '1';
-            } else {
-                $visibility = '0';
-            }
+                if (Database::num_rows($db_tool)) {
+                    $visibility = '1';
+                } else {
+                    $visibility = '0';
+                }
 
-            $lp = new CourseCopyLearnpath(
-                $obj->id,
-                $obj->lp_type,
-                $obj->name,
-                $obj->path,
-                $obj->ref,
-                $obj->description,
-                $obj->content_local,
-                $obj->default_encoding,
-                $obj->default_view_mod,
-                $obj->prevent_reinit,
-                $obj->force_commit,
-                $obj->content_maker,
-                $obj->display_order,
-                $obj->js_lib,
-                $obj->content_license,
-                $obj->debug,
-                $visibility,
-                $obj->author,
-                $obj->preview_image,
-                $obj->use_max_score,
-                $obj->autolunch,
-                $obj->created_on,
-                $obj->modified_on,
-                $obj->publicated_on,
-                $obj->expired_on,
-                $obj->session_id,
-                $items
-            );
-            $this->course->add_resource($lp);
-        }
+                $lp = new CourseCopyLearnpath(
+                    $obj->id,
+                    $obj->lp_type,
+                    $obj->name,
+                    $obj->path,
+                    $obj->ref,
+                    $obj->description,
+                    $obj->content_local,
+                    $obj->default_encoding,
+                    $obj->default_view_mod,
+                    $obj->prevent_reinit,
+                    $obj->force_commit,
+                    $obj->content_maker,
+                    $obj->display_order,
+                    $obj->js_lib,
+                    $obj->content_license,
+                    $obj->debug,
+                    $visibility,
+                    $obj->author,
+                    $obj->preview_image,
+                    $obj->use_max_score,
+                    $obj->autolunch,
+                    $obj->created_on,
+                    $obj->modified_on,
+                    $obj->publicated_on,
+                    $obj->expired_on,
+                    $obj->session_id,
+                    $items
+                );
+                $this->course->add_resource($lp);
+            }
 
         // Save scorm directory (previously build_scorm_documents())
         $i = 1;
@@ -1092,7 +1094,7 @@ class CourseBuilder
         $course_id         = $course_info['real_id'];
 
         if (!empty($session_id) && !empty($course_code)) {
-             $session_id = intval($session_id);
+            $session_id = intval($session_id);
             if ($with_base_content) {
                 $session_condition = api_get_session_condition($session_id, true, true);
             } else {
@@ -1111,8 +1113,8 @@ class CourseBuilder
     }
 
     /**
-    * Build the Surveys
-    */
+     * Build the Surveys
+     */
     public function build_thematic($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
     {
         $table_thematic            = Database :: get_course_table(TABLE_THEMATIC);
@@ -1149,7 +1151,7 @@ class CourseBuilder
                     //$thematic_plan_complete_list[$item['ref']] = $item;
                 }
             }
-             if (count($thematic_plan_id_list) > 0) {
+            if (count($thematic_plan_id_list) > 0) {
                 $sql = "SELECT tp.*
                         FROM $table_thematic_plan tp
                             INNER JOIN $table_thematic t ON (t.id=tp.thematic_id)
@@ -1169,8 +1171,8 @@ class CourseBuilder
     }
 
     /**
-    * Build the attendances
-    */
+     * Build the attendances
+     */
     public function build_attendance($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
     {
         $table_attendance            = Database :: get_course_table(TABLE_ATTENDANCE);
@@ -1196,21 +1198,23 @@ class CourseBuilder
 
     /**
      * Build the works (or "student publications", or "assignments")
+     *
+     * @param int $session_id
+     * @param string $course_code
+     * @param bool $with_base_content
+     * @param array $id_list
      */
     public function build_works($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
     {
         $table_work  = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
-        //$table_work_assignment  = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
-
         $course_id = api_get_course_int_id();
-
         $sessionCondition = api_get_session_condition($session_id, true, $with_base_content);
 
         $sql = "SELECT * FROM $table_work
                 WHERE
-                    c_id = $course_id 
+                    c_id = $course_id
                     $sessionCondition AND
-                    filetype = \'folder\' AND
+                    filetype = 'folder' AND
                     parent_id = 0 AND
                     active = 1";
         $db_result = Database::query($sql);

+ 37 - 7
main/coursecopy/classes/CourseCopyLearnpath.class.php

@@ -1,11 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
- * A learnpath
+ * Class CourseCopyLearnpath
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package chamilo.backup
  */
-class CourseCopyLearnpath extends Resource {
+class CourseCopyLearnpath extends Resource
+{
 	/**
 	 * Type of learnpath (can be dokeos (1), scorm (2), aicc (3))
 	 */
@@ -106,9 +108,35 @@ class CourseCopyLearnpath extends Resource {
 	 * @param string $visibility
 	 * @param array  $items
 	 */
-	function CourseCopyLearnpath($id,$type,$name, $path,$ref,$description,$content_local,$default_encoding,$default_view_mode,$prevent_reinit,$force_commit,
-	                             $content_maker, $display_order,$js_lib,$content_license,$debug, $visibility, $author, $preview_image,
-	                             $use_max_score, $autolunch, $created_on, $modified_on, $publicated_on, $expired_on, $session_id, $items) {
+	public function CourseCopyLearnpath(
+		$id,
+		$type,
+		$name,
+		$path,
+		$ref,
+		$description,
+		$content_local,
+		$default_encoding,
+		$default_view_mode,
+		$prevent_reinit,
+		$force_commit,
+		$content_maker,
+		$display_order,
+		$js_lib,
+		$content_license,
+		$debug,
+		$visibility,
+		$author,
+		$preview_image,
+		$use_max_score,
+		$autolunch,
+		$created_on,
+		$modified_on,
+		$publicated_on,
+		$expired_on,
+		$session_id,
+		$items
+	) {
 		parent::Resource($id,RESOURCE_LEARNPATH);
 		$this->lp_type = $type;
 		$this->name = $name;
@@ -147,6 +175,7 @@ class CourseCopyLearnpath extends Resource {
 	{
 		return $this->items;
 	}
+
 	/**
 	 * Check if a given resource is used as an item in this chapter
 	 */
@@ -154,13 +183,14 @@ class CourseCopyLearnpath extends Resource {
 	{
 		foreach ($this->items as $item) {
 			if ($item['id'] == $resource->get_id() &&
-                isset($item['type']) && $item['type'] == $resource->get_type()
-            ) {
+				isset($item['type']) && $item['type'] == $resource->get_type()
+			) {
 				return true;
 			}
 		}
 		return false;
 	}
+
 	/**
 	 * Show this learnpath
 	 */

+ 2 - 1
main/coursecopy/classes/CourseCopyTestCategory.php

@@ -34,7 +34,8 @@ class CourseCopyTestcategory extends Resource
     /**
      * Show the test_category title, used in the partial recycle_course.php form
      */
-    function show() {
+    function show()
+    {
         parent::show();
         echo $this->title;
     }

+ 7 - 4
main/coursecopy/classes/CourseDescription.class.php

@@ -21,24 +21,27 @@ class CourseDescription extends Resource
 	/**
 	 * The description type
 	 */
-	var $description_type;	
+	var $description_type;
 	/**
 	 * Create a new course description
 	 * @param int $id
 	 * @param string $title
 	 * @param string $content
 	 */
-	function __construct($id,$title,$content,$description_type) {
+	function __construct($id,$title,$content,$description_type)
+	{
 		parent::Resource($id,RESOURCE_COURSEDESCRIPTION);
 		$this->title = $title;
 		$this->content = $content;
 		$this->description_type = $description_type;
 	}
+
 	/**
 	 * Show this Event
 	 */
-	function show() {
+	function show()
+	{
 		parent::show();
 		echo $this->title;
 	}
-}
+}

+ 2 - 2
main/coursecopy/copy_course_session.php

@@ -90,7 +90,7 @@ function make_select_session_list($name, $sessions, $attr = array())
 function display_form()
 {
     $html  = '';
-    $sessions = SessionManager::get_sessions_list(null, array('name ASC'));
+    $sessions = SessionManager::get_sessions_list(array(), array('name', 'ASC'));
 
     // Actions
     $html .= '<div class="actions">';
@@ -166,7 +166,7 @@ function search_courses($id_session, $type)
             // Build select for destination sessions where is not included current session from select origin
             if (!empty($id_session)) {
 
-                $sessions = SessionManager::get_sessions_list(null, array('name ASC'));
+                $sessions = SessionManager::get_sessions_list(array(), array('name', 'ASC'));
 
                 $select_destination .= '<select name="sessions_list_destination" width="380px" onchange = "javascript: xajax_search_courses(this.value,\'destination\');">';
                 $select_destination .= '<option value = "0">-- '.get_lang('SelectASession').' --</option>';

+ 119 - 0
main/cron/hosting_total_size_limit.php

@@ -0,0 +1,119 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+require_once __DIR__.'/../inc/global.inc.php';
+require_once __DIR__.'/../../vendor/autoload.php';
+
+/**
+ * Checks total platform size
+ * @param bool $debug
+ *
+ * @return bool
+ */
+function isTotalPortalSizeBiggerThanLimit($debug = true)
+{
+    $sizeLimit = api_get_configuration_value('hosting_total_size_limit');
+    if (empty($sizeLimit)) {
+        return true;
+    }
+
+    $updateFile = true;
+    $file = api_get_path(SYS_COURSE_PATH).'hosting_total_size.php';
+
+    // Default data
+    $hostingData = array(
+        'frequency' => 86400,
+    );
+
+    $log = null;
+
+    // Check if file exists and if it is updated
+    if (file_exists($file)) {
+        $hostingDataFromFile = require $file;
+
+        // Check time() is UTC
+        if (isset($hostingDataFromFile['updated_at']) &&
+            isset($hostingDataFromFile['frequency']) &&
+            isset($hostingDataFromFile['size'])
+        ) {
+            $hostingData = $hostingDataFromFile;
+
+            $time = $hostingData['updated_at'] + $hostingData['frequency'];
+            $diff = $time - time();
+
+            if ($time > time()) {
+                $log .= "You need to wait $diff seconds to update the file \n";
+                $updateFile = false;
+            }
+        }
+    }
+
+    // Now get values for total portal size
+    $log .= "Frequency loaded: ".$hostingData['frequency']."\n";
+
+    if ($updateFile) {
+        $log .= "Updating total size ... \n";
+        $totalSize = calculateTotalPortalSize($debug);
+        $log .= "Total size calculated: $totalSize \n";
+
+        $hostingData['updated_at'] = time();
+        $hostingData['size'] = $totalSize;
+
+        $writer = new Zend\Config\Writer\PhpArray();
+        $phpCode = $writer->toString($hostingData);
+        file_put_contents($file, $phpCode);
+        $log .= "File saved in $file \n";
+    } else {
+        $log .= "Total size not updated \n";
+        $totalSize = $hostingData['size'];
+    }
+
+    $result = true;
+
+    if ($totalSize > $sizeLimit) {
+        $log .= "Current total size of $totalSize MB is bigger than limit: $sizeLimit MB \n";
+        $result = false;
+    }
+
+    if ($debug) {
+        echo $log;
+    }
+
+    return $result;
+}
+
+/**
+ * @param bool $debug
+ *
+ * @return int total size in MB
+ */
+function calculateTotalPortalSize($debug)
+{
+    $table = Database::get_course_table(TABLE_DOCUMENT);
+    // Documents
+    $sql = "SELECT SUM(size) total FROM $table
+            WHERE filetype = 'file' AND c_id <> ''";
+    $result = Database::query($sql);
+    $row = Database::fetch_array($result, 'ASSOC');
+    $totalSize = $row['total'];
+
+    if ($debug) {
+        echo "Total size in table $table " . (round($totalSize / 1024)) . " MB \n";
+    }
+
+    $table = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
+    $sql = "SELECT SUM(size) total FROM $table WHERE c_id <> ''";
+    $result = Database::query($sql);
+    $row = Database::fetch_array($result, 'ASSOC');
+    $subTotal = $row['total'];
+    $totalSize += $subTotal;
+    if ($debug) {
+        echo "Total size in table $table " . (round($subTotal / 1024)) . " MB \n";
+    }
+
+    $totalSize = $totalSize / 1024;
+
+    return $totalSize;
+}
+
+isTotalPortalSizeBiggerThanLimit(true);

+ 103 - 27
main/cron/import_csv.php

@@ -12,6 +12,9 @@ if (file_exists('multiple_url_fix.php')) {
 require_once __DIR__.'/../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'log.class.php';
 
+ini_set('memory_limit', -1);
+ini_set('max_execution_time', 0);
+
 /**
  * Class ImportCsv
  */
@@ -25,6 +28,7 @@ class ImportCsv
         'session' => 'external_session_id',
         'course' => 'external_course_id',
         'user' => 'external_user_id',
+        'calendar_event' => 'external_calendar_event_id'
     );
     public $defaultAdminId = 1;
     public $defaultSessionVisibility = 1;
@@ -196,18 +200,28 @@ class ImportCsv
             'External user id',
             null
         );
+
         // Create course extra field: extra_external_course_id
         CourseManager::create_course_extra_field(
             $this->extraFieldIdNameList['course'],
             1,
             'External course id'
         );
+
         // Create session extra field extra_external_session_id
         SessionManager::create_session_extra_field(
             $this->extraFieldIdNameList['session'],
             1,
             'External session id'
         );
+
+        // Create calendar_event extra field extra_external_session_id
+        $extraField = new ExtraField('calendar_event');
+        $extraField->save(array(
+            'field_type' => ExtraField::FIELD_TYPE_TEXT,
+            'field_variable' => $this->extraFieldIdNameList['calendar_event'],
+            'field_display_text' => 'External calendar event id'
+        ));
     }
 
     /**
@@ -622,7 +636,9 @@ class ImportCsv
 
     /**
      * @param string $file
-     * @param bool $moveFile
+     * @param bool   $moveFile
+     *
+     * @return int
      */
     private function importCalendarStatic($file, $moveFile = true)
     {
@@ -646,7 +662,7 @@ class ImportCsv
                 }
 
                 if (empty($sessionId)) {
-                    $this->logger->addInfo("Session '$sessionId' does not exists.");
+                    $this->logger->addInfo("external_sessionID: ".$row['external_sessionID']." does not exists.");
                 }
                 $teacherId = null;
 
@@ -684,7 +700,7 @@ class ImportCsv
                     $errorFound = true;
 
                     $this->logger->addInfo(
-                        "No teacher found in  '$courseCode' and session: $sessionId"
+                        "No teacher found in course code : '$courseCode' and session: '$sessionId'"
                     );
                 }
 
@@ -714,7 +730,8 @@ class ImportCsv
                         'title' => $title,
                         'sender_id' => $teacherId,
                         'course_id' => $courseInfo['real_id'],
-                        'session_id' => $sessionId
+                        'session_id' => $sessionId,
+                        $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID']
                     );
                 }
             }
@@ -727,38 +744,95 @@ class ImportCsv
                 return 0;
             }
 
-            if ($errorFound == false) {
+            $this->logger->addInfo(
+                "Ready to insert events"
+            );
+
+            $content = null;
+            $agenda = new Agenda();
+
+            $extraFieldValue = new ExtraFieldValue('calendar_event');
+            $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
+            $externalEventId = null;
+
+            $extraField = new ExtraField('calendar_event');
+            $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
+
+            if (empty($extraFieldInfo)) {
                 $this->logger->addInfo(
-                    "Ready to insert events"
+                    "No calendar event extra field created: $extraFieldName"
                 );
 
-                $content = null;
-                $agenda = new Agenda();
-
-                foreach ($eventsToCreate as $event) {
-                    $courseInfo = api_get_course_info_by_id($event['course_id']);
-                    $agenda->set_course($courseInfo);
-                    $agenda->setType('course');
-                    $agenda->setSessionId($event['session_id']);
-                    $agenda->setSenderId($event['sender_id']);
-                    $eventId = $agenda->add_event(
-                        $event['start'],
-                        $event['end'],
-                        false,
-                        $event['title'],
-                        $content,
-                        array('everyone'), // send to
-                        false //$addAsAnnouncement = false
+                return 0;
+            }
+
+            foreach ($eventsToCreate as $event) {
+                if (!isset($event[$extraFieldName])) {
+                    $this->logger->addInfo(
+                        "No external_calendar_itemID found. Skipping ..."
+                    );
+                    continue;
+                } else {
+                    $externalEventId = $event[$extraFieldName];
+                    $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
+                        $extraFieldName,
+                        $externalEventId
+                    );
+
+                    if (!empty($item) || empty($externalEventId)) {
+                        $this->logger->addInfo(
+                            "Event #$externalEventId was already added . Skipping ..."
+                        );
+                        continue;
+                    }
+                }
+
+                $courseInfo = api_get_course_info_by_id($event['course_id']);
+                $agenda->set_course($courseInfo);
+                $agenda->setType('course');
+                $agenda->setSessionId($event['session_id']);
+                $agenda->setSenderId($event['sender_id']);
+
+                if (empty($courseInfo)) {
+                    $this->logger->addInfo(
+                        "No course found for added: #".$event['course_id']." Skipping ..."
                     );
+                    continue;
+                }
 
+                if (empty($event['sender_id'])) {
                     $this->logger->addInfo(
-                        "Event added: #$eventId"
+                        "No sender found: #".$event['sender_id']." Skipping ..."
                     );
+                    continue;
                 }
-            } else {
-                echo 'There was an error check the logs in archive/import_csv.log ';
 
-                return 0;
+                $eventId = $agenda->add_event(
+                    $event['start'],
+                    $event['end'],
+                    false,
+                    $event['title'],
+                    $content,
+                    array('everyone'), // send to
+                    false //$addAsAnnouncement = false
+                );
+
+                if (!empty($eventId)) {
+                    $extraFieldValue->save(
+                        array(
+                            'field_value' => $externalEventId,
+                            'field_id' => $extraFieldInfo['id'],
+                            'calendar_event_id' => $eventId
+                        )
+                    );
+                    $this->logger->addInfo(
+                        "Event added: #$eventId"
+                    );
+                } else {
+                    $this->logger->addInfo(
+                        "Error while creating event."
+                    );
+                }
             }
         }
 
@@ -1232,6 +1306,8 @@ $logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
 
 $cronImportCSVConditions = isset($_configuration['cron_import_csv_conditions']) ? $_configuration['cron_import_csv_conditions'] : null;
 
+echo 'See the error log here: '.api_get_path(SYS_ARCHIVE_PATH).'import_csv.log'."\n";
+
 $import = new ImportCsv($logger, $cronImportCSVConditions);
 
 if (isset($_configuration['default_admin_user_id_for_cron'])) {

+ 4 - 7
main/cron/user_import/client.php

@@ -1,9 +1,6 @@
-<?php //$Id: $
-/*
- * See license terms in /dokeos_license.txt
- * Copyright (c) 2008 Dokeos SPRL
- * Copyright (c) 2008 Eric Marguin <eric.marguin@dokeos.com>
- */
+<?php
+/* See license terms in /license.txt */
+
 /**
  * This is a script used to automatically import a list of users from
  * a CSV file into Dokeos.
@@ -30,4 +27,4 @@ $client = new nusoap_client(api_get_path(WEB_CODE_PATH).'cron/user_import/servic
 
 // call import_user method
 $response = $client->call('import_users', array('filepath'	=> api_get_path(SYS_CODE_PATH)."upload/users_import.csv", 'security_key'=>$_configuration['security_key']));
-echo $response;
+echo $response;

+ 1 - 0
main/css/base.css

@@ -4303,6 +4303,7 @@ a.forum_group_link {
     /*border-bottom: 1px solid #666666;*/
     margin-bottom: 10px;
     vertical-align: top;
+    background:white;
 }
 .forum_message_post_text_2_be_approved {
     /*border-bottom: 1px solid #666666;*/

+ 37 - 14
main/document/document.inc.php

@@ -340,7 +340,11 @@ function create_document_link(
                     preg_match('/jpeg$/i', urldecode($url)) ||
                     preg_match('/bmp$/i', urldecode($url)) ||
                     preg_match('/svg$/i', urldecode($url)) ||
-                    (preg_match('/wav$/i', urldecode($url)) && preg_match('/_chnano_.wav$/i', urldecode($url)) && api_get_setting('enable_nanogong') == 'true')
+                    (
+                        preg_match('/wav$/i', urldecode($url)) &&
+                        preg_match('/_chnano_.wav$/i', urldecode($url)) &&
+                        api_get_setting('enable_nanogong') == 'true'
+                    )
                 ) {
                     $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
                     return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
@@ -760,23 +764,36 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
         if (is_array($folders)) {
             foreach ($folders as & $folder) {
                 // Hide some folders
-                if ($folder == '/HotPotatoes_files' || $folder == '/certificates' || basename($folder) == 'css') {
+                if ($folder == '/HotPotatoes_files' ||
+                    $folder == '/certificates' ||
+                    basename($folder) == 'css'
+                ) {
                     continue;
                 }
-                //Admin setting for Hide/Show the folders of all users
+                // Admin setting for Hide/Show the folders of all users
                 if (api_get_setting('show_users_folders') == 'false' &&
                     (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))
                 ) {
                     continue;
                 }
-                //Admin setting for Hide/Show Default folders to all users
+
+                // Admin setting for Hide/Show Default folders to all users
                 if (api_get_setting('show_default_folders') == 'false' &&
-                    ($folder == '/images' || $folder == '/flash' || $folder == '/audio' || $folder == '/video' || strstr($folder, '/images/gallery') || $folder == '/video/flv')
+                    (
+                        $folder == '/images' ||
+                        $folder == '/flash' ||
+                        $folder == '/audio' ||
+                        $folder == '/video' ||
+                        strstr($folder, '/images/gallery') ||
+                        $folder == '/video/flv'
+                    )
                 ) {
                     continue;
                 }
-                //Admin setting for Hide/Show chat history folder
-                if (api_get_setting('show_chat_folder') == 'false' && $folder == '/chat_files') {
+
+                // Admin setting for Hide/Show chat history folder
+                if (api_get_setting('show_chat_folder') == 'false' &&
+                    $folder == '/chat_files') {
                     continue;
                 }
 
@@ -784,7 +801,10 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
                 // 1. current directory
                 // 2. inside the folder you want to move
                 // 3. inside a subfolder of the folder you want to move
-                if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')) {
+                if (($curdirpath != $folder) &&
+                    ($folder != $move_file) &&
+                    (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')
+                ) {
                     $path_displayed = $folder;
                     // If document title is used, we have to display titles instead of real paths...
                     $path_displayed = get_titles_of_path($folder);
@@ -793,13 +813,15 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
                         $path_displayed = get_lang('Untitled');
                     }
                     $options[$folder] = $path_displayed;
-                    //$form .= '<option value="'.$folder.'">'.$path_displayed.'</option>';
                 }
             }
         }
     } else {
         foreach ($folders as $folder) {
-            if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')) {
+            if (($curdirpath != $folder) &&
+                ($folder != $move_file) &&
+                (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')
+            ) {
                 // Cannot copy dir into his own subdir
                 $path_displayed = get_titles_of_path($folder);
                 $display_folder = substr($path_displayed, strlen($group_dir));
@@ -816,10 +838,11 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
 
 /**
  * Gets the path translated with title of docs and folders
- * @param string the real path
+ * @param string $path the real path
  * @return the path which should be displayed
  */
-function get_titles_of_path($path) {
+function get_titles_of_path($path)
+{
     global $tmp_folders_titles;
     $course_id = api_get_course_int_id();
     $nb_slashes = substr_count($path, '/');
@@ -871,12 +894,12 @@ function display_user_link_document($user_id, $name) {
  * Creates form that asks for the directory name.
  * @return string	html-output text for the form
  */
-function create_dir_form($current_dir_id) {
+function create_dir_form($dirId) {
     global $document_id;
     $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq(), '', null, false);
     $form->addElement('hidden', 'create_dir', 1);
     $form->addElement('hidden', 'dir_id', intval($document_id));
-    $form->addElement('hidden', 'id', intval($current_dir_id));
+    $form->addElement('hidden', 'id', intval($dirId));
     $form->addElement('header', '', get_lang('CreateDir'));
     $form->addElement('text', 'dirname', get_lang('NewDir'), array('autofocus' => 'autofocus'));
     $form->addElement('style_submit_button', 'submit', get_lang('CreateFolder'), 'class="add"');

+ 5 - 2
main/document/slideshow.php

@@ -48,6 +48,7 @@ if (isset($_SESSION['image_files_only'])) {
 }
 
 // Calculating the current slide, next slide, previous slide and the number of slides
+$slide = null;
 if ($slide_id != 'all') {
 	$slide = $slide_id ? $slide_id : 0;
 	$previous_slide = $slide - 1;
@@ -64,9 +65,11 @@ function MM_openBrWindow(theURL,winName,features) { //v2.0
 <?php
 
 if ($slide_id != 'all') {
-	$image = $sys_course_path.$_course['path'].'/document'.$folder.$image_files_only[$slide];
+	$image = null;
+	if (isset($image_files_only[$slide])) {
+		$image = $sys_course_path . $_course['path'] . '/document' . $folder . $image_files_only[$slide];
+	}
 	if (file_exists($image)) {
-
 		echo '<div class="actions-pagination">';
 
 		// Back forward buttons

+ 1 - 0
main/document/upload.php

@@ -208,6 +208,7 @@ Display::display_header($nameTools, 'Doc');
 $unzip = isset($_POST['unzip']) ? $_POST['unzip'] : null;
 $index = isset($_POST['index_document']) ? $_POST['index_document'] : null;
 // User has submitted a file
+
 if (!empty($_FILES)) {
     DocumentManager::upload_document(
         $_FILES,

+ 4 - 2
main/dropbox/index.php

@@ -5,7 +5,7 @@
 require_once 'dropbox_init.inc.php';
 
 // get the last time the user accessed the tool
-if ($_SESSION[$_course['id']]['last_access'][TOOL_DROPBOX] == '') {
+if (isset($_SESSION[$_course['id']]) && $_SESSION[$_course['id']]['last_access'][TOOL_DROPBOX] == '') {
 	$last_access = get_last_tool_access(TOOL_DROPBOX);
 	$_SESSION[$_course['id']]['last_access'][TOOL_DROPBOX] = $last_access;
 } else {
@@ -181,9 +181,11 @@ if (isset($_GET['error']) AND !empty($_GET['error'])) {
 	Display :: display_normal_message(get_lang($_GET['error']));
 }
 
+$dropbox_data_sent = array();
+$movelist = array();
+$dropbox_data_recieved = array();
 
 if ($action != 'add') {
-
 	// Getting all the categories in the dropbox for the given user
 	$dropbox_categories = get_dropbox_categories();
 	// Greating the arrays with the categories for the received files and for the sent files

+ 76 - 29
main/exercice/exercice.php

@@ -49,6 +49,12 @@ $is_tutor = api_is_allowed_to_edit(true);
 $is_tutor_course = api_is_course_tutor();
 $courseInfo = api_get_course_info();
 $courseId = api_get_course_int_id();
+$userId = api_get_user_id();
+$userInfo = api_get_user_info();
+$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+    $userId,
+    $courseInfo
+);
 
 $TBL_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
 $TBL_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
@@ -174,7 +180,7 @@ if (!empty($errorXmlExport)) {
     echo $errorXmlExport;
 }
 
-HotPotGCt($documentPath, 1, api_get_user_id());
+HotPotGCt($documentPath, 1, $userId);
 
 // Only for administrator
 
@@ -240,7 +246,7 @@ if ($is_allowedToEdit) {
                         // enables an exercise
                         $objExerciseTmp->enable();
                         $objExerciseTmp->save();
-                        api_item_property_update($courseInfo, TOOL_QUIZ, $objExerciseTmp->id, 'visible', api_get_user_id());
+                        api_item_property_update($courseInfo, TOOL_QUIZ, $objExerciseTmp->id, 'visible', $userId);
                         // "WHAT'S NEW" notification: update table item_property (previously last_tooledit)
                         Display :: display_confirmation_message(get_lang('VisibilityChanged'));
                         break;
@@ -248,7 +254,7 @@ if ($is_allowedToEdit) {
                         // disables an exercise
                         $objExerciseTmp->disable();
                         $objExerciseTmp->save();
-                        api_item_property_update($courseInfo, TOOL_QUIZ, $objExerciseTmp->id, 'invisible', api_get_user_id());
+                        api_item_property_update($courseInfo, TOOL_QUIZ, $objExerciseTmp->id, 'invisible', $userId);
                         Display :: display_confirmation_message(get_lang('VisibilityChanged'));
                         break;
                     case 'disable_results' :
@@ -325,7 +331,7 @@ if ($is_allowedToEdit) {
                     TOOL_DOCUMENT,
                     $row['id'],
                     'visible',
-                    api_get_user_id()
+                    $userId
                 );
                 //$dialogBox = get_lang('ViMod');
 
@@ -341,7 +347,7 @@ if ($is_allowedToEdit) {
                     TOOL_DOCUMENT,
                     $row['id'],
                     'invisible',
-                    api_get_user_id()
+                    $userId
                 );
                 break;
             default :
@@ -361,7 +367,7 @@ $limit = 50;
 
 // Display the next and previous link if needed
 $from = $page * $limit;
-HotPotGCt($documentPath, 1, api_get_user_id());
+HotPotGCt($documentPath, 1, $userId);
 
 //condition for the session
 $course_code = api_get_course_id();
@@ -399,7 +405,9 @@ if (Database :: num_rows($result_total)) {
 //get HotPotatoes files (active and inactive)
 if ($is_allowedToEdit) {
     $sql = "SELECT * FROM $TBL_DOCUMENT
-            WHERE c_id = $courseId AND path LIKE '".Database :: escape_string($uploadPath)."/%/%'";
+            WHERE
+                c_id = $courseId AND
+                path LIKE '".Database :: escape_string($uploadPath.'/%/%')."'";
     $res = Database::query($sql);
     $hp_count = Database :: num_rows($res);
 } else {
@@ -407,7 +415,7 @@ if ($is_allowedToEdit) {
             WHERE
                 d.id = ip.ref AND
                 ip.tool = '".TOOL_DOCUMENT."' AND
-                d.path LIKE '".Database :: escape_string($uploadPath)."/%/%' AND
+                d.path LIKE '".Database :: escape_string($uploadPath.'/%/%')."' AND
                 ip.visibility ='1' AND
                 d.c_id      = ".$courseId." AND
                 ip.c_id     = ".$courseId;
@@ -496,7 +504,6 @@ if (isset($list_ordered) && !empty($list_ordered)) {
 }
 
 echo '<table class="'.Display::return_default_table_class().'">';
-$_user = api_get_user_info();
 
 /*  Listing exercises  */
 if (!empty($exercise_list)) {
@@ -511,13 +518,21 @@ if (!empty($exercise_list)) {
         $i = 1;
 
         if ($is_allowedToEdit) {
-            $headers = array(array('name' => get_lang('ExerciseName')),
+            $headers = array(
+                array('name' => get_lang('ExerciseName')),
                 array('name' => get_lang('QuantityQuestions'), 'params' => array('width' => '100px')),
                 array('name' => get_lang('Actions'), 'params' => array('width' => '180px')));
         } else {
-            $headers = array(array('name' => get_lang('ExerciseName')),
+            $headers = array(
+                array('name' => get_lang('ExerciseName')),
                 array('name' => get_lang('Status')),
             );
+            if ($isDrhOfCourse) {
+                $headers[] = array(
+                    'name' => get_lang('Actions'),
+                    'params' => array('width' => '180px')
+                );
+            }
         }
 
         $header_list = '';
@@ -541,7 +556,7 @@ if (!empty($exercise_list)) {
             $locked = $exercise_obj->is_gradebook_locked;
             $i++;
             //validacion when belongs to a session
-            $session_img = api_get_session_image($row['session_id'], $_user['status']);
+            $session_img = api_get_session_image($row['session_id'], $userInfo['status']);
 
             $time_limits = false;
             if ($row['start_time'] != '0000-00-00 00:00:00' || $row['end_time'] != '0000-00-00 00:00:00') {
@@ -693,14 +708,17 @@ if (!empty($exercise_list)) {
                 } else {
                     // not session
                     $actions = Display::return_icon('edit_na.png', get_lang('ExerciseEditionNotAvailableInSession'));
-                    $actions .='<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
+                    $actions .='<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
+                        Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
                     $actions .= Display::url(Display::return_icon('cd.gif', get_lang('CopyExercise')), '', array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;", 'href' => 'exercice.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id']));
                 }
 
                 // Delete
                 if ($session_id == $row['session_id']) {
                     if ($locked == false) {
-                        $actions .= Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL), '', array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDelete'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;", 'href' => 'exercice.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&exerciseId='.$row['id']));
+                        $actions .= Display::url(
+                            Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL), '',
+                            array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDelete'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;", 'href' => 'exercice.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&exerciseId='.$row['id']));
                     } else {
                         $actions .= Display::return_icon('delete_na.png', get_lang('ResourceLockedByGradebook'), '', ICON_SIZE_SMALL);
                     }
@@ -715,7 +733,10 @@ if (!empty($exercise_list)) {
                         $random_number_of_question = $rowi;
                     }
                     if ($row['random_by_category'] > 0) {
-                        $nbQuestionsTotal = Testcategory::getNumberOfQuestionRandomByCategory($my_exercise_id, $random_number_of_question);
+                        $nbQuestionsTotal = Testcategory::getNumberOfQuestionRandomByCategory(
+                            $my_exercise_id,
+                            $random_number_of_question
+                        );
                         $number_of_questions = $nbQuestionsTotal." ";
                         $number_of_questions .= ($nbQuestionsTotal > 1) ? get_lang("QuestionsLowerCase") : get_lang("QuestionLowerCase");
                         $number_of_questions .= " - ";
@@ -768,7 +789,7 @@ if (!empty($exercise_list)) {
                 $sql = "SELECT * FROM $TBL_TRACK_EXERCICES
                         WHERE
                             exe_exo_id      = ".$row['id']." AND
-                            exe_user_id     = ".api_get_user_id()." AND
+                            exe_user_id     = ".$userId." AND
                             exe_cours_id    = '".api_get_course_id()."' AND
                             status          <> 'incomplete' AND
                             orig_lp_id      = 0 AND
@@ -858,6 +879,7 @@ if (!empty($exercise_list)) {
 
                 $item .= Display::tag('td', $attempt_text);
             }
+
             $class = 'row_even';
             if ($count % 2) {
                 $class = 'row_odd';
@@ -865,6 +887,12 @@ if (!empty($exercise_list)) {
 
             if ($is_allowedToEdit) {
                 $item .= Display::tag('td', $actions, array('class' => 'td_actions'));
+            } else {
+                if ($isDrhOfCourse) {
+                    $actions ='<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
+                        Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
+                    $item .= Display::tag('td', $actions, array('class' => 'td_actions'));
+                }
             }
 
             echo Display::tag(
@@ -894,7 +922,7 @@ if ($is_allowedToEdit) {
                 d.id = ip.ref AND
                 ip.tool = '".TOOL_DOCUMENT."' AND
                 (d.path LIKE '%htm%') AND
-                d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%'
+                d.path  LIKE '".Database :: escape_string($uploadPath.'/%/%')."'
             LIMIT ".$from.",".$limit; // only .htm or .html files listed
 } else {
     $sql = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility
@@ -905,7 +933,7 @@ if ($is_allowedToEdit) {
                 d.id = ip.ref AND
                 ip.tool = '".TOOL_DOCUMENT."' AND
                 (d.path LIKE '%htm%') AND
-                d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%' AND
+                d.path  LIKE '".Database :: escape_string($uploadPath.'/%/%')."' AND
                 ip.visibility='1'
             LIMIT ".$from.",".$limit;
 }
@@ -941,38 +969,45 @@ if (isset($attribute['path']) && is_array($attribute['path'])) {
 
         // prof only
         if ($is_allowedToEdit) {
-            $item = Display::tag('td', '<img src="../img/hotpotatoes_s.png" alt="HotPotatoes" /> <a href="showinframes.php?file='.$path.'&cid='.api_get_course_id().'&uid='.api_get_user_id().'" '.(!$active ? 'class="invisible"' : '').' >'.$title.'</a> ');
+            $item = Display::tag('td', '<img src="../img/hotpotatoes_s.png" alt="HotPotatoes" /> <a href="showinframes.php?file='.$path.'&cid='.api_get_course_id().'&uid='.$userId.'" '.(!$active ? 'class="invisible"' : '').' >'.$title.'</a> ');
             $item .= Display::tag('td', '-');
 
-            $actions = Display::url(Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL), 'adminhp.php?'.api_get_cidreq().'&hotpotatoesName='.$path);
-            $actions .='<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
+            $actions = Display::url(
+                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL),
+                'adminhp.php?'.api_get_cidreq().'&hotpotatoesName='.$path
+            );
+
+            $actions .='<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.
+                Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
 
             // if active
             if ($active) {
                 $nbrActiveTests = $nbrActiveTests + 1;
-                $actions .= '      <a href="'.$exercicePath.'?'.api_get_cidreq().'&hpchoice=disable&amp;page='.$page.'&amp;file='.$path.'">'.Display::return_icon('visible.png', get_lang('Deactivate'), '', ICON_SIZE_SMALL).'</a>';
+                $actions .= '      <a href="'.$exercicePath.'?'.api_get_cidreq().'&hpchoice=disable&amp;page='.$page.'&amp;file='.$path.'">'.
+                    Display::return_icon('visible.png', get_lang('Deactivate'), '', ICON_SIZE_SMALL).'</a>';
             } else { // else if not active
-                $actions .='    <a href="'.$exercicePath.'?'.api_get_cidreq().'&hpchoice=enable&amp;page='.$page.'&amp;file='.$path.'">'.Display::return_icon('invisible.png', get_lang('Activate'), '', ICON_SIZE_SMALL).'</a>';
+                $actions .='    <a href="'.$exercicePath.'?'.api_get_cidreq().'&hpchoice=enable&amp;page='.$page.'&amp;file='.$path.'">'.
+                    Display::return_icon('invisible.png', get_lang('Activate'), '', ICON_SIZE_SMALL).'</a>';
             }
-            $actions .= '<a href="'.$exercicePath.'?'.api_get_cidreq().'&amp;hpchoice=delete&amp;file='.$path.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('AreYouSureToDelete'), ENT_QUOTES, $charset).' '.$title."?").'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
+            $actions .= '<a href="'.$exercicePath.'?'.api_get_cidreq().'&amp;hpchoice=delete&amp;file='.$path.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('AreYouSureToDelete'), ENT_QUOTES, $charset).' '.$title."?").'\')) return false;">'.
+                Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
             $item .= Display::tag('td', $actions);
             echo Display::tag('tr', $item, array('class' => $class));
         } else {
             // Student only
             if ($active == 1) {
-
                 $attempt = getLatestHotPotatoResult(
                     $path,
-                    api_get_user_id(),
+                    $userId,
                     api_get_course_int_id(),
                     api_get_session_id()
                 );
 
                 $nbrActiveTests = $nbrActiveTests + 1;
-                $item .= Display::tag('td', '<a href="showinframes.php?'.api_get_cidreq().'&file='.$path.'&cid='.api_get_course_id().'&uid='.api_get_user_id().'" '.(!$active ? 'class="invisible"' : '').' >'.$title.'</a>');
+                $item .= Display::tag('td', '<a href="showinframes.php?'.api_get_cidreq().'&file='.$path.'&cid='.api_get_course_id().'&uid='.$userId.'" '.(!$active ? 'class="invisible"' : '').' >'.$title.'</a>');
 
                 if (!empty($attempt)) {
-                    $actions = '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'&filter_by_user='.api_get_user_id().'">'.Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
+                    $actions = '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'&filter_by_user='.$userId.'">'.Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
                     $attemptText = get_lang('LatestAttempt').' : ';
                     $attemptText .= show_score($attempt['exe_result'], $attempt['exe_weighting']).' ';
                     $attemptText .= $actions;
@@ -982,7 +1017,19 @@ if (isset($attribute['path']) && is_array($attribute['path'])) {
                 }
 
                 $item .= Display::tag('td', $attemptText);
-                echo Display::tag('tr', $item, array('class' => $class));
+
+                if ($isDrhOfCourse) {
+                    $actions ='<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.
+                        Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
+
+                    $item .= Display::tag('td', $actions, array('class' => 'td_actions'));
+                }
+
+                echo Display::tag(
+                    'tr',
+                    $item,
+                    array('class' => $class)
+                );
             }
         }
         $count++;

File diff suppressed because it is too large
+ 361 - 330
main/exercice/exercise.lib.php


+ 2 - 2
main/exercice/hotspot_savescore.inc.php

@@ -1,5 +1,5 @@
-<?php //$id:$
-/* For licensing terms, see /dokeos_license.txt */
+<?php
+/* For licensing terms, see /license.txt */
 /**
 *	This file saves every click in the hotspot tool into track_e_hotspots
 *	@package chamilo.exercise

+ 3 - 6
main/exercice/hotspot_updatescore.inc.php

@@ -1,20 +1,17 @@
-<?php //$id:$
-/* For licensing terms, see /dokeos_license.txt */
+<?php
+/* For licensing terms, see /license.txt */
+
 /**
 *	This file saves every click in the hotspot tool into track_e_hotspots
 *	@package chamilo.exercise
 * 	@author Toon Keppens
 * 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
 */
-/**
- * Code
- */
 include 'exercise.class.php';
 include 'question.class.php';
 include 'answer.class.php';
 include '../inc/global.inc.php';
 
-
 $courseCode   = $_GET['coursecode'];
 $questionId   = $_GET['questionId'];
 $coordinates  = $_GET['coord'];

+ 22 - 12
main/exercice/savescores.php

@@ -6,9 +6,7 @@
  * 	@author
  * 	@version $Id: savescores.php 15602 2008-06-18 08:52:24Z pcool $
  */
-/**
- * Code
- */
+
 // name of the language file that needs to be included
 $language_file = 'learnpath';
 
@@ -22,9 +20,12 @@ if (isset($_GET['origin']) && $_GET['origin'] == 'learnpath') {
 }
 
 require_once '../inc/global.inc.php';
+$courseInfo = api_get_course_info();
+$_user = api_get_user_info();
+
 $this_section = SECTION_COURSES;
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-$documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
+$documentPath = api_get_path(SYS_COURSE_PATH).$courseInfo['path']."/document";
 
 $test = $_REQUEST['test'];
 $full_file_path = $documentPath.$test;
@@ -34,13 +35,12 @@ my_delete($full_file_path.$_user['user_id'].".t.html");
 $TABLETRACK_HOTPOTATOES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
 $TABLE_LP_ITEM_VIEW = Database::get_course_table(TABLE_LP_ITEM_VIEW);
 
-$_cid = api_get_course_id();
-
 $score = $_REQUEST['score'];
 $origin = $_REQUEST['origin'];
 $learnpath_item_id = intval($_REQUEST['learnpath_item_id']);
-$course_info = api_get_course_info();
-$course_id = $course_info['real_id'];
+$lpViewId = isset($_REQUEST['lp_view_id']) ? intval($_REQUEST['lp_view_id']) : null;
+$course_id = $courseInfo['real_id'];
+$_cid = api_get_course_id();
 $jscript2run = '';
 
 /**
@@ -103,9 +103,19 @@ if ($origin != 'learnpath') {
 } else {
     $htmlHeadXtra[] = $jscript2run;
     Display::display_reduced_header();
-    $update_sql = "UPDATE $TABLE_LP_ITEM_VIEW SET status = 'completed'
-                   WHERE c_id = $course_id AND lp_item_id= $learnpath_item_id";
-    Database::query($update_sql);
-    Display::display_confirmation_message(get_lang('HotPotatoesFinished'));
+    if (!empty($course_id) && !empty($learnpath_item_id) && !empty($lpViewId)) {
+        $sql = "UPDATE $TABLE_LP_ITEM_VIEW SET
+                    status = 'completed'
+                WHERE
+                    c_id = $course_id AND
+                    lp_item_id= $learnpath_item_id AND
+                    lp_view_id = $lpViewId
+                ";
+        Database::query($sql);
+        Display::display_confirmation_message(get_lang('HotPotatoesFinished'));
+    } else {
+        Display::display_error_message(get_lang('Error'));
+    }
+
     Display::display_footer();
 }

+ 10 - 8
main/exercice/showinframes.php

@@ -8,16 +8,18 @@
 require_once '../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php';
+$_course = api_get_course_info();
 
 $time = time();
 $doc_url = str_replace(array('../', '\\', '\\0', '..'), array('', '', '', ''), urldecode($_GET['file']));
 $cid = api_get_course_id();
-$document_path      = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-$document_web_path  = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document';
-$origin             = isset($_REQUEST['origin']) ? $_REQUEST['origin'] : null;
-$learnpath_id       = isset($_REQUEST['learnpath_id']) ? $_REQUEST['learnpath_id'] : null;
-$learnpath_item_id  = isset($_REQUEST['learnpath_item_id']) ? $_REQUEST['learnpath_item_id'] : null;
-$time               = isset($_REQUEST['time']) ? $_REQUEST['time'] : null;
+$document_path = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document';
+$document_web_path = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/document';
+$origin = isset($_REQUEST['origin']) ? $_REQUEST['origin'] : null;
+$learnpath_id = isset($_REQUEST['learnpath_id']) ? $_REQUEST['learnpath_id'] : null;
+$learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? $_REQUEST['learnpath_item_id'] : null;
+$time = isset($_REQUEST['time']) ? $_REQUEST['time'] : null;
+$lpViewId = isset($_REQUEST['lp_view_id']) ? $_REQUEST['lp_view_id'] : null;
 
 $user_id = api_get_user_id();
 $full_file_path = $document_path.$doc_url;
@@ -35,10 +37,10 @@ if ($content == '') {
         if (SaveScoreVariable==0) {
             SaveScoreVariable = 1;
             if (C.ie) {
-                document.location.href = '".api_get_path(WEB_PATH)."main/exercice/savescores.php?origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS($time)."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
+                document.location.href = '".api_get_path(WEB_PATH)."main/exercice/savescores.php?lp_view_id=$lpViewId&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS($time)."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
                 //window.alert(Score);
             } else {
-                window.location.href = '".api_get_path(WEB_PATH)."main/exercice/savescores.php?origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS($time)."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
+                window.location.href = '".api_get_path(WEB_PATH)."main/exercice/savescores.php?lp_view_id=$lpViewId&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS($time)."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
             }
         }
     }

+ 7 - 3
main/forum/editpost.php

@@ -70,8 +70,8 @@ $htmlHeadXtra[] = '<script>
 // We are getting all the information about the current forum and forum category.
 // Note pcool: I tried to use only one sql statement (and function) for this,
 // but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table.
-$current_thread = get_thread_information($_GET['thread']); // Note: This has to be validated that it is an existing thread.
-$current_forum = get_forum_information($_GET['forum']); // Note: This has to be validated that it is an existing forum.
+$current_thread = get_thread_information($_GET['thread']);
+$current_forum = get_forum_information($_GET['forum']);
 $current_forum_category = get_forumcategory_information($current_forum['forum_category']);
 $current_post = get_post_information($_GET['post']);
 
@@ -201,7 +201,11 @@ echo '</div></div></div>';
 /* End new display forum */
 
 // Set forum attachment data into $_SESSION
-getAttachedFiles($current_forum['forum_id'], $current_thread['thread_id'], $current_post['post_id']);
+getAttachedFiles(
+    $current_forum['forum_id'],
+    $current_thread['thread_id'],
+    $current_post['post_id']
+);
 // The form for the reply
 echo '<div class="row">';
 echo '<div class="span12">';

+ 118 - 87
main/forum/forumfunction.inc.php

@@ -44,7 +44,7 @@ $(document).ready(function () {
 $htmlHeadXtra[] = '<script>
 
 function check_unzip() {
-    if(document.upload.unzip.checked){
+    if (document.upload.unzip.checked){
         document.upload.if_exists[0].disabled=true;
         document.upload.if_exists[1].checked=true;
         document.upload.if_exists[2].disabled=true;
@@ -85,46 +85,47 @@ $(function () {
             }
         }
     });
-    enableDeleteFile();
 });
 </script>";
+
 // Recover Thread ID, will be used to generate delete attachment URL to do ajax
 $threadId = isset($_REQUEST['thread']) ? intval($_REQUEST['thread']) : 0;
+$forumId = isset($_REQUEST['forum']) ? intval($_REQUEST['forum']) : 0;
+
 // The next javascript script is to delete file by ajax
-$htmlHeadXtra[] =
-    '<script>
-        function enableDeleteFile() {
-            $(document).on("click", ".deleteLink", function(e) {
-                e.preventDefault();
-                e.stopPropagation();
-                var l = $(this);
-                var id = l.closest("tr").attr("id");
-                var filename = l.closest("tr").find(".attachFilename").html();
-                if (confirm("' . get_lang('AreYouSureToDeleteFileX') . '".replace("%s", filename))) {
-                    $.ajax({
-                        type: "POST",
-                        url: "' . api_get_path(WEB_AJAX_PATH) . 'forum.ajax.php?a=delete_file&attachId=" + id +"&thread=" + ' .
-                            $threadId . ',
-                        dataType: "json",
-                        success: function(data) {
-                                if (data.error == false) {
-                                    l.closest("tr").remove();
-                                    if ($(".files td").length < 1) {
-                                        $(".files").closest(".control-group").hide();
-                                    }
-                                }
+$htmlHeadXtra[] = '<script>
+    $(function () {
+        $(document).on("click", ".deleteLink", function(e) {
+            e.preventDefault();
+            e.stopPropagation();
+            var l = $(this);
+            var id = l.closest("tr").attr("id");
+            var filename = l.closest("tr").find(".attachFilename").html();
+            if (confirm("' . get_lang('AreYouSureToDeleteFileX') . '".replace("%s", filename))) {
+                $.ajax({
+                    type: "POST",
+                    url: "'.api_get_path(WEB_AJAX_PATH) . 'forum.ajax.php?'.api_get_cidreq().'&a=delete_file&attachId=" + id +"&thread='.$threadId .'&forum='.$forumId .'",
+                    dataType: "json",
+                    success: function(data) {
+                        if (data.error == false) {
+                            l.closest("tr").remove();
+                            if ($(".files td").length < 1) {
+                                $(".files").closest(".control-group").hide();
                             }
-                    })
-                }
-            });
-        }
-    </script>';
+                        }
+                    }
+                })
+            }
+        });
+    });
+</script>';
 
 /**
- * This function handles all the forum and forumcategories actions. This is a wrapper for the
+ * This function handles all the forum and forum categories actions. This is a wrapper for the
  * forum and forum categories. All this code code could go into the section where this function is
  * called but this make the code there cleaner.
- * @param int $lp_id Learning path ID
+ * @param int $lp_id Learning path Id
+ *
  * @return void
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @author Juan Carlos Raña Trabado (return to lp_id)
@@ -181,6 +182,7 @@ function handle_forum_and_forumcategories($lp_id = null)
         $return_message = delete_forum_forumcategory_thread($get_content, $get_id);
         Display::display_confirmation_message($return_message, false);
     }
+
     // Change visibility of a forum or a forum category.
     if ($action_forum_cat == 'invisible' || $action_forum_cat == 'visible') {
         $return_message = change_visibility($get_content, $get_id, $action_forum_cat);
@@ -220,8 +222,6 @@ function show_add_forumcategory_form($inputvalues = array(), $lp_id)
     // Setting the form elements.
     $form->addElement('header', '', get_lang('AddForumCategory'));
     $form->addElement('text', 'forum_category_title', get_lang('Title'), 'class="input_titles" id="category_title"');
-
-    //$form->applyFilter('forum_category_title', 'html_filter');
     $form->addElement('html_editor', 'forum_category_comment', get_lang('Description'), null, array('ToolbarSet' => 'Forum', 'Width' => '98%', 'Height' => '200'));
 
     //$form->applyFilter('forum_category_comment', 'html_filter');
@@ -441,9 +441,10 @@ function delete_forum_image($forum_id)
 {
     $table_forums = Database::get_course_table(TABLE_FORUM);
     $course_id = api_get_course_int_id();
+    $forum_id = intval($forum_id);
 
-    $forum_id = Database::escape_string($forum_id);
-    $sql = "SELECT forum_image FROM $table_forums WHERE forum_id = '".$forum_id."' AND c_id = $course_id";
+    $sql = "SELECT forum_image FROM $table_forums
+            WHERE forum_id = '".$forum_id."' AND c_id = $course_id";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
     if ($row['forum_image'] != '') {
@@ -527,7 +528,7 @@ function store_forumcategory($values)
     $table_categories = Database::get_course_table(TABLE_FORUM_CATEGORY);
 
     // Find the max cat_order. The new forum category is added at the end => max cat_order + &
-    $sql = "SELECT MAX(cat_order) as sort_max FROM ".Database::escape_string($table_categories)."
+    $sql = "SELECT MAX(cat_order) as sort_max FROM ".$table_categories."
             WHERE c_id = $course_id";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
@@ -1023,9 +1024,9 @@ function display_up_down_icon($content, $id, $list)
 /**
  * This function changes the visibility in the database (item_property)
  *
- * @param $content what is it that we want to make (in)visible: forum category, forum, thread, post
- * @param $id the id of the content we want to make invisible
- * @param $target_visibility what is the current status of the visibility (0 = invisible, 1 = visible)
+ * @param string $content what is it that we want to make (in)visible: forum category, forum, thread, post
+ * @param int $id the id of the content we want to make invisible
+ * @param string $target_visibility what is the current status of the visibility (0 = invisible, 1 = visible)
  *
  * @todo change the get parameter so that it matches the tool constants.
  * @todo check if api_item_property_update returns true or false => returnmessage depends on it.
@@ -1134,6 +1135,7 @@ function move_up_down($content, $direction, $id)
     $table_forums = Database :: get_course_table(TABLE_FORUM);
     $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
     $course_id = api_get_course_int_id();
+    $id = intval($id);
 
     // Determine which field holds the sort order.
     if ($content == 'forumcategory') {
@@ -1253,7 +1255,7 @@ function get_forum_categories($id = '')
     $session_id = api_get_session_id();
     $course_id = api_get_course_int_id();
 
-    $condition_session = api_get_session_condition($session_id, true, false);
+    $condition_session = api_get_session_condition($session_id, true, true);
     $condition_session .= " AND forum_categories.c_id = $course_id AND item_properties.c_id = $course_id";
 
     if (empty($id)) {
@@ -1349,9 +1351,11 @@ function get_forums_in_category($cat_id)
  * The forums are sorted according to the forum_order.
  * Since it does not take the forum category into account there probably
  * will be two or more forums that have forum_order=1, ...
- * @param int forum id
- * @param string course db name
- * @return an array containing all the information about the forums (regardless of their category)
+ * @param int $id forum id
+ * @param string $course_code
+ * @param bool $includeGroupsForum
+ * @param int $sessionId
+ * @return array an array containing all the information about the forums (regardless of their category)
  * @todo check $sql4 because this one really looks fishy.
  *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
@@ -1380,7 +1384,7 @@ function get_forums(
         $session_id = $sessionId;
     }
 
-    $condition_session = api_get_session_condition($session_id, true, false);
+    $condition_session = api_get_session_condition($session_id, true, false, 'id_session');
     $course_id = $course_info['real_id'];
 
     $forum_list = array();
@@ -1392,9 +1396,13 @@ function get_forums(
     if ($id == '') {
         // Student
         // Select all the forum information of all forums (that are visible to students).
-        $sql = "SELECT * FROM $table_forums forum, ".$table_item_property." item_properties
-                WHERE
+        $sql = "SELECT * FROM $table_forums forum
+                INNER JOIN ".$table_item_property." item_properties
+                ON (
                     forum.forum_id=item_properties.ref AND
+                    forum.c_id = item_properties.c_id
+                )
+                WHERE
                     item_properties.visibility=1 AND
                     item_properties.tool='".TOOL_FORUM."'
                     $condition_session AND
@@ -1405,9 +1413,14 @@ function get_forums(
 
         // Select the number of threads of the forums (only the threads that are visible).
         $sql2 = "SELECT count(*) AS number_of_threads, threads.forum_id
-                FROM $table_threads threads, ".$table_item_property." item_properties
-                WHERE
+                FROM $table_threads threads
+                INNER JOIN ".$table_item_property." item_properties
+                ON (
                     threads.thread_id=item_properties.ref AND
+                    threads.c_id = item_properties.c_id AND
+                    threads.session_id = item_properties.id_session
+                )
+                WHERE
                     item_properties.visibility=1 AND
                     item_properties.tool='".TOOL_FORUM_THREAD."' AND
                     threads.c_id = $course_id AND
@@ -1421,6 +1434,7 @@ function get_forums(
                     posts.visible=1 AND
                     posts.thread_id=threads.thread_id AND
                     threads.thread_id=item_properties.ref AND
+                    threads.session_id = item_properties.id_session AND
                     item_properties.visibility=1 AND
                     item_properties.tool='".TOOL_FORUM_THREAD."' AND
                     threads.c_id = $course_id AND
@@ -1431,10 +1445,14 @@ function get_forums(
         // Course Admin
         if (is_allowed_to_edit()) {
             // Select all the forum information of all forums (that are not deleted).
-            $sql = "SELECT * FROM ".$table_forums." forum , ".$table_item_property." item_properties
-                    WHERE
+            $sql = "SELECT * FROM ".$table_forums." forum
+                    INNER JOIN ".$table_item_property." item_properties
+                    ON (
                         forum.forum_id = item_properties.ref AND
-                        item_properties.visibility<>2 AND
+                        forum.c_id = item_properties.c_id
+                    )
+                    WHERE
+                        item_properties.visibility <> 2 AND
                         item_properties.tool='".TOOL_FORUM."'
                         $condition_session AND
                         forum.c_id = $course_id AND
@@ -1444,11 +1462,16 @@ function get_forums(
 
             // Select the number of threads of the forums (only the threads that are not deleted).
             $sql2 = "SELECT count(*) AS number_of_threads, threads.forum_id
-                    FROM $table_threads threads, ".$table_item_property." item_properties
+                    FROM $table_threads threads
+                    INNER JOIN ".$table_item_property." item_properties
+                    ON (
+                        threads.thread_id=item_properties.ref AND
+                        threads.c_id = item_properties.c_id AND
+                        threads.session_id = item_properties.id_session
+                    )
                     WHERE
-                        threads.thread_id=item_properties.ref
-                        AND item_properties.visibility<>2
-                        AND item_properties.tool='".TOOL_FORUM_THREAD."' AND
+                        item_properties.visibility<>2 AND
+                        item_properties.tool='".TOOL_FORUM_THREAD."' AND
                         threads.c_id = $course_id AND
                         item_properties.c_id = $course_id
                     GROUP BY threads.forum_id";
@@ -1458,6 +1481,7 @@ function get_forums(
                     WHERE
                         posts.thread_id=threads.thread_id AND
                         threads.thread_id=item_properties.ref AND
+                        threads.session_id = item_properties.id_session AND
                         item_properties.visibility=1 AND
                         item_properties.tool='".TOOL_FORUM_THREAD."' AND
                         posts.c_id = $course_id AND
@@ -1718,10 +1742,11 @@ function get_threads($forum_id, $course_code = null)
                 thread.locked as locked
             FROM $table_threads thread
             INNER JOIN $table_item_property item_properties
-                ON  thread.thread_id=item_properties.ref AND
-                    item_properties.c_id = $course_id AND
-                    thread.c_id = $course_id AND
-                    item_properties.tool='".TABLE_FORUM_THREAD."'$groupCondition
+            ON
+                thread.thread_id=item_properties.ref AND
+                item_properties.c_id = $course_id AND
+                thread.c_id = $course_id AND
+                item_properties.tool='".TABLE_FORUM_THREAD."'$groupCondition
             LEFT JOIN $table_users users
                 ON thread.thread_poster_id=users.user_id
             WHERE
@@ -1745,10 +1770,10 @@ function get_threads($forum_id, $course_code = null)
                 FROM $table_threads thread
                 INNER JOIN $table_item_property item_properties
                 ON
-                    thread.thread_id=item_properties.ref AND
+                    thread.thread_id = item_properties.ref AND
                     item_properties.c_id = $course_id AND
                     thread.c_id = $course_id AND
-                    item_properties.tool='".TABLE_FORUM_THREAD."'$groupCondition
+                    item_properties.tool = '".TABLE_FORUM_THREAD."' $groupCondition
                 LEFT JOIN $table_users users
                     ON thread.thread_poster_id=users.user_id
                 WHERE
@@ -2280,9 +2305,6 @@ function store_thread($current_forum, $values)
         $message = get_lang('NewThreadStored');
         // Storing the attachments if any.
         if ($has_attachment) {
-            $course_dir = $_course['path'].'/upload/forum';
-            $sys_course_path = api_get_path(SYS_COURSE_PATH);
-            $updir = $sys_course_path.$course_dir;
 
             // Try to add an extension to the file if it hasn't one.
             $new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
@@ -2386,14 +2408,13 @@ function show_add_post_form($current_forum, $forum_setting, $action = '', $id =
 
     $form->addElement('text', 'post_title', get_lang('Title'));
 
-    $form->addElement('html_editor', 'post_text', get_lang('Text'), true, api_is_allowed_to_edit(null, true) ? array('ToolbarSet' => 'Forum', 'Width' => '100%', 'Height' => '300') : array('ToolbarSet' => 'ForumStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student')
-    );
+    $form->addElement('html_editor', 'post_text', get_lang('Text'), true, api_is_allowed_to_edit(null, true) ? array('ToolbarSet' => 'Forum', 'Width' => '100%', 'Height' => '300') : array('ToolbarSet' => 'ForumStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student'));
 
     $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required');
     $iframe = null;
     $myThread = Security::remove_XSS($myThread);
     if ($forum_setting['show_thread_iframe_on_reply'] && $action != 'newthread' && !empty($myThread)) {
-        $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?forum=".Security::remove_XSS($my_forum)."&amp;thread=".$myThread."#".Security::remove_XSS($my_post)."\" width=\"100%\"></iframe>";
+        $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?".api_get_cidreq()."&amp;forum=".Security::remove_XSS($my_forum)."&amp;thread=".$myThread."#".Security::remove_XSS($my_post)."\" width=\"100%\"></iframe>";
     }
     if (!empty($iframe)) {
         $form->addElement('label', get_lang('Thread'), $iframe);
@@ -2709,7 +2730,6 @@ function current_qualify_of_thread($thread_id, $session_id)
 function store_reply($current_forum, $values)
 {
     $_course = api_get_course_info();
-    $forum_table_attachment = Database :: get_course_table(TABLE_FORUM_ATTACHMENT);
     $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
 
     $post_date = api_get_utc_datetime();
@@ -4820,29 +4840,31 @@ function editAttachedFile($array, $id, $courseId = null) {
 
 /**
  * Return a form to upload asynchronously attachments to forum post.
- * @param $forumId Forum ID from where the post are
- * @param $threadId Thread ID where forum post are
- * @param $postId Post ID to identify Post
+ * @param int $forumId Forum ID from where the post are
+ * @param int $threadId Thread ID where forum post are
+ * @param int $postId Post ID to identify Post
  * @return string The Forum Attachment Ajax Form
  */
 function getAttachmentAjaxForm($forumId, $threadId, $postId)
 {
-    // Init variables
     $forumId = intval($forumId);
     $postId = intval($postId);
     $threadId = !empty($threadId) ? intval($threadId) : isset($_REQUEST['thread']) ? intval($_REQUEST['thread']) : '';
     if ($forumId === 0) {
-        // Forum ID must be defined
+        // Forum Id must be defined
 
         return '';
     }
-    $url = api_get_path(WEB_AJAX_PATH).'forum.ajax.php?forum=' . $forumId . '&thread=' . $threadId . '&postId=' . $postId . '&a=upload_file';
+
+    $url = api_get_path(WEB_AJAX_PATH).'forum.ajax.php?'.api_get_cidreq().'&forum=' . $forumId . '&thread=' . $threadId . '&postId=' . $postId . '&a=upload_file';
     // Form
     $formFileUpload = '<div class="form-ajax">
         <form id="file_upload" action="'.$url.'" method="POST" enctype="multipart/form-data">
             <input type="file" name="user_upload" multiple>
-            <button type="submit">Upload</button><div class="button-load">
-            '.get_lang('UploadFiles').'</div>
+            <button type="submit">Upload</button>
+            <div class="button-load">
+                '.get_lang('UploadFiles').'
+            </div>
         </form></div>
         ';
 
@@ -4865,14 +4887,18 @@ function getAttachmentsAjaxTable($postId = null)
     if (!empty($_REQUEST['file_ids']) && is_array($_REQUEST['file_ids'])) {
         // 'file_ids is the name from forum attachment ajax form
         foreach ($_REQUEST['file_ids'] as $key => $attachId) {
-            if (!empty($_SESSION['forum']['upload_file'][$courseId][$attachId]) && is_array($_SESSION['forum']['upload_file'][$courseId][$attachId])) {
+            if (!empty($_SESSION['forum']['upload_file'][$courseId][$attachId]) &&
+                is_array($_SESSION['forum']['upload_file'][$courseId][$attachId])
+            ) {
                 // If exist forum attachment then update into $_SESSION data
                 $_SESSION['forum']['upload_file'][$courseId][$attachId]['comment'] = $_POST['file_comments'][$key];
             }
         }
     }
     // Get data to fill into attachment files table
-    if (!empty($_SESSION['forum']['upload_file'][$courseId]) && is_array($_SESSION['forum']['upload_file'][$courseId])) {
+    if (!empty($_SESSION['forum']['upload_file'][$courseId]) &&
+        is_array($_SESSION['forum']['upload_file'][$courseId])
+    ) {
         $uploadedFiles = $_SESSION['forum']['upload_file'][$courseId];
         foreach ($uploadedFiles as $k => $uploadedFile) {
             if (!empty($uploadedFile) && in_array($uploadedFile['id'], $attachIds)) {
@@ -4922,8 +4948,8 @@ function getAttachmentsAjaxTable($postId = null)
  * @param null $courseId
  * @return array
  */
-function getAttachedFiles($forumId, $threadId, $postId = null, $attachId = null, $courseId = null) {
-    // Init values
+function getAttachedFiles($forumId, $threadId, $postId = null, $attachId = null, $courseId = null)
+{
     $forumId = intval($forumId);
     $courseId = intval($courseId);
     $attachId = intval($attachId);
@@ -4954,14 +4980,17 @@ function getAttachedFiles($forumId, $threadId, $postId = null, $attachId = null,
         $filter = "AND post_id = $postId AND id = $attachId";
     }
     $forumAttachmentTable = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
-    $sql = "SELECT id, comment, filename, path, size FROM $forumAttachmentTable WHERE c_id = $courseId $filter";
+    $sql = "SELECT id, comment, filename, path, size
+            FROM $forumAttachmentTable
+            WHERE c_id = $courseId $filter";
     $result = Database::query($sql);
+    $json = array();
     if ($result !== false && Database::num_rows($result) > 0) {
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             // name contains an URL to download attachment file and its filename
             $json['name'] = Display::url(
                 api_htmlentities($row['filename']),
-                api_get_path(WEB_CODE_PATH) . 'forum/download.php?file='.$row['path'],
+                api_get_path(WEB_CODE_PATH) . 'forum/download.php?file='.$row['path'].'&'.api_get_cidreq(),
                 array('target'=>'_blank', 'class' => 'attachFilename')
             );
             $json['id'] = $row['id'];
@@ -4970,12 +4999,14 @@ function getAttachedFiles($forumId, $threadId, $postId = null, $attachId = null,
             $json['size'] = format_file_size($row['size']);
             // Check if $row is consistent
             if (!empty($row) && is_array($row)) {
-                // Set result as succes and bring delete URL
+                // Set result as success and bring delete URL
                 $json['result'] = Display::return_icon('accept.png', get_lang('Uploaded'));
-                $json['delete'] = '<a class="deleteLink" href="'.api_get_path(WEB_CODE_PATH) . 'forum/viewthread.php' .
-                    '?' . api_get_cidreq() . '&amp;action=delete_attach&amp;forum=' . $forumId . '&amp;thread=' . $threadId .
-                    '&amp;id_attach=' . $row['id'] . '">' .
-                    Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
+                $url = api_get_path(WEB_CODE_PATH) . 'forum/viewthread.php?' . api_get_cidreq() . '&amp;action=delete_attach&amp;forum=' . $forumId . '&amp;thread=' . $threadId.'&amp;id_attach=' . $row['id'];
+                $json['delete'] = Display::url(
+                    Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL),
+                    $url,
+                    array('class' => 'deleteLink')
+                );
             } else {
                 // If not, set an exclamation result
                 $json['result'] = Display::return_icon('exclamation.png', get_lang('Error'));

+ 3 - 6
main/forum/forumsearch.php

@@ -57,9 +57,9 @@ if (isset($_SESSION['gradebook'])){
 
 if (!empty($gradebook) && $gradebook == 'view') {
     $interbreadcrumb[] = array (
-            'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-            'name' => get_lang('ToolGradebook')
-        );
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('ToolGradebook')
+    );
 }
 
 if (!empty ($_GET['gidReq'])) {
@@ -87,9 +87,6 @@ if ($origin == 'learnpath') {
     Display :: display_header($nameTools);
 }
 
-// Display the tool title.
-// api_display_tool_title($nameTools);
-
 // Tool introduction
 Display::display_introduction_section(TOOL_FORUM);
 

+ 4 - 10
main/forum/iframe_thread.php

@@ -21,15 +21,9 @@
  * @package chamilo.forum
  */
 
-/* INIT SECTION */
-
-/* Language Initialisation */
-
 // Name of the language file that needs to be included
 $language_file = 'forum';
 
-//$this_section = SECTION_COURSES;
-
 require_once '../inc/global.inc.php';
 
 /* ACCESS RIGHTS */
@@ -77,13 +71,13 @@ $course_id = api_get_course_int_id();
 
 $sql = "SELECT * FROM $table_posts posts, $table_users users
         WHERE
-        posts.c_id = $course_id AND
-        posts.thread_id='".$current_thread['thread_id']."'
-        AND posts.poster_id=users.user_id
+            posts.c_id = $course_id AND
+            posts.thread_id='".$current_thread['thread_id']."' AND
+            posts.poster_id=users.user_id
         ORDER BY posts.post_id ASC";
 $result = Database::query($sql);
 
-echo "<table width=\"100%\" cellspacing=\"5\" border=\"0\">";
+echo "<table width=\"100%\" height=\"100%\" cellspacing=\"5\" border=\"0\">";
 while ($row = Database::fetch_array($result)) {
     echo "<tr>";
     echo "<td rowspan=\"2\" class=\"forum_message_left\">";

+ 43 - 37
main/forum/index.php

@@ -21,9 +21,6 @@
  *
  * @package chamilo.forum
  */
-/**
- * Code
- */
 
 use \ChamiloSession as Session;
 // Name of the language file that needs to be included.
@@ -63,6 +60,8 @@ api_protect_course_script(true);
 require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 
 $nameTools = get_lang('Forums');
+$_course = api_get_course_info();
+$sessionId = api_get_session_id();
 
 // Including necessary files.
 require_once 'forumconfig.inc.php';
@@ -115,9 +114,9 @@ $form_count = 0;
 
 if (api_is_allowed_to_edit(false, true)) {
 
-	//if is called from a learning path lp_id
-	$lp_id = isset($_REQUEST['lp_id']) ? Security::remove_XSS($_REQUEST['lp_id']): null;
-	handle_forum_and_forumcategories($lp_id);
+    //if is called from a learning path lp_id
+    $lp_id = isset($_REQUEST['lp_id']) ? Security::remove_XSS($_REQUEST['lp_id']): null;
+    handle_forum_and_forumcategories($lp_id);
 }
 
 // Notification
@@ -175,8 +174,6 @@ if (isset($_SESSION['_gid'])) {
 
 /* ACTION LINKS */
 
-$session_id = api_get_session_id();
-
 echo '<div class="actions">';
 
 //if is called from learning path
@@ -203,11 +200,11 @@ echo '</div>';
 $forumsInNoCategory = get_forums_in_category(0);
 if (!empty($forumsInNoCategory)) {
     $forumCategories = array_merge($forumCategories, array(
-        array(
-            'cat_id' => 0,
-            'session_id' => 0,
-            'visibility' => 1,
-            'cat_comment' => null
+            array(
+                'cat_id' => 0,
+                'session_id' => 0,
+                'visibility' => 1,
+                'cat_comment' => null
             )
         )
     );
@@ -217,12 +214,12 @@ if (!empty($forumsInNoCategory)) {
 // Step 3: We display the forum_categories first.
 if (is_array($forumCategories)) {
     foreach ($forumCategories as $forumCategory) {
-         // The forums in this category.
+        // The forums in this category.
         $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
         // Validation when belongs to a session.
         $session_img = api_get_session_image($forumCategory['session_id'], $_user['status']);
 
-        if ((!isset($_SESSION['id_session']) || $_SESSION['id_session'] == 0) && !empty($forumCategory['session_name'])) {
+        if (empty($sessionId) && !empty($forumCategory['session_name'])) {
             $session_displayed = ' ('.Security::remove_XSS($forumCategory['session_name']).')';
         } else {
             $session_displayed = '';
@@ -244,7 +241,7 @@ if (is_array($forumCategories)) {
         echo '</th>';
         echo '<th style="vertical-align: top;" align="center" >';
         if (!empty($forumCategory['cat_id'])) {
-            if (api_is_allowed_to_edit(false, true) && !($forumCategory['session_id'] == 0 && intval($session_id) != 0)) {
+            if (api_is_allowed_to_edit(false, true) && !($forumCategory['session_id'] == 0 && intval($sessionId) != 0)) {
                 echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;gradebook='.$gradebook.'&amp;action=edit&amp;content=forumcategory&amp;id='.intval($forumCategory['cat_id']).'">'.Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
                 echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;gradebook='.$gradebook.'&amp;action=delete&amp;content=forumcategory&amp;id='.intval($forumCategory['cat_id'])."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('DeleteForumCategory'), ENT_QUOTES))."')) return false;\">".Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
                 display_visible_invisible_icon('forumcategory', strval(intval($forumCategory['cat_id'])), strval(intval($forumCategory['visibility'])));
@@ -273,19 +270,25 @@ if (is_array($forumCategories)) {
             foreach ($forum_list as $forum) {
                 // Here we clean the whatnew_post_info array a little bit because to display the icon we
                 // test if $whatsnew_post_info[$forum['forum_id']] is empty or not.
-                if (!empty($whatsnew_post_info)) {
-                    if (is_array(isset($whatsnew_post_info[$forum['forum_id']]) ? $whatsnew_post_info[$forum['forum_id']] : null)) {
-                        foreach ($whatsnew_post_info[$forum['forum_id']] as $key_thread_id => $new_post_array) {
-                            if (empty($whatsnew_post_info[$forum['forum_id']][$key_thread_id]))	{
-                                unset($whatsnew_post_info[$forum['forum_id']][$key_thread_id]);
-                                unset($_SESSION['whatsnew_post_info'][$forum['forum_id']][$key_thread_id]);
+                if (isset($forum['forum_id'])) {
+                    if (!empty($whatsnew_post_info)) {
+                        if (isset($whatsnew_post_info[$forum['forum_id']]) &&
+                            is_array($whatsnew_post_info[$forum['forum_id']])
+                        ) {
+                            foreach ($whatsnew_post_info[$forum['forum_id']] as $key_thread_id => $new_post_array) {
+                                if (empty($whatsnew_post_info[$forum['forum_id']][$key_thread_id])) {
+                                    unset($whatsnew_post_info[$forum['forum_id']][$key_thread_id]);
+                                    unset($_SESSION['whatsnew_post_info'][$forum['forum_id']][$key_thread_id]);
+                                }
                             }
                         }
                     }
                 }
 
-                // Note: This can be speeded up if we transform the $forum_list to an array that uses the forum_category as the key.
-                if (isset($forum['forum_category']) && $forum['forum_category'] == $forumCategory['cat_id']) {
+                // Note: This can be speed up if we transform the $forum_list to an array that uses the forum_category as the key.
+                if (isset($forum['forum_category']) &&
+                    $forum['forum_category'] == $forumCategory['cat_id']
+                ) {
                     $show_forum = false;
 
                     // SHOULD WE SHOW THIS PARTICULAR FORUM
@@ -299,7 +302,11 @@ if (is_array($forumCategories)) {
                         if ($forum['forum_of_group'] == '0') {
                             $show_forum = true;
                         } else {
-                            $show_forum = GroupManager::user_has_access($user_id, $forum['forum_of_group'], GroupManager::GROUP_TOOL_FORUM);
+                            $show_forum = GroupManager::user_has_access(
+                                $user_id,
+                                $forum['forum_of_group'],
+                                GroupManager::GROUP_TOOL_FORUM
+                            );
                         }
                     }
 
@@ -319,21 +326,19 @@ if (is_array($forumCategories)) {
                                 if ($image_size['width'] > 100 || $image_size['height'] > 100) {
                                     //limit display width and height to 100px
                                     $img_attributes = ' style="width:100px" width="100px" height="100px"';
-									$td_width = 100;
+                                    $td_width = 100;
+                                } else {
+                                    $td_width = $image_size['width'];
                                 }
-								else
-								{
-									$td_width = $image_size['width'];
-								}
                                 $forum_image =  "<img src=\"$image_path\" $img_attributes>";
                             } else {
                                 $forum_image = '';
-								$td_width = 20;
+                                $td_width = 20;
                             }
-							echo '<td width="'.$td_width.'px">';
+                            echo '<td width="'.$td_width.'px">';
                             echo $forum_image;
                         } else {
-							echo '<td width="20px">';
+                            echo '<td width="20px">';
                             if ($forum['forum_of_group'] !== '0') {
                                 if (is_array($mywhatsnew_post_info) && !empty($mywhatsnew_post_info)) {
                                     echo Display::return_icon('forumgroupnew.gif');
@@ -363,7 +368,7 @@ if (is_array($forumCategories)) {
                             $forum_title_group_addition = '';
                         }
 
-                        if ((!isset($_SESSION['id_session']) || $_SESSION['id_session'] == 0) && !empty($forum['session_name'])) {
+                        if (empty($sessionId) && !empty($forum['session_name'])) {
                             $session_displayed = ' ('.$forum['session_name'].')';
                         } else {
                             $session_displayed = '';
@@ -378,13 +383,13 @@ if (is_array($forumCategories)) {
                         echo '<span class="forum_description">'.prepare4display($forum['forum_comment']).'</span>';
                         echo '</td>';
 
-                        //$number_forum_topics_and_posts = get_post_topics_of_forum($forum['forum_id']); // deprecated
-
                         // The number of topics and posts.
                         $number_threads = isset($forum['number_of_threads']) ? $forum['number_of_threads'] : null;
                         $number_posts = isset($forum['number_of_posts']) ? $forum['number_of_posts'] : null;
+
                         echo '<td>'.$number_threads.'</td>';
                         echo '<td>'.$number_posts.'</td>';
+
                         // The last post in the forum.
                         if ($forum['last_poster_name'] != '') {
                             $name = $forum['last_poster_name'];
@@ -402,8 +407,9 @@ if (is_array($forumCategories)) {
                             echo api_convert_and_format_date($forum['last_post_date']).'<br /> '.get_lang('By').' '.display_user_link($poster_id, $name, '', $username);
                         }
                         echo '</td>';
+
                         echo '<td class="td_actions">';
-                        if (api_is_allowed_to_edit(false, true) && !($forum['session_id'] == 0 && intval($session_id) != 0)) {
+                        if (api_is_allowed_to_edit(false, true) && !($forum['session_id'] == 0 && intval($sessionId) != 0)) {
                             echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;gradebook='.$gradebook.'&amp;action=edit&amp;content=forum&amp;id='.$forum['forum_id'].'">'.
                                 Display::return_icon('edit.png',get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
                             echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;gradebook='.$gradebook.'&amp;action=delete&amp;content=forum&amp;id='.$forum['forum_id']."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('DeleteForum'), ENT_QUOTES))."')) return false;\">".

+ 3 - 2
main/forum/newthread.php

@@ -154,7 +154,8 @@ handle_forum_and_forumcategories();
 // Action links
 echo '<div class="actions">';
 echo '<span style="float:right;">'.search_link().'</span>';
-echo '<a href="viewforum.php?origin='.$origin.'&forum='.Security::remove_XSS($_GET['forum']).'&'.api_get_cidreq().'">'.Display::return_icon('back.png',get_lang('BackToForum'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="viewforum.php?origin='.$origin.'&forum='.Security::remove_XSS($_GET['forum']).'&'.api_get_cidreq().'">'.
+    Display::return_icon('back.png',get_lang('BackToForum'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '</div>';
 
 // Set forum attachment data into $_SESSION
@@ -178,4 +179,4 @@ if (!empty($values) && isset($values['SubmitPost'])) {
 
 if ($origin != 'learnpath') {
     Display :: display_footer();
-}
+}

+ 8 - 3
main/forum/reply.php

@@ -143,7 +143,8 @@ if ($origin == 'learnpath') {
 if ($origin != 'learnpath') {
     echo '<div class="actions">';
     echo '<span style="float:right;">'.search_link().'</span>';
-    echo '<a href="viewthread.php?forum='.Security::remove_XSS($_GET['forum']).'&amp;gradebook='.$gradebook.'&amp;thread='.Security::remove_XSS($_GET['thread']).'&amp;origin='.$origin.'">'.Display::return_icon('back.png', get_lang('BackToThread'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="viewthread.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&amp;gradebook='.$gradebook.'&amp;thread='.Security::remove_XSS($_GET['thread']).'&amp;origin='.$origin.'">'.
+        Display::return_icon('back.png', get_lang('BackToThread'), '', ICON_SIZE_MEDIUM).'</a>';
     echo '</div>';
 } else {
     echo '<div style="height:15px">&nbsp;</div>';
@@ -175,11 +176,15 @@ if (!empty($values) AND isset($_POST['SubmitPost'])) {
 } else {
     // Only show Forum attachment ajax form when do not pass form submit
     echo '<div class="row"><div class="span12">';
-    $attachmentAjaxForm = getAttachmentAjaxForm($current_forum['forum_id'], $current_thread['thread_id'], 0);
+    $attachmentAjaxForm = getAttachmentAjaxForm(
+        $current_forum['forum_id'],
+        $current_thread['thread_id'],
+        0
+    );
     echo $attachmentAjaxForm;
     echo '</div></div>';
 }
 
 if ($origin != 'learnpath') {
     Display :: display_footer();
-}
+}

+ 26 - 18
main/forum/viewforum.php

@@ -77,7 +77,7 @@ if (!empty($groupId)) {
     //Course
     if (!api_is_allowed_to_edit(false, true) AND  //is a student
         (($current_forum_category && $current_forum_category['visibility'] == 0) OR
-        $current_forum['visibility'] == 0 OR !$user_has_access_in_group)
+            $current_forum['visibility'] == 0 OR !$user_has_access_in_group)
     ) {
         api_not_allowed();
     }
@@ -281,7 +281,8 @@ if ($origin != 'learnpath') {
             Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('Groups'),'',ICON_SIZE_MEDIUM).'</a>';
     } else {
         echo '<span style="float:right;">'.search_link().'</span>';
-        echo '<a href="'.$forumUrl.'index.php">'.Display::return_icon('back.png', get_lang('BackToForumOverview'), '', ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href="'.$forumUrl.'index.php?'.api_get_cidreq().'">'.
+            Display::return_icon('back.png', get_lang('BackToForumOverview'), '', ICON_SIZE_MEDIUM).'</a>';
     }
 }
 
@@ -289,19 +290,24 @@ if ($origin != 'learnpath') {
 // 1. the course admin is here
 // 2. the course member is here and new threads are allowed
 // 3. a visitor is here and new threads AND allowed AND  anonymous posts are allowed
-if (api_is_allowed_to_edit(false, true) OR ($current_forum['allow_new_threads'] == 1 AND isset($_user['user_id'])) OR ($current_forum['allow_new_threads'] == 1 AND !isset($_user['user_id']) AND $current_forum['allow_anonymous'] == 1)) {
-	if ($current_forum['locked'] <> 1 AND $current_forum['locked'] <> 1) {
-		if (!api_is_anonymous()) {
-			if ($my_forum == strval(intval($my_forum))) {
-				echo '<a href="'.$forumUrl.'newthread.php?'.api_get_cidreq().'&amp;forum='.Security::remove_XSS($my_forum).$origin_string.'">'.Display::return_icon('new_thread.png',get_lang('NewTopic'),'',ICON_SIZE_MEDIUM).'</a>';
-		    } else {
-		    	$my_forum = strval(intval($my_forum));
-				echo '<a href="'.$forumUrl.'newthread.php?'.api_get_cidreq().'&amp;forum='.$my_forum.$origin_string.'">'.Display::return_icon('new_thread.png',get_lang('NewTopic'),'',ICON_SIZE_MEDIUM).'</a>';
-			}
-		}
-	} else {
-		echo get_lang('ForumLocked');
-	}
+if (api_is_allowed_to_edit(false, true) OR
+    ($current_forum['allow_new_threads'] == 1 AND isset($_user['user_id'])) OR
+    ($current_forum['allow_new_threads'] == 1 AND !isset($_user['user_id']) AND $current_forum['allow_anonymous'] == 1)
+) {
+    if ($current_forum['locked'] <> 1 AND $current_forum['locked'] <> 1) {
+        if (!api_is_anonymous()) {
+            if ($my_forum == strval(intval($my_forum))) {
+                echo '<a href="'.$forumUrl.'newthread.php?'.api_get_cidreq().'&amp;forum='.Security::remove_XSS($my_forum).$origin_string.'">'.
+                    Display::return_icon('new_thread.png',get_lang('NewTopic'),'',ICON_SIZE_MEDIUM).'</a>';
+            } else {
+                $my_forum = strval(intval($my_forum));
+                echo '<a href="'.$forumUrl.'newthread.php?'.api_get_cidreq().'&amp;forum='.$my_forum.$origin_string.'">'.
+                    Display::return_icon('new_thread.png',get_lang('NewTopic'),'',ICON_SIZE_MEDIUM).'</a>';
+            }
+        }
+    } else {
+        echo get_lang('ForumLocked');
+    }
 }
 echo '</div>';
 
@@ -335,7 +341,7 @@ echo '<td>'.get_lang('Actions').'</td>';
 echo '</tr>';
 
 // Getting al the threads
-$threads = get_threads($my_forum); // Note: This has to be cleaned first
+$threads = get_threads($my_forum);
 $whatsnew_post_info = isset($_SESSION['whatsnew_post_info']) ? $_SESSION['whatsnew_post_info'] : null;
 
 $course_id = api_get_course_int_id();
@@ -344,9 +350,11 @@ $counter = 0;
 if (is_array($threads)) {
     foreach ($threads as $row) {
         // Thread who have no replies yet and the only post is invisible should not be displayed to students.
-        if (api_is_allowed_to_edit(false, true) OR !($row['thread_replies'] == '0' AND $row['visibility'] == '0')) {
+        if (api_is_allowed_to_edit(false, true) OR
+            !($row['thread_replies'] == '0' AND $row['visibility'] == '0')
+        ) {
             if ($counter % 2 == 0) {
-                 $class = 'row_odd';
+                $class = 'row_odd';
             } else {
                 $class = 'row_even';
             }

+ 4 - 3
main/forum/viewforumcategory.php

@@ -75,11 +75,11 @@ $interbreadcrumb[] = array('url' => 'index.php?gradebook='.$gradebook.'&amp;sear
 
 if (!empty($_GET['action']) && !empty($_GET['content'])) {
     if ($_GET['action']=='add' && $_GET['content']=='forum' ) {
-    	$interbreadcrumb[] = array('url' =>'viewforumcategory.php?forumcategory='.$current_forum_category['cat_id'].'&amp;origin='.$origin,'name' => $current_forum_category['cat_title']);
+        $interbreadcrumb[] = array('url' =>'viewforumcategory.php?forumcategory='.$current_forum_category['cat_id'].'&amp;origin='.$origin,'name' => $current_forum_category['cat_title']);
         $interbreadcrumb[] = array('url' =>'#', 'name' => get_lang('AddForum'));
     }
 } else {
-	$interbreadcrumb[] = array('url' => '#','name' => $current_forum_category['cat_title']);
+    $interbreadcrumb[] = array('url' => '#','name' => $current_forum_category['cat_title']);
 }
 
 // Are we in a lp ?
@@ -108,7 +108,8 @@ if (!api_is_allowed_to_edit(false,true) AND ($current_forum_category && $current
 /* Action Links */
 echo '<div class="actions">';
 echo '<span style="float:right;">'.search_link().'</span>';
-echo '<a href="index.php?gradebook='.$gradebook.'">'.Display::return_icon('back.png', get_lang('BackToForumOverview'), '', ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="index.php?gradebook='.$gradebook.'&'.api_get_cidreq().'">'.
+    Display::return_icon('back.png', get_lang('BackToForumOverview'), '', ICON_SIZE_MEDIUM).'</a>';
 if (api_is_allowed_to_edit(false,true)) {
     echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&forumcategory='.$current_forum_category['cat_id'].'&amp;action=add&amp;content=forum"> '.Display::return_icon('new_forum.png', get_lang('AddForum'),'',ICON_SIZE_MEDIUM).'</a>';
 }

+ 19 - 14
main/forum/viewthread.php

@@ -39,13 +39,13 @@ $gradebook = null;
 
 // We are getting all the information about the current forum and forum category.
 // Note pcool: I tried to use only one sql statement (and function) for this,
-// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table.
+// but the problem is that the visibility of the forum AND forum category are stored in the item_property table.
 // Note: This has to be validated that it is an existing thread
 $current_thread	= get_thread_information($_GET['thread']);
 // Note: This has to be validated that it is an existing forum.
 $current_forum	= get_forum_information($current_thread['forum_id']);
 $current_forum_category	= get_forumcategory_information($current_forum['forum_category']);
-$whatsnew_post_info	= isset($_SESSION['whatsnew_post_info']) ? $_SESSION['whatsnew_post_info'] : null; // This variable should be deprecated?
+$whatsnew_post_info	= isset($_SESSION['whatsnew_post_info']) ? $_SESSION['whatsnew_post_info'] : null;
 
 /* Header and Breadcrumbs */
 
@@ -132,7 +132,6 @@ if ($my_message != 'PostDeletedSpecial') {
     if ($origin != 'learnpath') {
         echo '<a href="'.$forumUrl.'viewforum.php?forum='.Security::remove_XSS($_GET['forum']).'&'.api_get_cidreq().'">'.
             Display::return_icon('back.png', get_lang('BackToForum'), '', ICON_SIZE_MEDIUM).'</a>';
-
     }
     // The reply to thread link should only appear when the forum_category is not locked AND the forum is not locked AND the thread is not locked.
     // If one of the three levels is locked then the link should not be displayed.
@@ -145,7 +144,14 @@ if ($my_message != 'PostDeletedSpecial') {
                     Display::return_icon('reply_thread.png', get_lang('ReplyToThread'), '', ICON_SIZE_MEDIUM).'</a>';
             }
             // new thread link
-            if ((api_is_allowed_to_edit(false, true) && !(api_is_course_coach() && $current_forum['session_id'] != $_SESSION['id_session'])) OR ($current_forum['allow_new_threads'] == 1 AND isset($_user['user_id'])) OR ($current_forum['allow_new_threads'] == 1 AND !isset($_user['user_id']) AND $current_forum['allow_anonymous'] == 1)) {
+            if (
+                (
+                    api_is_allowed_to_edit(false, true) &&
+                    !(api_is_course_coach() && $current_forum['session_id'] != $_SESSION['id_session'])
+                ) OR
+                ($current_forum['allow_new_threads'] == 1 AND isset($_user['user_id'])) OR
+                ($current_forum['allow_new_threads'] == 1 AND !isset($_user['user_id']) AND $current_forum['allow_anonymous'] == 1)
+            ) {
                 if ($current_forum['locked'] <> 1 AND $current_forum['locked'] <> 1) {
                     echo '&nbsp;&nbsp;';
                 } else {
@@ -184,15 +190,16 @@ if ($my_message != 'PostDeletedSpecial') {
     }
 
     if (isset($_GET['msg']) && isset($_GET['type'])) {
-    	switch($_GET['type']) {
-    		case 'error':
-    			Display::display_error_message($_GET['msg']);
-    			break;
-    		case 'confirmation':
-    			Display::display_confirmation_message($_GET['msg']);
-    			break;
-    	}
+        switch($_GET['type']) {
+            case 'error':
+                Display::display_error_message($_GET['msg']);
+                break;
+            case 'confirmation':
+                Display::display_confirmation_message($_GET['msg']);
+                break;
+        }
     }
+
     switch ($viewmode) {
         case 'flat':
             include_once 'viewthread_flat.inc.php';
@@ -209,8 +216,6 @@ if ($my_message != 'PostDeletedSpecial') {
     }
 }
 
-/* FOOTER */
-
 if ($origin != 'learnpath') {
     Display :: display_footer();
 }

+ 18 - 4
main/gradebook/gradebook.php

@@ -587,12 +587,26 @@ $gradebooktable= new GradebookTable($cats[0], $allcat, $alleval, $alllink, $addp
 if (((empty ($allcat)) && (empty ($alleval)) && (empty ($alllink)) && (!$is_platform_admin) && ($is_course_admin) && (!isset ($_GET['selectcat']))) && api_is_course_tutor()) {
     Display :: display_normal_message(get_lang('GradebookWelcomeMessage') . '<br /><br /><form name="createcat" method="post" action="' . api_get_self() . '?createallcategories=1"><input type="submit" value="' . get_lang('CreateAllCat') . '"></form>',false);
 }
-//here we are in a sub category
+// Here we are in a sub category
 if ($category != '0') {
-    DisplayGradebook :: display_header_gradebook($cats[0], 1, $_GET['selectcat'], $is_course_admin, $is_platform_admin, $simple_search_form);
+    DisplayGradebook:: display_header_gradebook(
+        $cats[0],
+        1,
+        $_GET['selectcat'],
+        $is_course_admin,
+        $is_platform_admin,
+        $simple_search_form
+    );
 } else {
-    //this is the root category
-    DisplayGradebook :: display_header_gradebook($cats[0], (((count($allcat) == '0') && (!isset ($_GET['search']))) ? 0 : 1), 0, $is_course_admin, $is_platform_admin, $simple_search_form);
+    // This is the root category
+    DisplayGradebook:: display_header_gradebook(
+        $cats[0],
+        (((count($allcat) == '0') && (!isset ($_GET['search']))) ? 0 : 1),
+        0,
+        $is_course_admin,
+        $is_platform_admin,
+        $simple_search_form
+    );
 }
 $gradebooktable->display();
 Display :: display_footer();

+ 9 - 7
main/gradebook/gradebook_add_cat.php

@@ -57,7 +57,7 @@ $(document).ready(function () {
 });
 
 function check_skills() {
-    //selecting only selected users
+    // selecting only selected users
     $("#skills option:selected").each(function() {
         var skill_id = $(this).val();
         if (skill_id != "" ) {
@@ -76,7 +76,7 @@ function check_skills() {
                             }
                         });
                     }
-                },
+                }
             });
         }
     });
@@ -98,7 +98,6 @@ if ($_in_course) {
 }
 
 $catadd->set_course_code(api_get_course_id());
-
 $form = new CatForm(
     CatForm :: TYPE_ADD,
     $catadd,
@@ -140,14 +139,17 @@ if ($form->validate()) {
     }
     $cat->set_visible($visible);
     $result = $cat->add();
-    header('Location: '.Security::remove_XSS($_SESSION['gradebook_dest']).'?addcat=&selectcat=' . $cat->get_parent_id());
+    header('Location: '.Security::remove_XSS($_SESSION['gradebook_dest']).'?addcat=&selectcat=' . $cat->get_parent_id().'&'.api_get_cidreq());
     exit;
 }
 
-if ( !$_in_course ) {
-    $interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.$get_select_cat,'name' => get_lang('Gradebook'));
+if (!$_in_course) {
+    $interbreadcrumb[] = array (
+        'url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.$get_select_cat.'&'.api_get_cidreq(),
+        'name' => get_lang('Gradebook')
+    );
 }
-$interbreadcrumb[]= array (	'url' =>'index.php','name' => get_lang('ToolGradebook'));
+$interbreadcrumb[]= array(	'url' =>'index.php','name' => get_lang('ToolGradebook'));
 Display :: display_header(get_lang('NewCategory'));
 
 $display_form = true;

+ 17 - 13
main/gradebook/gradebook_add_eval.php

@@ -1,6 +1,6 @@
 <?php
-
 /* For licensing terms, see /license.txt */
+
 /**
  * Script
  * @package chamilo.gradebook
@@ -29,7 +29,14 @@ if (isset($_GET['selectcat']) && (!empty($_GET['selectcat']))) {
     $evaladd->set_category_id(0);
 }
 
-$form = new EvalForm(EvalForm :: TYPE_ADD, $evaladd, null, 'add_eval_form', null, api_get_self() . '?selectcat=' . $select_cat);
+$form = new EvalForm(
+    EvalForm :: TYPE_ADD,
+    $evaladd,
+    null,
+    'add_eval_form',
+    null,
+    api_get_self() . '?selectcat=' . $select_cat.'&'.api_get_cidreq()
+);
 
 if ($form->validate()) {
     $values = $form->exportValues();
@@ -51,7 +58,6 @@ if ($form->validate()) {
     //$values['weight'] = $values['weight_mask']/$global_weight*$parent_cat[0]->get_weight();
     $values['weight'] = $values['weight_mask'];
 
-
     $eval->set_weight($values['weight']);
     $eval->set_max($values['max']);
 
@@ -68,32 +74,30 @@ if ($form->validate()) {
             //header('Location: gradebook_add_user.php?selecteval=' . $eval->get_id());
             exit;
         } else {
-            header('Location: ' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $eval->get_category_id());
+            header('Location: ' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $eval->get_category_id().'&'.api_get_cidreq());
             exit;
         }
     } else {
         $val_addresult = isset($values['addresult']) ? $values['addresult'] : null;
         if ($val_addresult == 1) {
-            header('Location: gradebook_add_result.php?selecteval=' . $eval->get_id());
+            header('Location: gradebook_add_result.php?selecteval=' . $eval->get_id().'&'.api_get_cidreq());
             exit;
         } else {
-            header('Location: ' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $eval->get_category_id());
+            header('Location: ' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $eval->get_category_id().'&'.api_get_cidreq());
             exit;
         }
     }
 }
 
 $interbreadcrumb[] = array(
-    'url' => Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $select_cat,
-    'name' => get_lang('Gradebook'
-    ));
+    'url' => Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $select_cat.'&'.api_get_cidreq(),
+    'name' => get_lang('Gradebook'))
+;
 $this_section = SECTION_COURSES;
 
 $htmlHeadXtra[] = '<script type="text/javascript">
 $(document).ready( function() {
-
-    $("#hid_category_id").change(function(){
-
+    $("#hid_category_id").change(function() {
        $("#hid_category_id option:selected").each(function () {
            var cat_id = $(this).val();
             $.ajax({
@@ -103,7 +107,7 @@ $(document).ready( function() {
                     if (return_value != 0 ) {
                         $("#max_weight").html(return_value);
                     }
-                },
+                }
             });
        });
     });

+ 16 - 11
main/gradebook/gradebook_add_link.php

@@ -34,7 +34,7 @@ if ($session_id == 0) {
     $all_categories = Category::load_session_categories(null, $session_id);
 }
 $category = Category :: load($_GET['selectcat']);
-$url = api_get_self().'?selectcat='.Security::remove_XSS($_GET['selectcat']).'&newtypeselected='.$typeSelected.'&course_code='.api_get_course_id();
+$url = api_get_self().'?selectcat='.Security::remove_XSS($_GET['selectcat']).'&newtypeselected='.$typeSelected.'&course_code='.api_get_course_id().'&'.api_get_cidreq();
 $typeform = new LinkForm(LinkForm :: TYPE_CREATE, $category[0], null, 'create_link', null, $url, $typeSelected);
 
 // if user selected a link type
@@ -87,8 +87,10 @@ if (isset($typeSelected) && $typeSelected != '0') {
         $link->set_visible(empty($addvalues['visible']) ? 0 : 1);
 
         // Update view_properties
-        if (isset($typeSelected) && 5 == $typeSelected && (isset($addvalues['select_link']) && $addvalues['select_link'] <> "")) {
-
+        if (isset($typeSelected) &&
+            5 == $typeSelected &&
+            (isset($addvalues['select_link']) && $addvalues['select_link'] <> "")
+        ) {
             $sql1 = 'SELECT thread_title from '.$tbl_forum_thread.'
 					 WHERE c_id = '.$course_info['real_id'].' AND thread_id='.$addvalues['select_link'];
             $res1 = Database::query($sql1);
@@ -100,32 +102,35 @@ if (isset($typeSelected) && $typeSelected != '0') {
             $row = Database::fetch_row($res_l);
             if ($row[0] == 0) {
                 $link->add();
-                $sql = 'UPDATE '.$tbl_forum_thread.' SET thread_qualify_max='.$addvalues['weight'].',thread_weight='.$addvalues['weight'].',thread_title_qualify="'.$rowtit[0].'"
+                $sql = 'UPDATE '.$tbl_forum_thread.' SET
+                            thread_qualify_max='.$addvalues['weight'].',
+                            thread_weight='.$addvalues['weight'].',
+                            thread_title_qualify="'.$rowtit[0].'"
 						WHERE thread_id='.$addvalues['select_link'].' AND c_id = '.$course_info['real_id'].' ';
                 Database::query($sql);
             }
         }
 
         $link->add();
-
         $addvalue_result = !empty($addvalues['addresult']) ? $addvalues['addresult'] : array();
         if ($addvalue_result == 1) {
-            header('Location: gradebook_add_result.php?selecteval='.$link->get_ref_id());
+            header('Location: gradebook_add_result.php?selecteval='.$link->get_ref_id().'&'.api_get_cidreq());
             exit;
         } else {
-            header('Location: '.Security::remove_XSS($_SESSION['gradebook_dest']).'?linkadded=&selectcat='.Security::remove_XSS($_GET['selectcat']));
+            header('Location: '.Security::remove_XSS($_SESSION['gradebook_dest']).'?linkadded=&selectcat='.Security::remove_XSS($_GET['selectcat']).'&'.api_get_cidreq());
             exit;
         }
     }
 }
 
-
-$interbreadcrumb[] = array('url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']), 'name' => get_lang('Gradebook'));
+$interbreadcrumb[] = array(
+    'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']).'&'.api_get_cidreq(),
+    'name' => get_lang('Gradebook')
+);
 $this_section = SECTION_COURSES;
 
 $htmlHeadXtra[] = '<script>
 $(document).ready( function() {
-
     $("#hide_category_id").change(function() {
        $("#hide_category_id option:selected").each(function () {
            var cat_id = $(this).val();
@@ -136,7 +141,7 @@ $(document).ready( function() {
                     if (return_value != 0 ) {
                         $("#max_weight").html(return_value);
                     }
-                },
+                }
             });
        });
     });

+ 13 - 7
main/gradebook/gradebook_add_link_select_course.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Script
  * @package chamilo.gradebook
@@ -18,25 +19,30 @@ api_block_anonymous_users();
 block_students();
 
 $catadd = new Category();
-$catadd->set_user_id($_user['user_id']);
+$catadd->set_user_id(api_get_user_id());
 $catadd->set_parent_id($_GET['selectcat']);
 $catcourse = Category :: load ($_GET['selectcat']);
-//$catadd->set_course_code($catcourse[0]->get_course_code());
-$form = new CatForm(CatForm :: TYPE_SELECT_COURSE, $catadd, 'add_cat_form', null, api_get_self().'?selectcat=' . Security::remove_XSS($_GET['selectcat']));
+$form = new CatForm(
+    CatForm :: TYPE_SELECT_COURSE,
+    $catadd,
+    'add_cat_form',
+    null,
+    api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']).'&'.api_get_cidreq()
+);
 
 if ($form->validate()) {
     $values = $form->exportValues();
     $cat = new Category();
     $cat->set_course_code($values['select_course']);
     $cat->set_name($values['name']);
-    header('location: gradebook_add_link.php?selectcat=' .Security::remove_XSS($_GET['selectcat']).'&course_code='.Security::remove_XSS($values['select_course']));
+    header('location: gradebook_add_link.php?selectcat=' .Security::remove_XSS($_GET['selectcat']).'&course_code='.Security::remove_XSS($values['select_course']).'&'.api_get_cidreq());
     exit;
 }
 
 $interbreadcrumb[] = array (
-    'url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.Security::remove_XSS($_GET['selectcat']),
-    'name' => get_lang('Gradebook'
-    ));
+    'url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.Security::remove_XSS($_GET['selectcat']).'&'.api_get_cidreq(),
+    'name' => get_lang('Gradebook')
+);
 Display :: display_header(get_lang('NewCategory'));
 $form->display();
 Display :: display_footer();

+ 14 - 4
main/gradebook/gradebook_add_result.php

@@ -24,13 +24,20 @@ $resultadd = new Result();
 $resultadd->set_evaluation_id($_GET['selecteval']);
 $evaluation = Evaluation :: load($_GET['selecteval']);
 $category = !empty($_GET['selectcat']) ? $_GET['selectcat'] : "";
-$add_result_form = new EvalForm(EvalForm :: TYPE_RESULT_ADD, $evaluation[0], $resultadd, 'add_result_form', null, api_get_self() . '?selectcat=' . Security::remove_XSS($category) . '&selecteval=' . Security::remove_XSS($_GET['selecteval']));
+$add_result_form = new EvalForm(
+    EvalForm :: TYPE_RESULT_ADD,
+    $evaluation[0],
+    $resultadd,
+    'add_result_form',
+    null,
+    api_get_self() . '?selectcat=' . Security::remove_XSS($category) . '&selecteval=' . Security::remove_XSS($_GET['selecteval']).'&'.api_get_cidreq()
+);
 $table = $add_result_form->toHtml();
 if ($add_result_form->validate()) {
     $values = $add_result_form->exportValues();
     $nr_users = $values['nr_users'];
     if ($nr_users == '0') {
-        header('Location: gradebook_view_result.php?addresultnostudents=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
+        header('Location: gradebook_view_result.php?addresultnostudents=&selecteval=' . Security::remove_XSS($_GET['selecteval']).'&'.api_get_cidreq());
         exit;
     }
     $scores = ($values['score']);
@@ -43,10 +50,13 @@ if ($add_result_form->validate()) {
         $res->add();
         next($scores);
     }
-    header('Location: gradebook_view_result.php?addresult=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
+    header('Location: gradebook_view_result.php?addresult=&selecteval=' . Security::remove_XSS($_GET['selecteval']).'&'.api_get_cidreq());
     exit;
 }
-$interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']),'name' => get_lang('Gradebook'));
+$interbreadcrumb[] = array(
+    'url' => Security::remove_XSS($_SESSION['gradebook_dest']),
+    'name' => get_lang('Gradebook')
+);
 Display :: display_header(get_lang('AddResult'));
 DisplayGradebook :: display_header_result ($evaluation[0], null, 0,0);
 echo $table;

+ 56 - 51
main/gradebook/gradebook_display_certificate.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Script
  * @package chamilo.gradebook
@@ -34,69 +35,36 @@ if (!api_is_allowed_to_edit()) {
 
 $cat_id = isset($_GET['cat_id']) ? (int)$_GET['cat_id'] : null;
 $action = isset($_GET['action']) && $_GET['action'] ? $_GET['action'] : null;
+$filterOfficialCode = isset($_POST['filter']) ? Security::remove_XSS($_POST['filter']) : null;
+$filterOfficialCodeGet = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
+
 switch ($action) {
     case 'export_all_certificates':
-        $params['orientation'] = 'landscape';
-        $params['left'] = 0;
-        $params['right'] = 0;
-        $params['top'] = 0;
-        $params['bottom'] = 0;
-        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
-        $pdf = new PDF($page_format, $params['orientation'], $params);
-
-        $certificate_list = get_list_users_certificates($cat_id);
-        $certificate_path_list = array();
-
-        if (!empty($certificate_list)) {
-            foreach ($certificate_list as $index=>$value) {
-                $list_certificate = get_list_gradebook_certificates_by_user_id($value['user_id'], $cat_id);
-                foreach ($list_certificate as $value_certificate) {
-                    $certificate_obj = new Certificate($value_certificate['id']);
-                    $certificate_obj->generate(array('hide_print_button' => true));
-                    if ($certificate_obj->html_file_is_generated()) {
-                        $certificate_path_list[]= $certificate_obj->html_file;
-                    }
-                }
-            }
-        }
-        if (!empty($certificate_path_list)) {
-            // Print certificates (without the common header/footer/watermark
-            //  stuff) and return as one multiple-pages PDF
-            $pdf->html_to_pdf($certificate_path_list, get_lang('Certificates'), null, false, false);
+        $userList = array();
+        if (!empty($filterOfficialCodeGet)) {
+            $userList = UserManager::getUsersByOfficialCode($filterOfficialCodeGet);
         }
+        Category::exportAllCertificates($cat_id, $userList);
         break;
     case 'generate_all_certificates':
         $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id());
-        if (!empty($user_list)) {
-            foreach ($user_list as $user_info) {
-                Category::register_user_certificate($cat_id, $user_info['user_id']);
-            }
-        }
+        Category::generateCertificatesInUserList($cat_id, $user_list);
         break;
     case 'delete_all_certificates':
-        $certificate_list = get_list_users_certificates($cat_id);
-        if (!empty($certificate_list)) {
-            foreach ($certificate_list as $index=>$value) {
-                $list_certificate = get_list_gradebook_certificates_by_user_id($value['user_id'], $cat_id);
-                foreach ($list_certificate as $value_certificate) {
-                    $certificate_obj = new Certificate($value_certificate['id']);
-                    $certificate_obj->delete(true);
-                }
-            }
-        }
+        Category::deleteAllCertificates($cat_id);
         break;
 }
 
 $course_code = api_get_course_id();
 
-$interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?',	'name' => get_lang('Gradebook'));
-$interbreadcrumb[] = array ('url' => '#','name' => get_lang('GradebookListOfStudentsCertificates'));
+$interbreadcrumb[] = array('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?',	'name' => get_lang('Gradebook'));
+$interbreadcrumb[] = array('url' => '#','name' => get_lang('GradebookListOfStudentsCertificates'));
 
 $this_section = SECTION_COURSES;
 
 Display::display_header('');
 
-if ($_GET['action'] == 'delete') {
+if (isset($_GET['action']) && $_GET['action'] == 'delete') {
     $check = Security::check_token('get');
     if ($check) {
         $certificate = new Certificate($_GET['certificate_id']);
@@ -104,7 +72,7 @@ if ($_GET['action'] == 'delete') {
         Security::clear_token();
         if ($result ==true) {
             Display::display_confirmation_message(get_lang('CertificateRemoved'));
-        } else  {
+        } else {
             Display::display_error_message(get_lang('CertificateNotRemoved'));
         }
     }
@@ -155,22 +123,59 @@ if (!empty($cats)) {
     }
 }
 
-$certificate_list = get_list_users_certificates($cat_id);
+$filter = api_get_configuration_value('certificate_filter_by_official_code');
+$userList = array();
+$filterForm = null;
+$certificate_list = array();
+if ($filter) {
+    echo '<br />';
+    $options = UserManager::getOfficialCodeGrouped();
+    $options =array_merge(array('all' => get_lang('All')), $options);
+    $form = new FormValidator(
+        'official_code_filter',
+        'POST',
+        api_get_self().'?'.api_get_cidreq().'&cat_id='.$cat_id
+    );
+    $form->addElement('select', 'filter', get_lang('OfficialCode'), $options);
+    $form->add_button('submit', get_lang('Submit'));
+    $filterForm = '<br />'.$form->return_form();
+
+    if ($form->validate()) {
+        $officialCode = $form->getSubmitValue('filter');
+         if ($officialCode == 'all') {
+            $certificate_list = get_list_users_certificates($cat_id);
+        } else {
+             $userList = UserManager::getUsersByOfficialCode($officialCode);
+             if (!empty($userList)) {
+                 $certificate_list = get_list_users_certificates(
+                     $cat_id,
+                     $userList
+                 );
+             }
+         }
+    } else {
+        $certificate_list = get_list_users_certificates($cat_id);
+    }
+} else {
+    $certificate_list = get_list_users_certificates($cat_id);
+}
 
 echo '<div class="btn-group">';
-$url = api_get_self().'?action=generate_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id;
+$url = api_get_self().'?action=generate_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
 echo Display::url(get_lang('GenerateCertificates'), $url, array('class' => 'btn'));
 
-$url = api_get_self().'?action=delete_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id;
+$url = api_get_self().'?action=delete_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
 echo Display::url(get_lang('DeleteAllCertificates'), $url, array('class' => 'btn'));
 
 if (count($certificate_list) > 0) {
-    $url = api_get_self().'?action=export_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id;
+    $url = api_get_self().'?action=export_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
     echo Display::url(get_lang('ExportAllCertificatesToPDF'), $url, array('class' => 'btn'));
 }
 echo '</div>';
 
-if (count($certificate_list)==0) {
+echo $filterForm;
+
+if (count($certificate_list) == 0 ) {
     echo Display::display_warning_message(get_lang('NoResultsAvailable'));
 } else {
 

+ 6 - 5
main/gradebook/gradebook_edit_all.php

@@ -57,7 +57,6 @@ $course_id			  =	get_course_id_by_link_id($my_selectcat);
 
 $table_link           = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 $table_evaluation     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
-
 $tbl_forum_thread     = Database :: get_course_table(TABLE_FORUM_THREAD);
 $tbl_work             = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 $tbl_attendance       = Database :: get_course_table(TABLE_ATTENDANCE);
@@ -77,7 +76,7 @@ if ($submitted==1) {
         require_once 'lib/be/evaluation.class.php';
         $eval_log = new Evaluation();
     }
-    if(isset($_POST['link'])){
+    if (isset($_POST['link'])) {
         require_once 'lib/be/abstractlink.class.php';
         //$eval_link_log = new AbstractLink();
     }
@@ -170,7 +169,7 @@ if ($my_api_cidreq=='') {
 }
 ?>
     <div class="actions">
-        <a href="<?php echo Security::remove_XSS($_SESSION['gradebook_dest']).'?id_session='.api_get_session_id().'&amp;'.$my_api_cidreq ?>&selectcat=<?php echo $my_selectcat ?>">
+        <a href="<?php echo Security::remove_XSS($_SESSION['gradebook_dest']).'?'.$my_api_cidreq ?>&selectcat=<?php echo $my_selectcat ?>">
             <?php echo Display::return_icon('back.png',get_lang('FolderView'),'',ICON_SIZE_MEDIUM); ?>
         </a>
     </div>
@@ -178,7 +177,7 @@ if ($my_api_cidreq=='') {
 $warning_message = sprintf(get_lang('TotalWeightMustBeX'), $masked_total);
 Display::display_normal_message($warning_message, false);
 ?>
-    <form method="post" action="gradebook_edit_all.php?id_session=<?php echo $_SESSION['id_session'].'&amp;'.$my_api_cidreq ?>&selectcat=<?php echo $my_selectcat?>">
+    <form method="post" action="gradebook_edit_all.php?<?php echo $my_api_cidreq ?>&selectcat=<?php echo $my_selectcat?>">
         <table class="data_table">
             <tr class="row_odd">
                 <th style="width: 35px;"><?php echo get_lang('Type'); ?></th>
@@ -189,7 +188,9 @@ Display::display_normal_message($warning_message, false);
         </table>
         <input type="hidden" name="submitted" value="1" />
         <br />
-        <button class="save" type="submit" name="name" value="<?php echo get_lang('Save') ?>"><?php echo get_lang('SaveScoringRules') ?></button>
+        <button class="save" type="submit" name="name" value="<?php echo get_lang('Save') ?>">
+            <?php echo get_lang('SaveScoringRules') ?>
+        </button>
     </form>
 <?php
 Display :: display_footer();

+ 53 - 9
main/gradebook/gradebook_flatview.php

@@ -24,14 +24,24 @@ require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.
 require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
 
 api_block_anonymous_users();
-block_students();
+$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+    api_get_user_id(),
+    api_get_course_info()
+);
+
+if (!$isDrhOfCourse) {
+    block_students();
+}
 
 if (isset ($_POST['submit']) && isset ($_POST['keyword'])) {
     header('Location: '.api_get_self().'?selectcat='.Security::remove_XSS($_GET['selectcat']).'&search='.Security::remove_XSS($_POST['keyword']));
     exit;
 }
 
-$interbreadcrumb[] = array ('url' => $_SESSION['gradebook_dest'].'?selectcat=1', 'name' => get_lang('ToolGradebook'));
+$interbreadcrumb[] = array(
+    'url' => $_SESSION['gradebook_dest'].'?selectcat=1',
+    'name' => get_lang('ToolGradebook')
+);
 
 $showeval = isset($_POST['showeval']) ? '1' : '0';
 $showlink = isset($_POST['showlink']) ? '1' : '0';
@@ -101,7 +111,14 @@ if (!empty($keyword)) {
 $offset = isset($_GET['offset']) ? $_GET['offset'] : '0';
 
 // Main course category
-$mainCourseCategory = Category::load(null, null, api_get_course_id(), null, null, api_get_session_id());
+$mainCourseCategory = Category::load(
+    null,
+    null,
+    api_get_course_id(),
+    null,
+    null,
+    api_get_session_id()
+);
 
 $flatviewtable = new FlatViewTable(
     $cat[0],
@@ -125,7 +142,15 @@ if (isset($_GET['export_pdf']) && $_GET['export_pdf'] == 'category') {
     $params['export_pdf'] = true;
     if ($cat[0]->is_locked() == true || api_is_platform_admin()) {
         Display :: set_header(null, false, false);
-        export_pdf_flatview($flatviewtable, $cat, $users, $alleval, $alllinks, $params, $mainCourseCategory[0]);
+        export_pdf_flatview(
+            $flatviewtable,
+            $cat,
+            $users,
+            $alleval,
+            $alllinks,
+            $params,
+            $mainCourseCategory[0]
+        );
     }
 }
 
@@ -139,7 +164,7 @@ if (isset($_GET['exportpdf']))	{
         DataForm::TYPE_EXPORT_PDF,
         'export_pdf_form',
         null,
-        api_get_self() . '?exportpdf=&offset=' . intval($_GET['offset']) . '&selectcat=' . intval($_GET['selectcat']),
+        api_get_self() . '?exportpdf=&offset=' . intval($_GET['offset']) . '&selectcat=' . intval($_GET['selectcat']).'&'.api_get_cidreq(),
         '_blank',
         ''
     );
@@ -151,7 +176,15 @@ if (isset($_GET['exportpdf']))	{
         $params['show_official_code'] = true;
         $params['export_pdf'] = true;
         $params['only_total_category'] = false;
-        export_pdf_flatview($flatviewtable, $cat, $users, $alleval, $alllinks, $params, $mainCourseCategory[0]);
+        export_pdf_flatview(
+            $flatviewtable,
+            $cat,
+            $users,
+            $alleval,
+            $alllinks,
+            $params,
+            $mainCourseCategory[0]
+        );
 
     } else {
         Display :: display_header(get_lang('ExportPDF'));
@@ -177,7 +210,7 @@ if (isset($_GET['print']))	{
 }
 
 if (!empty($_GET['export_report']) && $_GET['export_report'] == 'export_report') {
-    if (api_is_platform_admin() || api_is_course_admin() || api_is_course_coach()) {
+    if (api_is_platform_admin() || api_is_course_admin() || api_is_course_coach() || $isDrhOfCourse) {
         $user_id = null;
 
         if (empty($_SESSION['export_user_fields'])) {
@@ -233,10 +266,21 @@ if (isset($_GET['exportpdf'])) {
 }
 
 if (isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'false') {
-    DisplayGradebook :: display_header_reduce_flatview($cat[0], $showeval, $showlink, $simple_search_form);
+    DisplayGradebook:: display_header_reduce_flatview(
+        $cat[0],
+        $showeval,
+        $showlink,
+        $simple_search_form
+    );
     $flatviewtable->display();
 } elseif (isset($_GET['selectcat']) && ($_SESSION['studentview'] == 'teacherview')) {
-    DisplayGradebook :: display_header_reduce_flatview($cat[0], $showeval, $showlink, $simple_search_form);
+
+    DisplayGradebook:: display_header_reduce_flatview(
+        $cat[0],
+        $showeval,
+        $showlink,
+        $simple_search_form
+    );
 
     // main graph
     $flatviewtable->display();

+ 43 - 7
main/gradebook/gradebook_view_result.php

@@ -25,8 +25,14 @@ require_once api_get_path(LIBRARY_PATH) . 'ezpdf/class.ezpdf.php';
 require_once api_get_path(SYS_CODE_PATH) . 'gradebook/lib/gradebook_functions.inc.php';
 
 api_block_anonymous_users();
+$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+    api_get_user_id(),
+    api_get_course_info()
+);
 
-block_students();
+if (!$isDrhOfCourse) {
+    block_students();
+}
 
 $interbreadcrumb[] = array(
     'url' => $_SESSION['gradebook_dest'],
@@ -66,7 +72,15 @@ if (isset($_GET['editres'])) {
     $edit_res_xml = Security::remove_XSS($_GET['editres']);
     $select_eval_edit = Security::remove_XSS($_GET['selecteval']);
     $resultedit = Result :: load($edit_res_xml);
-    $edit_res_form = new EvalForm(EvalForm :: TYPE_RESULT_EDIT, $eval[0], $resultedit[0], 'edit_result_form', null, api_get_self() . '?editres=' . $resultedit[0]->get_id() . '&selecteval=' . $select_eval_edit);
+    $edit_res_form = new EvalForm(
+        EvalForm :: TYPE_RESULT_EDIT,
+        $eval[0],
+        $resultedit[0],
+        'edit_result_form',
+        null,
+        api_get_self() . '?editres=' . $resultedit[0]->get_id(
+        ) . '&selecteval=' . $select_eval_edit
+    );
     if ($edit_res_form->validate()) {
 
         $values = $edit_res_form->exportValues();
@@ -88,9 +102,15 @@ if (isset($_GET['editres'])) {
 }
 
 if (isset($_GET['import'])) {
-
     $interbreadcrumb[] = array('url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']), 'name' => get_lang('ViewResult'));
-    $import_result_form = new DataForm(DataForm :: TYPE_IMPORT, 'import_result_form', null, api_get_self() . '?import=&selecteval=' . Security::remove_XSS($_GET['selecteval']), '_blank', '');
+    $import_result_form = new DataForm(
+        DataForm :: TYPE_IMPORT,
+        'import_result_form',
+        null,
+        api_get_self() . '?import=&selecteval=' . Security::remove_XSS($_GET['selecteval']),
+        '_blank',
+        ''
+    );
     if (!$import_result_form->validate()) {
         Display :: display_header(get_lang('Import'));
     }
@@ -135,7 +155,10 @@ if (isset($_GET['import'])) {
                     exit;
                 }
                 $userinfo = get_user_info_from_id($importedresult['user_id']);
-                if ($userinfo['lastname'] != $importedresult['lastname'] || $userinfo['firstname'] != $importedresult['firstname'] || $userinfo['official_code'] != $importedresult['official_code']) {
+                if ($userinfo['lastname'] != $importedresult['lastname'] ||
+                    $userinfo['firstname'] != $importedresult['firstname'] ||
+                    $userinfo['official_code'] != $importedresult['official_code']
+                ) {
                     if (!isset($values['ignoreerrors'])) {
                         header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&import_user_error=' . $importedresult['user_id']);
                         exit;
@@ -181,7 +204,14 @@ if (isset($_GET['import'])) {
 if (isset($_GET['export'])) {
     $interbreadcrumb[] = array('url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']), 'name' => get_lang('ViewResult'));
     $locked_status = $eval[0]->get_locked();
-    $export_result_form = new DataForm(DataForm :: TYPE_EXPORT, 'export_result_form', null, api_get_self() . '?export=&selecteval=' . $_GET['selecteval'], '_blank', $locked_status);
+    $export_result_form = new DataForm(
+        DataForm :: TYPE_EXPORT,
+        'export_result_form',
+        null,
+        api_get_self() . '?export=&selecteval=' . $_GET['selecteval'],
+        '_blank',
+        $locked_status
+    );
     if (!$export_result_form->validate()) {
         Display :: display_header(get_lang('Export'));
     }
@@ -291,7 +321,13 @@ if (isset($_GET['export'])) {
                 }
                 $data_table[] = $result;
             }
-            export_pdf_with_html($head_table, $data_table, $header_pdf, $footer_pdf, $title_pdf);
+            export_pdf_with_html(
+                $head_table,
+                $data_table,
+                $header_pdf,
+                $footer_pdf,
+                $title_pdf
+            );
         }
 
         // export results to xml or csv file

+ 38 - 17
main/gradebook/index.php

@@ -9,7 +9,7 @@ $language_file = array('gradebook', 'exercice');
 
 // $cidReset : This is the main difference with gradebook.php, here we say,
 // basically, that we are inside a course, and many things depend from that
-$cidReset= false;
+//$cidReset = false;
 $_in_course = true;
 require_once '../inc/global.inc.php';
 $current_course_tool  = TOOL_GRADEBOOK;
@@ -612,11 +612,11 @@ if (isset ($move_form)){
 
 // LOAD DATA & DISPLAY TABLE
 
-$is_platform_admin  = api_is_platform_admin();
-$is_course_admin    = api_is_allowed_to_edit(null, true);
+$is_platform_admin = api_is_platform_admin();
+$is_course_admin = api_is_allowed_to_edit(null, true);
 
 //load data for category, evaluation and links
-if (empty ($_GET['selectcat'])) {
+if (empty($_GET['selectcat'])) {
     $category= 0;
 } else {
     $category= $_GET['selectcat'];
@@ -702,7 +702,7 @@ if (isset($_GET['studentoverview'])) {
         }
         unset($cats);
     }
-    $cats = Category :: load ($category, null, null, null, null, null, false);
+    $cats = Category::load($category, null, null, null, null, null, false);
 
     //with this fix the teacher only can view 1 gradebook
     if (api_is_platform_admin()) {
@@ -734,7 +734,7 @@ if (isset($_GET['cidReq']) && $_GET['cidReq']!='') {
 $no_qualification = false;
 
 // Show certificate link.
-
+$certificate = array();
 if ($category != '0') {
     $cat = new Category();
     $category_id   = intval($_GET['selectcat']);
@@ -744,9 +744,14 @@ if ($category != '0') {
     if ($show_message == '') {
         // Student
         if (!api_is_allowed_to_edit()) {
-            $certificate_html = Category::register_user_certificate($category_id, $stud_id);
-            if ($certificate_html) {
-                echo $certificate_html;
+            $certificate = Category::register_user_certificate(
+                $category_id,
+                $stud_id
+            );
+            if (!empty($certificate)) {
+                echo '<div class="actions" align="right">';
+                echo $certificate['pdf_link'];
+                echo '</div>';
             }
         }
     }
@@ -756,11 +761,24 @@ if (api_is_allowed_to_edit(null, true)) {
     // Tool introduction
     Display::display_introduction_section(TOOL_GRADEBOOK, array('ToolbarSet' => 'AssessmentsIntroduction'));
 
-    if ( (isset ($_GET['selectcat']) && $_GET['selectcat']<>0)) {
+    if ((isset ($_GET['selectcat']) && $_GET['selectcat']<>0)) {
         //
     } else {
-        if (((isset ($_GET['selectcat']) && $_GET['selectcat']==0) || ((isset($_GET['cidReq']) && $_GET['cidReq']!==''))) || isset($_GET['isStudentView']) && $_GET['isStudentView']=='false') {
-            $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
+        if ((
+                (isset ($_GET['selectcat']) && $_GET['selectcat'] == 0) || (
+                (isset($_GET['cidReq']) && $_GET['cidReq'] !== ''))
+            ) ||
+            isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'false'
+        ) {
+            $cats = Category:: load(
+                null,
+                null,
+                $course_code,
+                null,
+                null,
+                $session_id,
+                false
+            );
         }
     }
 }
@@ -772,10 +790,11 @@ if (isset($first_time) && $first_time==1 && api_is_allowed_to_edit(null,true)) {
 
     if (!empty($cats)) {
         if ((api_get_setting('gradebook_enable_grade_model') == 'true') &&
-            (api_is_platform_admin() || (api_is_allowed_to_edit(null, true) &&
-                    api_get_setting('teachers_can_change_grade_model_settings') == 'true'))
+            (
+                api_is_platform_admin() || (api_is_allowed_to_edit(null, true) &&
+                api_get_setting('teachers_can_change_grade_model_settings') == 'true')
+            )
         ) {
-
             // Getting grade models.
             $obj = new GradeModel();
             $grade_models = $obj->get_all();
@@ -815,7 +834,7 @@ if (isset($first_time) && $first_time==1 && api_is_allowed_to_edit(null,true)) {
 
                             $gradebook->save($params);
                         }
-                        //Reloading cats
+                        // Reloading cats
                         $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
                     } else {
                         $form_grade->display();
@@ -837,6 +856,7 @@ if (isset($first_time) && $first_time==1 && api_is_allowed_to_edit(null,true)) {
             } else {
                 // This is the father
                 // Create gradebook/add gradebook links.
+
                 DisplayGradebook::display_header_gradebook(
                     $cat,
                     0,
@@ -845,7 +865,8 @@ if (isset($first_time) && $first_time==1 && api_is_allowed_to_edit(null,true)) {
                     $is_platform_admin,
                     $simple_search_form,
                     false,
-                    true
+                    true,
+                    $certificate
                 );
 
                 if (api_is_allowed_to_edit(null,true) &&

+ 33 - 17
main/gradebook/lib/be/abstractlink.class.php

@@ -198,9 +198,9 @@ abstract class AbstractLink implements GradebookItem
         }
         if (isset ($course_code)) {
             if ($paramcount != 0) {
-             $sql .= ' AND';
+                $sql .= ' AND';
             } else {
-             $sql .= ' WHERE';
+                $sql .= ' WHERE';
             }
             $sql .= " course_code = '".Database::escape_string($course_code)."'";
             $paramcount ++;
@@ -218,7 +218,7 @@ abstract class AbstractLink implements GradebookItem
             if ($paramcount != 0) {
                 $sql .= ' AND';
             } else {
-                 $sql .= ' WHERE';
+                $sql .= ' WHERE';
             }
             $sql .= ' visible = '.intval($visible);
         }
@@ -300,9 +300,9 @@ abstract class AbstractLink implements GradebookItem
     /**
      * Update the properties of this link in the database
      */
-    public function save() {
+    public function save()
+    {
         $this->save_linked_data();
-
         $tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
         $sql = "UPDATE $tbl_grade_links SET
                     type        = ".intval($this->get_type()).",
@@ -322,7 +322,7 @@ abstract class AbstractLink implements GradebookItem
     /**
      * @param int $idevaluation
      */
-    public function add_link_log($idevaluation)
+    public static function add_link_log($idevaluation)
     {
         $tbl_grade_linkeval_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
         $dateobject=AbstractLink::load ($idevaluation,null,null,null,null);
@@ -345,7 +345,8 @@ abstract class AbstractLink implements GradebookItem
     /**
      * Delete this link from the database
      */
-    public function delete() {
+    public function delete()
+    {
         $this->delete_linked_data();
         $tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
         $sql = 'DELETE FROM '.$tbl_grade_links.' WHERE id = '.intval($this->id);
@@ -361,7 +362,6 @@ abstract class AbstractLink implements GradebookItem
     public function get_target_categories()
     {
         // links can only be moved to categories inside this course
-
         $targets = array();
         $level = 0;
 
@@ -416,22 +416,26 @@ abstract class AbstractLink implements GradebookItem
                 $foundlinks[] = $link;
             }
         }
+
         return $foundlinks;
     }
 
-
-    // Other methods implementing GradebookItem
+    /**
+     * @return string
+     */
     public function get_item_type()
     {
         return 'L';
     }
 
-    public function get_icon_name() {
+    /**
+     * @return string
+     */
+    public function get_icon_name()
+    {
         return 'link';
     }
 
-    // ABSTRACT FUNCTIONS - to be implemented by subclass
-
     abstract function has_results();
     abstract function get_link();
     abstract function is_valid_link();
@@ -469,19 +473,31 @@ abstract class AbstractLink implements GradebookItem
     {
     }
 
+    /**
+     *
+     */
     public function delete_linked_data()
     {
     }
 
-    public function set_name ($name)
+    /**
+     * @param $name
+     */
+    public function set_name($name)
     {
     }
 
-    public function set_description ($description)
+    /**
+     * @param $description
+     */
+    public function set_description($description)
     {
     }
 
-    public function set_max ($max)
+    /**
+     * @param $max
+     */
+    public function set_max($max)
     {
     }
 
@@ -495,7 +511,7 @@ abstract class AbstractLink implements GradebookItem
      * @param int locked 1 or unlocked 0
      *
      * */
-    function lock($locked)
+    public function lock($locked)
     {
         $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
         $sql = "UPDATE $table SET locked = '".intval($locked)."' WHERE id='".$this->id."'";

+ 150 - 145
main/gradebook/lib/be/attendancelink.class.php

@@ -5,45 +5,43 @@
  * @author Christian Fasanando (christian1827@gmail.com)
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class AttendanceLink extends AbstractLink
 {
+	private $attendance_table = null;
+	private $itemprop_table = null;
 
-    // INTERNAL VARIABLES
-    private $attendance_table = null;
-    private $itemprop_table = null;
-
-    // CONSTRUCTORS
-    function __construct() {
-    	parent::__construct();
-    	$this->set_type(LINK_ATTENDANCE);    	
-    }
+	/**
+	 * Constructor
+	 */
+	public function __construct()
+	{
+		parent::__construct();
+		$this->set_type(LINK_ATTENDANCE);
+	}
 
-    public function get_type_name() {
-    	return get_lang('Attendance');
-    }
+	public function get_type_name()
+	{
+		return get_lang('Attendance');
+	}
 
-	public function is_allowed_to_change_name() {
+	public function is_allowed_to_change_name()
+	{
 		return false;
 	}
 
-    // FUNCTIONS IMPLEMENTING ABSTRACTLINK
-
 	/**
 	 * Generate an array of attendances that a teacher hasn't created a link for.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
-     * @todo seems to be depracated
+	 * @todo seems to be depracated
 	 */
-    public function get_not_created_links() {
-        return false;
-    	if (empty($this->course_code)) {
-    		die('Error in get_not_created_links() : course code not set');
-    	}
-    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
-    	
+	public function get_not_created_links()
+	{
+		return false;
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+
 		$sql = 'SELECT att.id, att.name, att.attendance_qualify_title
 				FROM '.$this->get_attendance_table().' att
 				WHERE att.c_id = '.$this->course_id.' AND att.id NOT IN (SELECT ref_id FROM '.$tbl_grade_links.' WHERE type = '.LINK_ATTENDANCE.' AND course_code = "'.Database::escape_string($this->get_course_code()).'")
@@ -59,37 +57,38 @@ class AttendanceLink extends AbstractLink
 			}
 		}
 		return $cats;
-    }
+	}
 
 	/**
 	 * Generate an array of all attendances available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links() {
-    	if (empty($this->course_code)) {
-    		die('Error in get_not_created_links() : course code not set');
-    	}
-    	$tbl_attendance = $this->get_attendance_table();
-        $session_id = api_get_session_id();
-        
-    	/*
+	public function get_all_links()
+	{
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_attendance = $this->get_attendance_table();
+		$session_id = api_get_session_id();
+
+		/*
         if (empty($session_id)) {
             $session_condition = api_get_session_condition(0, true);
         } else {
             $session_condition = api_get_session_condition($session_id, true, true);
-        }       
-        
-    	$sql = 'SELECT att.id, att.name, att.attendance_qualify_title 
-    			FROM '.$tbl_attendance.' att 
-    			WHERE att.c_id = '.$this->course_id.' AND att.active = 1 '.$session_condition;*/
-                
-    	$sql = 'SELECT att.id, att.name, att.attendance_qualify_title 
-    			FROM '.$tbl_attendance.' att 
-    			WHERE att.c_id = '.$this->course_id.' AND att.active = 1 AND att.session_id = '.$session_id;        
-        
-                
+        }
+
+        $sql = 'SELECT att.id, att.name, att.attendance_qualify_title
+                FROM '.$tbl_attendance.' att
+                WHERE att.c_id = '.$this->course_id.' AND att.active = 1 '.$session_condition;*/
+
+		$sql = 'SELECT att.id, att.name, att.attendance_qualify_title
+    			FROM '.$tbl_attendance.' att
+    			WHERE att.c_id = '.$this->course_id.' AND att.active = 1 AND att.session_id = '.$session_id;
+
+
 		$result = Database::query($sql);
-        
+
 		while ($data=Database::fetch_array($result)) {
 			if (isset($data['attendance_qualify_title']) && $data['attendance_qualify_title'] != ''){
 				$cats[] = array ($data['id'], $data['attendance_qualify_title']);
@@ -99,50 +98,56 @@ class AttendanceLink extends AbstractLink
 		}
 		$my_cats = isset($cats)?$cats:null;
 		return $my_cats;
-    }
+	}
 
 
-    /**
-     * Has anyone done this exercise yet ?
-     */
-    public function has_results() {    	
-    	$tbl_attendance_result = Database :: get_course_table(TABLE_ATTENDANCE_RESULT);
-        $session_id = api_get_session_id();
-		$sql = 'SELECT count(*) AS number FROM '.$tbl_attendance_result." 
+	/**
+	 * Has anyone done this exercise yet ?
+	 */
+	public function has_results()
+	{
+		$tbl_attendance_result = Database :: get_course_table(TABLE_ATTENDANCE_RESULT);
+		$session_id = api_get_session_id();
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_attendance_result."
 				WHERE session_id = $session_id AND c_id = '.$this->course_id.' AND attendance_id = '".intval($this->get_ref_id())."'";
-    	$result = Database::query($sql);
+		$result = Database::query($sql);
 		$number = Database::fetch_row($result);
 		return ($number[0] != 0);
-    }
+	}
 
-  	public function calc_score($stud_id = null) {    	    	
+	/**
+	 * @param int $stud_id
+	 * @return array|null
+	 */
+	public function calc_score($stud_id = null)
+	{
 		$tbl_attendance_result = Database::get_course_table(TABLE_ATTENDANCE_RESULT);
 		$session_id = api_get_session_id();
 
 		// get attendance qualify max
-  		$sql = 'SELECT att.attendance_qualify_max FROM '.$this->get_attendance_table().' att 
+		$sql = 'SELECT att.attendance_qualify_max FROM '.$this->get_attendance_table().' att
   				WHERE att.c_id = '.$this->course_id.' AND att.id = '.intval($this->get_ref_id()).' AND att.session_id='.intval($session_id).'';
 		$query = Database::query($sql);
 		$attendance = Database::fetch_array($query);
 
 		// get results
-  	    $sql = 'SELECT * FROM '.$tbl_attendance_result.' 
+		$sql = 'SELECT * FROM '.$tbl_attendance_result.'
   	    		WHERE c_id = '.$this->course_id.' AND attendance_id = '.intval($this->get_ref_id());
-    	if (isset($stud_id)) {
-    		$sql .= ' AND user_id = '.intval($stud_id);
-    	}
-    	$scores = Database::query($sql);
+		if (isset($stud_id)) {
+			$sql .= ' AND user_id = '.intval($stud_id);
+		}
+		$scores = Database::query($sql);
 		// for 1 student
-    	if (isset($stud_id)) {    		
-    		if ($data = Database::fetch_array($scores)) {
-    			return array ($data['score'], $attendance['attendance_qualify_max']);
-    		} else {
-    			//We sent the 0/attendance_qualify_max instead of null for correct calculations
-      			return array (0, $attendance['attendance_qualify_max']);
-    		}
-    	} else {// all students -> get average
-    		$students=array();  // user list, needed to make sure we only
-    							// take first attempts into account
+		if (isset($stud_id)) {
+			if ($data = Database::fetch_array($scores)) {
+				return array ($data['score'], $attendance['attendance_qualify_max']);
+			} else {
+				//We sent the 0/attendance_qualify_max instead of null for correct calculations
+				return array (0, $attendance['attendance_qualify_max']);
+			}
+		} else {// all students -> get average
+			$students=array();  // user list, needed to make sure we only
+			// take first attempts into account
 			$rescount = 0;
 			$sum = 0;
 			while ($data=Database::fetch_array($scores)) {
@@ -156,81 +161,81 @@ class AttendanceLink extends AbstractLink
 			}
 			if ($rescount == 0) {
 				return null;
-			  } else {
+			} else {
 				return array ($sum , $rescount);
-			 }
-    	}		
-    }
+			}
+		}
+	}
 
 	// INTERNAL FUNCTIONS
 
-    /**
-     * Lazy load function to get the database table of the student publications
-     */
-    private function get_attendance_table() {
-    	$this->attendance_table = Database :: get_course_table(TABLE_ATTENDANCE);
-    	return $this->attendance_table;
-    }
-
-    /**
-     * Lazy load function to get the database table of the item properties
-     */
-    private function get_itemprop_table () {    	
-    	$this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-   		return $this->itemprop_table;
-    }
-
-   	public function needs_name_and_description() {
+	/**
+	 * Lazy load function to get the database table of the student publications
+	 */
+	private function get_attendance_table() {
+		$this->attendance_table = Database :: get_course_table(TABLE_ATTENDANCE);
+		return $this->attendance_table;
+	}
+
+	/**
+	 * Lazy load function to get the database table of the item properties
+	 */
+	private function get_itemprop_table () {
+		$this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+		return $this->itemprop_table;
+	}
+
+	public function needs_name_and_description() {
+		return false;
+	}
+	public function needs_max() {
 		return false;
 	}
-    public function needs_max() {
-        return false;
-    }
-
-    public function needs_results() {
-        return false;
-    }
-
-    public function get_name() {
-    	$this->get_attendance_data();
-    	$attendance_title = isset($this->attendance_data['name']) ? $this->attendance_data['name'] : '';
-    	$attendance_qualify_title = isset($this->attendance_data['attendance_qualify_title']) ? $this->attendance_data['attendance_qualify_title'] : '';
-    	if ( isset($attendance_qualify_title) && $attendance_qualify_title != '') {
-    		return $this->attendance_data['attendance_qualify_title'];
-    	} else {
-    		return $attendance_title;
-    	}
-    }
-
-    public function get_description() {
-    	return '';
-    }
-    /**
-     * Check if this still links to an exercise
-     */
-    public function is_valid_link() {
-    	$session_id = api_get_session_id();
-        $sql = 'SELECT count(att.id) FROM '.$this->get_attendance_table().' att
+
+	public function needs_results() {
+		return false;
+	}
+
+	public function get_name() {
+		$this->get_attendance_data();
+		$attendance_title = isset($this->attendance_data['name']) ? $this->attendance_data['name'] : '';
+		$attendance_qualify_title = isset($this->attendance_data['attendance_qualify_title']) ? $this->attendance_data['attendance_qualify_title'] : '';
+		if ( isset($attendance_qualify_title) && $attendance_qualify_title != '') {
+			return $this->attendance_data['attendance_qualify_title'];
+		} else {
+			return $attendance_title;
+		}
+	}
+
+	public function get_description() {
+		return '';
+	}
+	/**
+	 * Check if this still links to an exercise
+	 */
+	public function is_valid_link() {
+		$session_id = api_get_session_id();
+		$sql = 'SELECT count(att.id) FROM '.$this->get_attendance_table().' att
         		 WHERE att.c_id = '.$this->course_id.' AND att.id = '.intval($this->get_ref_id()).' ';
-        $result = Database::query($sql);
-        $number = Database::fetch_row($result);
-        return ($number[0] != 0);
-    }
-
-    public function get_test_id() {
-    	return 'DEBUG:ID';
-    }
-
-    public function get_link() {
-    	//it was extracts the attendance id   		
-   		$session_id = api_get_session_id();   		
-    	$sql = 'SELECT * FROM '.$this->get_attendance_table().' att
+		$result = Database::query($sql);
+		$number = Database::fetch_row($result);
+		return ($number[0] != 0);
+	}
+
+	public function get_test_id() {
+		return 'DEBUG:ID';
+	}
+
+	public function get_link() {
+		//it was extracts the attendance id
+		$session_id = api_get_session_id();
+		$sql = 'SELECT * FROM '.$this->get_attendance_table().' att
     			WHERE att.c_id = '.$this->course_id.' AND att.id = '.intval($this->get_ref_id()).' ';
 		$result = Database::query($sql);
 		$row    = Database::fetch_array($result,'ASSOC');
 		$attendance_id = $row['id'];
-    	$url = api_get_path(WEB_PATH).'main/attendance/index.php?action=attendance_sheet_list&gradebook=view&attendance_id='.$attendance_id.'&session_id='.$session_id.'&cidReq='.$this->get_course_code();
-		return $url;   		
+		$url = api_get_path(WEB_PATH).'main/attendance/index.php?action=attendance_sheet_list&gradebook=view&attendance_id='.$attendance_id.'&session_id='.$session_id.'&cidReq='.$this->get_course_code();
+		return $url;
 	}
 
 	private function get_attendance_data() {
@@ -239,15 +244,15 @@ class AttendanceLink extends AbstractLink
 		if ($tbl_name == '') {
 			return false;
 		} elseif (!isset($this->attendance_data)) {
-			$sql = 'SELECT * FROM '.$this->get_attendance_table().' att 
+			$sql = 'SELECT * FROM '.$this->get_attendance_table().' att
 					WHERE att.c_id = '.$this->course_id.' AND att.id = '.intval($this->get_ref_id()).' ';
 			$query = Database::query($sql);
 			$this->attendance_data = Database::fetch_array($query);
-    	}
-    	return $this->attendance_data;
-    }
+		}
+		return $this->attendance_data;
+	}
 
-    public function get_icon_name() {
+	public function get_icon_name() {
 		return 'attendance';
 	}
-}
+}

+ 172 - 86
main/gradebook/lib/be/category.class.php

@@ -10,7 +10,6 @@ require_once api_get_path(LIBRARY_PATH).'grade_model.lib.php';
  * Defines a gradebook Category object
  * @package chamilo.gradebook
  */
-
 class Category implements GradebookItem
 {
     private $id;
@@ -30,8 +29,6 @@ class Category implements GradebookItem
     {
     }
 
-    // GETTERS AND SETTERS
-
     public function get_id()
     {
         return $this->id;
@@ -205,11 +202,12 @@ class Category implements GradebookItem
         $session_id = intval($session_id);
 
         if (!empty($session_id)) {
-             $tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-             $sql = 'SELECT id, course_code FROM '.$tbl_grade_categories. '
-                     WHERE session_id = '.$session_id;
-             $result_session = Database::query($sql);
-             if (Database::num_rows($result_session) > 0) {
+            $tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+            $sql = 'SELECT id, course_code
+                    FROM '.$tbl_grade_categories. '
+                    WHERE session_id = '.$session_id;
+            $result_session = Database::query($sql);
+            if (Database::num_rows($result_session) > 0) {
                 $categoryList = array();
                 while ($data_session = Database::fetch_array($result_session)) {
                     $parent_id = $data_session['id'];
@@ -219,20 +217,21 @@ class Category implements GradebookItem
                         //$allSubCategories = Category::load(null,null,null, $parent_id, null, $session_id, null);
                     }
                 }
+
                 return $categoryList;
-             }
+            }
         }
     }
 
     /**
      * Retrieve categories and return them as an array of Category objects
-     * @param int      category id
-     * @param int      user id (category owner)
-     * @param string   course code
-     * @param int      parent category
-     * @param bool     visible
-     * @param int      session id (in case we are in a session)
-     * @param bool     Whether to show all "session" categories (true) or hide them (false) in case there is no session id
+     * @param int      $id category id
+     * @param int      $user_id (category owner)
+     * @param string   $course_code
+     * @param int      $parent_id parent category
+     * @param bool     $visible
+     * @param int      $session_id (in case we are in a session)
+     * @param bool     $order_by Whether to show all "session" categories (true) or hide them (false) in case there is no session id
      */
     public static function load(
         $id = null,
@@ -256,7 +255,6 @@ class Category implements GradebookItem
         $sql = 'SELECT * FROM '.$tbl_grade_categories;
         $paramcount = 0;
         if (isset($id)) {
-            $id = Database::escape_string($id);
             $sql.= ' WHERE id = '.intval($id);
             $paramcount ++;
         }
@@ -273,7 +271,6 @@ class Category implements GradebookItem
         }
 
         if (isset($course_code)) {
-            $course_code = Database::escape_string($course_code);
             if ($paramcount != 0) {
                 $sql .= ' AND';
             } else {
@@ -303,7 +300,6 @@ class Category implements GradebookItem
         }
 
         if (isset($parent_id)) {
-            $parent_id = Database::escape_string($parent_id);
             if ($paramcount != 0) {
                 $sql .= ' AND ';
             } else {
@@ -314,7 +310,6 @@ class Category implements GradebookItem
         }
 
         if (isset($visible)) {
-            $visible = Database::escape_string($visible);
             if ($paramcount != 0) {
                 $sql .= ' AND';
             } else {
@@ -338,7 +333,10 @@ class Category implements GradebookItem
         return $allcat;
     }
 
-    private function create_root_category()
+    /**
+     * @return Category
+     */
+    private static function create_root_category()
     {
         $cat = new Category();
         $cat->set_id(0);
@@ -349,9 +347,14 @@ class Category implements GradebookItem
         $cat->set_parent_id(null);
         $cat->set_weight(0);
         $cat->set_visible(1);
+
         return $cat;
     }
 
+    /**
+     * @param $result
+     * @return array
+     */
     private static function create_category_objects_from_sql_result($result)
     {
         $allcat = array();
@@ -394,7 +397,7 @@ class Category implements GradebookItem
                 $sql .= ',course_code';
             }
             if (isset($this->parent)) {
-                 $sql .= ',parent_id';
+                $sql .= ',parent_id';
             }
             if (!empty($this->session_id)) {
                 $sql .= ', session_id';
@@ -419,9 +422,9 @@ class Category implements GradebookItem
             $visible = intval($this->is_visible());
 
             $sql .= ") VALUES ('".Database::escape_string($this->get_name())."'"
-                    .','.intval($this->get_user_id())
-                    .','.Database::escape_string($this->get_weight())
-                    .','.$visible;
+                .','.intval($this->get_user_id())
+                .','.Database::escape_string($this->get_weight())
+                .','.$visible;
             if (isset($this->description)) {
                 $sql .= ",'".Database::escape_string($this->get_description())."'";
             }
@@ -429,7 +432,7 @@ class Category implements GradebookItem
                 $sql .= ",'".Database::escape_string($this->get_course_code())."'";
             }
             if (isset($this->parent)) {
-                 $sql .= ','.intval($this->get_parent_id());
+                $sql .= ','.intval($this->get_parent_id());
             }
             if (!empty($this->session_id)) {
                 $sql .= ', '.intval($this->get_session_id());
@@ -658,8 +661,8 @@ class Category implements GradebookItem
         }
         $tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
         $sql = 'SELECT count(id) AS number'
-             .' FROM '.$tbl_grade_categories
-             ." WHERE name = '".Database::escape_string($name)."'";
+            .' FROM '.$tbl_grade_categories
+            ." WHERE name = '".Database::escape_string($name)."'";
 
         if (api_is_allowed_to_edit()) {
             $parent = Category::load($parent);
@@ -667,10 +670,10 @@ class Category implements GradebookItem
             if (isset($code) && $code != '0') {
                 $main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
                 $sql .= ' AND user_id IN ('
-                        .' SELECT user_id FROM '.$main_course_user_table
-                        ." WHERE course_code = '".Database::escape_string($code)."'"
-                        .' AND status = '.COURSEMANAGER
-                        .')';
+                    .' SELECT user_id FROM '.$main_course_user_table
+                    ." WHERE course_code = '".Database::escape_string($code)."'"
+                    .' AND status = '.COURSEMANAGER
+                    .')';
             } else {
                 $sql .= ' AND user_id = '.api_get_user_id();
             }
@@ -842,8 +845,8 @@ class Category implements GradebookItem
         $tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
 
         $sql = 'SELECT *'
-                .' FROM '.$tbl_grade_categories
-                .' WHERE parent_id = 0';
+            .' FROM '.$tbl_grade_categories
+            .' WHERE parent_id = 0';
         if (!api_is_allowed_to_edit()) {
             $sql .= ' AND visible = 1';
             //proceed with checks on optional parameters course & session
@@ -854,7 +857,7 @@ class Category implements GradebookItem
                 // could be an improvement
                 if (!empty($session_id)) {
                     $sql .= " AND course_code  = '".Database::escape_string($course_code)."'"
-                            ." AND session_id = ".(int)$session_id;
+                        ." AND session_id = ".(int)$session_id;
                 } else {
                     $sql .= " AND course_code  = '".Database::escape_string($course_code)."' AND session_id is null OR session_id=0";
                 }
@@ -882,11 +885,11 @@ class Category implements GradebookItem
                 }
             } else {
                 $sql .= ' AND course_code in'
-                        .' (SELECT course_code'
-                        .' FROM '.$main_course_user_table
-                        .' WHERE user_id = '.api_get_user_id()
-                        .' AND status = '.COURSEMANAGER
-                        .')';
+                    .' (SELECT course_code'
+                    .' FROM '.$main_course_user_table
+                    .' WHERE user_id = '.api_get_user_id()
+                    .' AND status = '.COURSEMANAGER
+                    .')';
             }
         }elseif (api_is_platform_admin()) {
             if (isset($session_id) && $session_id!=0) {
@@ -900,7 +903,7 @@ class Category implements GradebookItem
 
         // course independent categories
         if (empty($course_code)) {
-          $cats = Category::get_independent_categories_with_result_for_student (0, $stud_id, $cats);
+            $cats = Category::get_independent_categories_with_result_for_student (0, $stud_id, $cats);
         }
 
         return $cats;
@@ -922,8 +925,8 @@ class Category implements GradebookItem
         $tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
 
         $sql = 'SELECT *'
-                .' FROM '.$tbl_grade_categories
-                .' WHERE parent_id = 0';
+            .' FROM '.$tbl_grade_categories
+            .' WHERE parent_id = 0';
         if (!empty($course_code)) {
             $sql .= " AND course_code = '".Database::escape_string($course_code)."' ";
             if (!empty($session_id)) {
@@ -1130,16 +1133,16 @@ class Category implements GradebookItem
         $tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
 
         $sql = 'SELECT DISTINCT(code), title FROM '.$tbl_main_courses.' cc, '.$tbl_main_course_user.' cu'
-                .' WHERE cc.code = cu.course_code'
-                .' AND cu.status = '.COURSEMANAGER;
+            .' WHERE cc.code = cu.course_code'
+            .' AND cu.status = '.COURSEMANAGER;
         if (!api_is_platform_admin()) {
-        $sql .= ' AND cu.user_id = '.$user_id;
+            $sql .= ' AND cu.user_id = '.$user_id;
         }
         $sql .= ' AND cc.code NOT IN'
-                .' (SELECT course_code FROM '.$tbl_grade_categories
-                .' WHERE parent_id = 0'
+            .' (SELECT course_code FROM '.$tbl_grade_categories
+            .' WHERE parent_id = 0'
 //                .' AND user_id = '.$user_id
-                .' AND course_code IS NOT null)';
+            .' AND course_code IS NOT null)';
         $result = Database::query($sql);
 
         $cats=array();
@@ -1159,8 +1162,8 @@ class Category implements GradebookItem
         $tbl_main_courses = Database :: get_main_table(TABLE_MAIN_COURSE);
         $tbl_main_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
         $sql = 'SELECT DISTINCT(code), title FROM '.$tbl_main_courses.' cc, '.$tbl_main_course_user.' cu'
-                .' WHERE cc.code = cu.course_code'
-                .' AND cu.status = '.COURSEMANAGER;
+            .' WHERE cc.code = cu.course_code'
+            .' AND cu.status = '.COURSEMANAGER;
         if (!api_is_platform_admin()) {
             $sql .= ' AND cu.user_id = '.intval($user_id);
         }
@@ -1278,18 +1281,18 @@ class Category implements GradebookItem
     public function get_subcategories($stud_id = null, $course_code = null, $session_id = null, $order = null)
     {
         if (!empty($session_id)) {
-             /*$tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-             $sql = 'SELECT id FROM '.$tbl_grade_categories. ' WHERE session_id = '.$session_id;
-             $result_session = Database::query($sql);
-             if (Database::num_rows($result_session) > 0) {
-                 $data_session = Database::fetch_array($result_session);
-                 $parent_id = $data_session['id'];
-                 return Category::load(null, null, null, $parent_id, null, null, $order);
-             }*/
-         }
-
-         // 1 student
-         if (isset($stud_id)) {
+            /*$tbl_grade_categories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+            $sql = 'SELECT id FROM '.$tbl_grade_categories. ' WHERE session_id = '.$session_id;
+            $result_session = Database::query($sql);
+            if (Database::num_rows($result_session) > 0) {
+                $data_session = Database::fetch_array($result_session);
+                $parent_id = $data_session['id'];
+                return Category::load(null, null, null, $parent_id, null, null, $order);
+            }*/
+        }
+
+        // 1 student
+        if (isset($stud_id)) {
             // special case: this is the root
             if ($this->id == 0) {
                 return Category::get_root_categories_for_student($stud_id, $course_code, $session_id);
@@ -1302,12 +1305,12 @@ class Category implements GradebookItem
                 // root
                 if ($this->id == 0) {
                     return $this->get_root_categories_for_teacher(api_get_user_id(), $course_code, $session_id, false);
-                // inside a course
+                    // inside a course
                 } elseif (!empty($this->course_code)) {
                     return Category::load(null, null, $this->course_code, $this->id, null, $session_id, $order);
                 } elseif (!empty($course_code)) {
                     return Category::load(null, null, $course_code, $this->id, null, $session_id, $order);
-                // course independent
+                    // course independent
                 } else {
                     return Category::load(null, api_get_user_id(), 0, $this->id, null);
                 }
@@ -1413,7 +1416,7 @@ class Category implements GradebookItem
                 $this->id,
                 api_is_allowed_to_edit() ? null : 1
             );
-         } elseif (api_is_allowed_to_edit() || api_is_drh() || api_is_session_admin()) {
+        } elseif (api_is_allowed_to_edit() || api_is_drh() || api_is_session_admin()) {
             // all students -> only for course/platform admin
             $links = LinkFactory::load(
                 null,
@@ -1451,12 +1454,11 @@ class Category implements GradebookItem
     public function getCategories($catId)
     {
         $tblGradeCategories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-        $courseInfo = api_get_course_info(api_get_course_id());
-        $courseCode = $courseInfo['code'];
         $sql='SELECT * FROM '.$tblGradeCategories.' WHERE parent_id = '.intval($catId);
 
         $result = Database::query($sql);
         $allcats = Category::create_category_objects_from_sql_result($result);
+
         return $allcats;
     }
 
@@ -1493,7 +1495,7 @@ class Category implements GradebookItem
         return 'cat';
     }
 
-     /**
+    /**
      * Find category by name
      * @param string $name_mask search string
      * @return array category objects matching the search criterium
@@ -1511,11 +1513,11 @@ class Category implements GradebookItem
     }
 
     /**
-    * This function, locks a category , only one who can unlock it is the platform administrator.
-    * @param int locked 1 or unlocked 0
+     * This function, locks a category , only one who can unlock it is the platform administrator.
+     * @param int locked 1 or unlocked 0
 
-    * @return bool
-    * */
+     * @return bool
+     * */
     public function lock($locked)
     {
         $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
@@ -1591,8 +1593,6 @@ class Category implements GradebookItem
             $score = $item->calc_score($user_id);
             $divide = ( ($score[1])==0 ) ? 1 : $score[1];
             $item_value = $score[0]/$divide*$item->get_weight();
-            /*var_dump($score[0], $divide, $item->get_weight(), $item_value);
-            echo '---';-*/
             $item_total_value += $item_value;
         }
 
@@ -1611,25 +1611,32 @@ class Category implements GradebookItem
         // A student always sees only the teacher's repartition
         $scoretotal_display = $scoredisplay->display_score($scoretotal, SCORE_DIV_PERCENT);
 
-        if (isset($certificate_min_score) && $item_total_value >= $certificate_min_score) {
+        if (isset($certificate_min_score) &&
+            $item_total_value >= $certificate_min_score
+        ) {
             $my_certificate = get_certificate_by_user_id($cats_course[0]->get_id(), $user_id);
             if (empty($my_certificate)) {
-                register_user_info_about_certificate($category_id, $user_id, $my_score_in_gradebook, api_get_utc_datetime());
+                register_user_info_about_certificate(
+                    $category_id,
+                    $user_id,
+                    $my_score_in_gradebook,
+                    api_get_utc_datetime()
+                );
                 $my_certificate = get_certificate_by_user_id($cats_course[0]->get_id(), $user_id);
             }
+            $html = array();
             if (!empty($my_certificate)) {
                 $certificate_obj = new Certificate($my_certificate['id']);
                 $fileWasGenerated = $certificate_obj->html_file_is_generated();
-                $html = null;
                 if (!empty($fileWasGenerated)) {
                     $url = api_get_path(WEB_PATH) . 'certificates/index.php?id=' . $my_certificate['id'];
                     $certificates = Display::url(
                         Display::return_icon(
-                            'certificate.png',
-                            get_lang('Certificates'),
+                            'certificate_download.png',
+                            get_lang('DownloadCertificate'),
                             array(),
-                            32
-                        ),
+                            ICON_SIZE_MEDIUM
+                        ).'&nbsp;'.get_lang('DownloadCertificate'),
                         $url,
                         array('target' => '_blank')
                     );
@@ -1638,13 +1645,14 @@ class Category implements GradebookItem
                             'pdf.png',
                             get_lang('ExportToPDF'),
                             array(),
-                            32
+                            ICON_SIZE_MEDIUM
                         ),
                         "$url&action=export"
                     );
-                    $html = '<div class="actions" align="right">';
-                    $html .= $certificates . $exportToPDF;
-                    $html .= '</div>';
+                    $html = array(
+                        'certificate_link' => $certificates,
+                        'pdf_link' => $exportToPDF
+                    );
                 }
                 return $html;
             }
@@ -1652,4 +1660,82 @@ class Category implements GradebookItem
             return false;
         }
     }
+
+    /**
+     * @param int $catId
+     * @param array $userList
+     */
+    public static function generateCertificatesInUserList($catId, $userList)
+    {
+        if (!empty($userList)) {
+            foreach ($userList as $userInfo) {
+                self::register_user_certificate($catId, $userInfo['user_id']);
+            }
+        }
+    }
+
+    /**
+     * @param int $catId
+     * @param array $userList
+     */
+    public static function exportAllCertificates(
+        $catId,
+        $userList = array()
+    ) {
+        $params['orientation'] = 'landscape';
+        $params['left'] = 0;
+        $params['right'] = 0;
+        $params['top'] = 0;
+        $params['bottom'] = 0;
+        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
+        $pdf = new PDF($page_format, $params['orientation'], $params);
+
+        $certificate_list = get_list_users_certificates($catId, $userList);
+        $certificate_path_list = array();
+
+        if (!empty($certificate_list)) {
+            foreach ($certificate_list as $index=>$value) {
+                $list_certificate = get_list_gradebook_certificates_by_user_id(
+                    $value['user_id'],
+                    $catId
+                );
+                foreach ($list_certificate as $value_certificate) {
+                    $certificate_obj = new Certificate($value_certificate['id']);
+                    $certificate_obj->generate(array('hide_print_button' => true));
+                    if ($certificate_obj->html_file_is_generated()) {
+                        $certificate_path_list[]= $certificate_obj->html_file;
+                    }
+                }
+            }
+        }
+
+        if (!empty($certificate_path_list)) {
+            // Print certificates (without the common header/footer/watermark
+            //  stuff) and return as one multiple-pages PDF
+            $pdf->html_to_pdf(
+                $certificate_path_list,
+                get_lang('Certificates'),
+                null,
+                false,
+                false
+            );
+        }
+    }
+
+    /**
+     * @param int $catId
+     */
+    public static function deleteAllCertificates($catId)
+    {
+        $certificate_list = get_list_users_certificates($catId);
+        if (!empty($certificate_list)) {
+            foreach ($certificate_list as $index=>$value) {
+                $list_certificate = get_list_gradebook_certificates_by_user_id($value['user_id'], $catId);
+                foreach ($list_certificate as $value_certificate) {
+                    $certificate_obj = new Certificate($value_certificate['id']);
+                    $certificate_obj->delete(true);
+                }
+            }
+        }
+    }
 }

+ 39 - 42
main/gradebook/lib/be/dropboxlink.class.php

@@ -1,73 +1,70 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Gradebook link to dropbox item
  * @author Bert Steppé
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class DropboxLink extends EvalLink
 {
+	private $dropbox_table = null;
 
-// INTERNAL VARIABLES
-
-    private $dropbox_table = null;
-
-// CONSTRUCTORS
-
-    function __construct() {
-    	parent::__construct();
-    	$this->set_type(LINK_DROPBOX);
-    }
-
+	/**
+	 * Constructor
+	 */
+	public function __construct()
+	{
+		parent::__construct();
+		$this->set_type(LINK_DROPBOX);
+	}
 
-    /**
-     * 
-     * Returns the URL of a document
-     * This funcion is loaded when using a gradebook as a tab (gradebook = -1) see issue #2705
-     */
 
-	public function get_view_url ($stud_id) {
+	/**
+	 *
+	 * Returns the URL of a document
+	 * This function is loaded when using a gradebook as a tab (gradebook = -1) see issue #2705
+	 */
+	public function get_view_url ($stud_id)
+	{
 		// find a file uploaded by the given student,
 		// with the same title as the evaluation name
-		
-    	$eval = $this->get_evaluation();
+
+		$eval = $this->get_evaluation();
 		$sql = 'SELECT filename FROM '.$this->get_dropbox_table()
-				.' WHERE c_id = '.$this->course_id.' AND uploader_id = '.intval($stud_id)
-				." AND title = '".Database::escape_string($eval->get_name())."'";
+			.' WHERE c_id = '.$this->course_id.' AND uploader_id = '.intval($stud_id)
+			." AND title = '".Database::escape_string($eval->get_name())."'";
 
 		$result = Database::query($sql);
 		if ($fileurl = Database::fetch_row($result)) {
-	    	$course_info = Database :: get_course_info($this->get_course_code());
-	        return null;
+			$course_info = Database :: get_course_info($this->get_course_code());
+			return null;
 		} else {
 			return null;
 		}
 	}
 
-    public function get_type_name() {
-    	return get_lang('DokeosDropbox');
-    }
+	public function get_type_name()
+	{
+		return get_lang('DokeosDropbox');
+	}
 
-	public function is_allowed_to_change_name() {
+	public function is_allowed_to_change_name()
+	{
 		return false;
 	}
 
+	/**
+	 * Lazy load function to get the dropbox database table
+	 */
+	private function get_dropbox_table()
+	{
+		$this->dropbox_table = Database :: get_course_table(TABLE_DROPBOX_FILE);
+		return $this->dropbox_table;
+	}
 
-// INTERNAL FUNCTIONS
-
-    /**
-     * Lazy load function to get the dropbox database table
-     */
-    private function get_dropbox_table () {
-    	$this->dropbox_table = Database :: get_course_table(TABLE_DROPBOX_FILE);
-   		return $this->dropbox_table;
-    }
-
-    public function get_icon_name() {
+	public function get_icon_name()
+	{
 		return 'dropbox';
 	}
 

+ 1 - 1
main/gradebook/lib/be/evallink.class.php

@@ -14,7 +14,7 @@ abstract class EvalLink extends AbstractLink
     /**
      * Constructor
      */
-    function __construct()
+    public function __construct()
     {
         parent::__construct();
     }

+ 286 - 285
main/gradebook/lib/be/evaluation.class.php

@@ -18,134 +18,134 @@ class Evaluation implements GradebookItem
 	private $eval_max;
 	private $visible;
 
-    public function __construct()
-    {
-    }
-
-    public function get_id()
-    {
-        return $this->id;
-    }
-
-    public function get_name()
-    {
-        return $this->name;
-    }
-
-    public function get_description()
-    {
-        return $this->description;
-    }
-
-    public function get_user_id()
-    {
-        return $this->user_id;
-    }
-
-    public function get_course_code()
-    {
-        return $this->course_code;
-    }
-
-    public function get_category_id()
-    {
-        return $this->category;
-    }
-
-    public function get_date()
-    {
-        return $this->created_at;
-    }
-
-    public function get_weight()
-    {
-        return $this->weight;
-    }
-
-    public function get_max()
-    {
-        return $this->eval_max;
-    }
-
-    public function get_type()
-    {
-        return $this->type;
-    }
-
-    public function is_visible()
-    {
-        return $this->visible;
-    }
-
-    public function get_locked()
-    {
-        return $this->locked;
-    }
-
-    public function is_locked()
-    {
-        return isset($this->locked) && $this->locked == 1 ? true : false;
-    }
-
-    public function set_id($id)
-    {
-        $this->id = $id;
-    }
-
-    public function set_name($name)
-    {
-        $this->name = $name;
-    }
-
-    public function set_description($description)
-    {
-        $this->description = $description;
-    }
-
-    public function set_user_id($user_id)
-    {
-        $this->user_id = $user_id;
-    }
-
-    public function set_course_code($course_code)
-    {
-        $this->course_code = $course_code;
-    }
-
-    public function set_category_id($category_id)
-    {
-        $this->category = $category_id;
-    }
-
-    public function set_date($date)
-    {
-        $this->created_at = $date;
-    }
-
-    public function set_weight($weight)
-    {
-        $this->weight = $weight;
-    }
-
-    public function set_max($max)
-    {
-        $this->eval_max = $max;
-    }
-
-    public function set_visible($visible)
-    {
-        $this->visible = $visible;
-    }
-
-    public function set_type($type)
-    {
-        $this->type = $type;
-    }
-
-    public function set_locked($locked)
-    {
-        $this->locked = $locked;
-    }
+	public function __construct()
+	{
+	}
+
+	public function get_id()
+	{
+		return $this->id;
+	}
+
+	public function get_name()
+	{
+		return $this->name;
+	}
+
+	public function get_description()
+	{
+		return $this->description;
+	}
+
+	public function get_user_id()
+	{
+		return $this->user_id;
+	}
+
+	public function get_course_code()
+	{
+		return $this->course_code;
+	}
+
+	public function get_category_id()
+	{
+		return $this->category;
+	}
+
+	public function get_date()
+	{
+		return $this->created_at;
+	}
+
+	public function get_weight()
+	{
+		return $this->weight;
+	}
+
+	public function get_max()
+	{
+		return $this->eval_max;
+	}
+
+	public function get_type()
+	{
+		return $this->type;
+	}
+
+	public function is_visible()
+	{
+		return $this->visible;
+	}
+
+	public function get_locked()
+	{
+		return $this->locked;
+	}
+
+	public function is_locked()
+	{
+		return isset($this->locked) && $this->locked == 1 ? true : false;
+	}
+
+	public function set_id($id)
+	{
+		$this->id = $id;
+	}
+
+	public function set_name($name)
+	{
+		$this->name = $name;
+	}
+
+	public function set_description($description)
+	{
+		$this->description = $description;
+	}
+
+	public function set_user_id($user_id)
+	{
+		$this->user_id = $user_id;
+	}
+
+	public function set_course_code($course_code)
+	{
+		$this->course_code = $course_code;
+	}
+
+	public function set_category_id($category_id)
+	{
+		$this->category = $category_id;
+	}
+
+	public function set_date($date)
+	{
+		$this->created_at = $date;
+	}
+
+	public function set_weight($weight)
+	{
+		$this->weight = $weight;
+	}
+
+	public function set_max($max)
+	{
+		$this->eval_max = $max;
+	}
+
+	public function set_visible($visible)
+	{
+		$this->visible = $visible;
+	}
+
+	public function set_type($type)
+	{
+		$this->type = $type;
+	}
+
+	public function set_locked($locked)
+	{
+		$this->locked = $locked;
+	}
 
 	/**
 	 * Retrieve evaluations and return them as an array of Evaluation objects
@@ -155,15 +155,15 @@ class Evaluation implements GradebookItem
 	 * @param int $category_id parent category
 	 * @param $visible visible
 	 */
-    public static function load(
-        $id = null,
-        $user_id = null,
-        $course_code = null,
-        $category_id = null,
-        $visible = null,
-        $locked = null
-    ) {
-    	$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
+	public static function load(
+		$id = null,
+		$user_id = null,
+		$course_code = null,
+		$category_id = null,
+		$visible = null,
+		$locked = null
+	) {
+		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql = 'SELECT * FROM '.$tbl_grade_evaluations;
 		$paramcount = 0;
 		if (isset ($id)) {
@@ -206,43 +206,43 @@ class Evaluation implements GradebookItem
 		return $alleval;
 	}
 
-    private static function create_evaluation_objects_from_sql_result($result)
-    {
-    	$alleval=array();
-    	if (Database::num_rows($result)) {
-    		while ($data = Database::fetch_array($result)) {
-    			$eval= new Evaluation();
-    			$eval->set_id($data['id']);
-    			$eval->set_name($data['name']);
-    			$eval->set_description($data['description']);
-    			$eval->set_user_id($data['user_id']);
-    			$eval->set_course_code($data['course_code']);
-    			$eval->set_category_id($data['category_id']);
-    			$eval->set_date(api_get_local_time($data['created_at']));
-    			$eval->set_weight($data['weight']);
-    			$eval->set_max($data['max']);
-    			$eval->set_visible($data['visible']);
-    			$eval->set_type($data['type']);
-    			$eval->set_locked($data['locked']);
-
-    			$alleval[]=$eval;
-    		}
-    	}
+	private static function create_evaluation_objects_from_sql_result($result)
+	{
+		$alleval=array();
+		if (Database::num_rows($result)) {
+			while ($data = Database::fetch_array($result)) {
+				$eval= new Evaluation();
+				$eval->set_id($data['id']);
+				$eval->set_name($data['name']);
+				$eval->set_description($data['description']);
+				$eval->set_user_id($data['user_id']);
+				$eval->set_course_code($data['course_code']);
+				$eval->set_category_id($data['category_id']);
+				$eval->set_date(api_get_local_time($data['created_at']));
+				$eval->set_weight($data['weight']);
+				$eval->set_max($data['max']);
+				$eval->set_visible($data['visible']);
+				$eval->set_type($data['type']);
+				$eval->set_locked($data['locked']);
+
+				$alleval[]=$eval;
+			}
+		}
 		return $alleval;
-    }
+	}
 
-    /**
-     * Insert this evaluation into the database
-     */
-    public function add()
-    {
+	/**
+	 * Insert this evaluation into the database
+	 */
+	public function add()
+	{
 		if (isset($this->name) && isset($this->user_id) && isset($this->weight) && isset ($this->eval_max) && isset($this->visible)) {
 			$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 
 			$sql = 'INSERT INTO '.$tbl_grade_evaluations
-					.' (name, user_id, weight, max, visible';
+				.' (name, user_id, weight, max, visible';
 			if (isset($this->description)) {
-			 $sql .= ',description';
+				$sql .= ',description';
 			}
 			if (isset($this->course_code)) {
 				$sql .= ', course_code';
@@ -253,18 +253,18 @@ class Evaluation implements GradebookItem
 			$sql .= ', created_at';
 			$sql .= ',type';
 			$sql .= ") VALUES ('".Database::escape_string($this->get_name())."'"
-					.','.intval($this->get_user_id())
-					.','.floatval($this->get_weight())
-					.','.intval($this->get_max())
-					.','.intval($this->is_visible());
+				.','.intval($this->get_user_id())
+				.','.floatval($this->get_weight())
+				.','.intval($this->get_max())
+				.','.intval($this->is_visible());
 			if (isset($this->description)) {
-				 $sql .= ",'".Database::escape_string($this->get_description())."'";
+				$sql .= ",'".Database::escape_string($this->get_description())."'";
 			}
 			if (isset($this->course_code)) {
-				 $sql .= ",'".Database::escape_string($this->get_course_code())."'";
+				$sql .= ",'".Database::escape_string($this->get_course_code())."'";
 			}
 			if (isset($this->category)) {
-				 $sql .= ','.intval($this->get_category_id());
+				$sql .= ','.intval($this->get_category_id());
 			}
 			if (empty($this->type)) {
 				$this->type = 'evaluation';
@@ -281,7 +281,7 @@ class Evaluation implements GradebookItem
 	}
 
 	public function add_evaluation_log($idevaluation)
-    {
+	{
 		if (!empty($idevaluation)) {
 			$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 			$tbl_grade_linkeval_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
@@ -304,7 +304,7 @@ class Evaluation implements GradebookItem
 	 * Update the properties of this evaluation in the database
 	 */
 	public function save()
-    {
+	{
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql = 'UPDATE '.$tbl_grade_evaluations
 			." SET name = '".Database::escape_string($this->get_name())."'"
@@ -315,7 +315,7 @@ class Evaluation implements GradebookItem
 			$sql .= 'null';
 		}
 		$sql .= ', user_id = '.intval($this->get_user_id())
-				.', course_code = ';
+			.', course_code = ';
 		if (isset($this->course_code)) {
 			$sql .= "'".Database::escape_string($this->get_course_code())."'";
 		} else {
@@ -328,9 +328,9 @@ class Evaluation implements GradebookItem
 			$sql .= 'null';
 		}
 		$sql .= ', weight = "'.Database::escape_string($this->get_weight()).'" '
-				.', max = '.Database::escape_string($this->get_max())
-				.', visible = '.intval($this->is_visible())
-				.' WHERE id = '.intval($this->id);
+			.', max = '.Database::escape_string($this->get_max())
+			.', visible = '.intval($this->is_visible())
+			.' WHERE id = '.intval($this->id);
 		//recorded history
 
 		$eval_log=new Evaluation();
@@ -342,7 +342,7 @@ class Evaluation implements GradebookItem
 	 * Delete this evaluation from the database
 	 */
 	public function delete()
-    {
+	{
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql = 'DELETE FROM '.$tbl_grade_evaluations.' WHERE id = '.intval($this->id);
 		Database::query($sql);
@@ -354,15 +354,15 @@ class Evaluation implements GradebookItem
 	 * @param $parent parent category
 	 */
 	public function does_name_exist($name, $parent)
-    {
+	{
 		if (!isset ($name)) {
 			$name = $this->name;
 			$parent = $this->category;
 		}
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql = 'SELECT count(id) AS number'
-			 .' FROM '.$tbl_grade_evaluations
-			 ." WHERE name = '".Database::escape_string($name)."'";
+			.' FROM '.$tbl_grade_evaluations
+			." WHERE name = '".Database::escape_string($name)."'";
 
 		if (api_is_allowed_to_edit()) {
 			$parent = Category::load($parent);
@@ -370,10 +370,10 @@ class Evaluation implements GradebookItem
 			if (isset($code) && $code != '0') {
 				$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 				$sql .= ' AND user_id IN ('
-						.' SELECT user_id FROM '.$main_course_user_table
-						." WHERE course_code = '".Database::escape_string($code)."'"
-						.' AND status = '.COURSEMANAGER
-						.')';
+					.' SELECT user_id FROM '.$main_course_user_table
+					." WHERE course_code = '".Database::escape_string($code)."'"
+					.' AND status = '.COURSEMANAGER
+					.')';
 			} else {
 				$sql .= ' AND user_id = '.api_get_user_id();
 			}
@@ -387,7 +387,7 @@ class Evaluation implements GradebookItem
 		} else {
 			$sql.= ' AND category_id = '.intval($parent);
 		}
-    	$result = Database::query($sql);
+		$result = Database::query($sql);
 		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
 	}
@@ -396,39 +396,39 @@ class Evaluation implements GradebookItem
 	 * Are there any results for this evaluation yet ?
 	 * The 'max' property should not be changed then.
 	 */
-    public function has_results() {
-    	$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
+	public function has_results() {
+		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql='SELECT count(id) AS number FROM '.$tbl_grade_results
 			.' WHERE evaluation_id = '.intval($this->id);
-    	$result = Database::query($sql);
+		$result = Database::query($sql);
 		$number=Database::fetch_row($result);
 
 		return ($number[0] != 0);
-    }
+	}
 
-    /**
-     * Delete all results for this evaluation
-     */
-    public function delete_results() {
+	/**
+	 * Delete all results for this evaluation
+	 */
+	public function delete_results() {
 		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql = 'DELETE FROM '.$tbl_grade_results.' WHERE evaluation_id = '.intval($this->id);
 		Database::query($sql);
-    }
-
-    /**
-     * Delete this evaluation and all underlying results.
-     */
-    public function delete_with_results(){
-    	$this->delete_results();
-    	$this->delete();
-    }
-
-    /**
-     * Check if the given score is possible for this evaluation
-     */
-    public function is_valid_score ($score) {
-    	return (is_numeric($score) && $score >= 0 && $score <= $this->eval_max);
-    }
+	}
+
+	/**
+	 * Delete this evaluation and all underlying results.
+	 */
+	public function delete_with_results(){
+		$this->delete_results();
+		$this->delete();
+	}
+
+	/**
+	 * Check if the given score is possible for this evaluation
+	 */
+	public function is_valid_score ($score) {
+		return (is_numeric($score) && $score >= 0 && $score <= $this->eval_max);
+	}
 
 	/**
 	 * Calculate the score of this evaluation
@@ -437,8 +437,8 @@ class Evaluation implements GradebookItem
 	 * 			array (sum of scores, number of scores) otherwise
 	 * 			or null if no scores available
 	 */
-    public function calc_score($stud_id = null)
-    {
+	public function calc_score($stud_id = null)
+	{
 		$results = Result::load(null, $stud_id, $this->id);
 		$rescount = 0;
 		$sum = 0;
@@ -458,9 +458,9 @@ class Evaluation implements GradebookItem
 		} else {
 			return array ($sum, $rescount);
 		}
-    }
+	}
 
-    /**
+	/**
 	 * Generate an array of possible categories where this evaluation can be moved to.
 	 * Notice: its own parent will be included in the list: it's up to the frontend
 	 * to disable this element.
@@ -499,7 +499,7 @@ class Evaluation implements GradebookItem
 	 * Internal function used by get_target_categories()
 	 */
 	private function add_target_subcategories($targets, $level, $catid)
-    {
+	{
 		$subcats = Category::load(null,null,null,$catid);
 		foreach ($subcats as $cat) {
 			$targets[] = array ($cat->get_id(), $cat->get_name(), $level+1);
@@ -515,7 +515,7 @@ class Evaluation implements GradebookItem
 	 * its course code is also changed.
 	 */
 	public function move_to_cat($cat)
-    {
+	{
 		$this->set_category_id($cat->get_id());
 		if ($this->get_course_code() != $cat->get_course_code()) {
 			$this->set_course_code($cat->get_course_code());
@@ -526,18 +526,19 @@ class Evaluation implements GradebookItem
 	/**
 	 * Retrieve evaluations where a student has results for
 	 * and return them as an array of Evaluation objects
-	 * @param $cat_id parent category (use 'null' to retrieve them in all categories)
-	 * @param $stud_id student id
+	 * @param int $cat_id parent category (use 'null' to retrieve them in all categories)
+	 * @param int $stud_id student id
 	 */
-    public function get_evaluations_with_result_for_student ($cat_id = null, $stud_id)
-    {
+	public static function get_evaluations_with_result_for_student($cat_id = null, $stud_id)
+	{
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
-    	$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
+		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 
-		$sql = 'SELECT * FROM '.$tbl_grade_evaluations
-				.' WHERE id IN'
-				.'(SELECT evaluation_id FROM '.$tbl_grade_results
-				.' WHERE user_id = '.intval($stud_id).' AND score IS NOT NULL)';
+		$sql = 'SELECT * FROM '.$tbl_grade_evaluations.'
+				WHERE id IN (
+					SELECT evaluation_id FROM '.$tbl_grade_results.'
+					WHERE user_id = '.intval($stud_id).' AND score IS NOT NULL
+				)';
 		if (!api_is_allowed_to_edit()) {
 			$sql .= ' AND visible = 1';
 		}
@@ -550,39 +551,39 @@ class Evaluation implements GradebookItem
 		$result = Database::query($sql);
 		$alleval = Evaluation::create_evaluation_objects_from_sql_result($result);
 		return $alleval;
-    }
+	}
 
-    /**
-     * Get a list of students that do not have a result record for this evaluation
-     */
-    public function get_not_subscribed_students ($first_letter_user = '')
-    {
+	/**
+	 * Get a list of students that do not have a result record for this evaluation
+	 */
+	public function get_not_subscribed_students ($first_letter_user = '')
+	{
 		$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-    	$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
+		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 
-    	$sql = 'SELECT user_id,lastname,firstname,username FROM '.$tbl_user
-				." WHERE lastname LIKE '".Database::escape_string($first_letter_user)."%'"
-				.' AND status = '.STUDENT
-				.' AND user_id NOT IN'
-				.' (SELECT user_id FROM '.$tbl_grade_results
-				.' WHERE evaluation_id = '.intval($this->id)
-				.' )'
-				.' ORDER BY lastname';
+		$sql = 'SELECT user_id,lastname,firstname,username FROM '.$tbl_user
+			." WHERE lastname LIKE '".Database::escape_string($first_letter_user)."%'"
+			.' AND status = '.STUDENT
+			.' AND user_id NOT IN'
+			.' (SELECT user_id FROM '.$tbl_grade_results
+			.' WHERE evaluation_id = '.intval($this->id)
+			.' )'
+			.' ORDER BY lastname';
 
 		$result = Database::query($sql);
 		$db_users = Database::store_result($result);
 		return $db_users;
-    }
-
-    /**
-     * Find evaluations by name
-     * @param string $name_mask search string
-     * @return array evaluation objects matching the search criterium
-     * @todo can be written more efficiently using a new (but very complex) sql query
-     */
-    public function find_evaluations ($name_mask,$selectcat)
-    {
-    	$rootcat = Category::load($selectcat);
+	}
+
+	/**
+	 * Find evaluations by name
+	 * @param string $name_mask search string
+	 * @return array evaluation objects matching the search criterium
+	 * @todo can be written more efficiently using a new (but very complex) sql query
+	 */
+	public function find_evaluations ($name_mask,$selectcat)
+	{
+		$rootcat = Category::load($selectcat);
 		$evals = $rootcat[0]->get_evaluations((api_is_allowed_to_create_course() ? null : api_get_user_id()), true);
 		$foundevals = array();
 		foreach ($evals as $eval) {
@@ -591,43 +592,43 @@ class Evaluation implements GradebookItem
 			}
 		}
 		return $foundevals;
-    }
+	}
 
-    public function get_item_type()
-    {
+	public function get_item_type()
+	{
 		return 'E';
 	}
 
 	public function get_icon_name()
-    {
+	{
 		return $this->has_results() ? 'evalnotempty' : 'evalempty';
 	}
 
-  	/**
-  	 * Locks an evaluation, only one who can unlock it is the platform administrator.
-  	 * @param int locked 1 or unlocked 0
-  	 *
-  	 **/
-  	function lock($locked)
-    {
-  		$table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
-  		$sql = "UPDATE $table_evaluation SET locked = '".intval($locked)."' WHERE id='".intval($this->id)."'";
-  		Database::query($sql);
-  	}
-
-    function check_lock_permissions()
-    {
-        if (api_is_platform_admin()) {
-            return true;
-        } else {
-            if ($this->is_locked()) {
-                api_not_allowed();
-            }
-        }
-    }
-
-    function delete_linked_data()
-    {
-
-    }
+	/**
+	 * Locks an evaluation, only one who can unlock it is the platform administrator.
+	 * @param int locked 1 or unlocked 0
+	 *
+	 **/
+	function lock($locked)
+	{
+		$table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
+		$sql = "UPDATE $table_evaluation SET locked = '".intval($locked)."' WHERE id='".intval($this->id)."'";
+		Database::query($sql);
+	}
+
+	function check_lock_permissions()
+	{
+		if (api_is_platform_admin()) {
+			return true;
+		} else {
+			if ($this->is_locked()) {
+				api_not_allowed();
+			}
+		}
+	}
+
+	function delete_linked_data()
+	{
+
+	}
 }

+ 63 - 68
main/gradebook/lib/be/exerciselink.class.php

@@ -5,13 +5,8 @@
  * @author Bert Steppé
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class ExerciseLink extends AbstractLink
 {
-    // INTERNAL VARIABLES
     private $course_info = null;
     private $exercise_table = null;
     private $exercise_data = null;
@@ -22,28 +17,28 @@ class ExerciseLink extends AbstractLink
      */
     public function __construct($hp = 0)
     {
-    	parent::__construct();
-    	$this->set_type(LINK_EXERCISE);
+        parent::__construct();
+        $this->set_type(LINK_EXERCISE);
         $this->is_hp = $hp;
         if ($this->is_hp == 1) {
             $this->set_type(LINK_HOTPOTATOES);
         }
     }
 
-	/**
-	 * Generate an array of exercises that a teacher hasn't created a link for.
-	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
-	 */
+    /**
+     * Generate an array of exercises that a teacher hasn't created a link for.
+     * @return array 2-dimensional array - every element contains 2 subelements (id, name)
+     */
     public function get_not_created_links()
     {
         return false;
 
-    	if (empty($this->course_code)) {
+        if (empty($this->course_code)) {
             die('Error in get_not_created_links() : course code not set');
-    	}
-    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+        }
+        $tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 
-		$sql = 'SELECT id, title from '.$this->get_exercise_table().' exe
+        $sql = 'SELECT id, title from '.$this->get_exercise_table().' exe
                 WHERE id NOT IN (
                         SELECT ref_id FROM '.$tbl_grade_links.'
                               WHERE type        = '.LINK_EXERCISE." AND
@@ -51,18 +46,18 @@ class ExerciseLink extends AbstractLink
                         ) AND
                 exe.c_id        = ".$this->course_id;
 
-		$result = Database::query($sql);
-		$cats = array();
-		while ($data=Database::fetch_array($result)) {
-			$cats[] = array ($data['id'], $data['title']);
-		}
-		return $cats;
+        $result = Database::query($sql);
+        $cats = array();
+        while ($data=Database::fetch_array($result)) {
+            $cats[] = array ($data['id'], $data['title']);
+        }
+        return $cats;
     }
 
-	/**
-	 * Generate an array of all exercises available.
-	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
-	 */
+    /**
+     * Generate an array of all exercises available.
+     * @return array 2-dimensional array - every element contains 2 subelements (id, name)
+     */
     public function get_all_links()
     {
         $TBL_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
@@ -81,7 +76,7 @@ class ExerciseLink extends AbstractLink
         // @todo
         $uploadPath = null;
 
-		$sql = 'SELECT id,title from '.$this->get_exercise_table().'
+        $sql = 'SELECT id,title from '.$this->get_exercise_table().'
 				WHERE c_id = '.$this->course_id.' AND active=1  '.$session_condition;
 
         $sql2 = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility, d.id
@@ -96,12 +91,12 @@ class ExerciseLink extends AbstractLink
 				WHERE c_id = '.$this->course_id.' AND active=1 AND session_id='.api_get_session_id().'';
         */
         require_once api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php';
-		if (!$this->is_hp) {
+        if (!$this->is_hp) {
             $result = Database::query($sql);
         } else {
             $result2 = Database::query($sql2);
         }
-		$cats = array();
+        $cats = array();
         if (isset($result)) {
             if (Database::num_rows($result) > 0) {
                 while ($data=Database::fetch_array($result)) {
@@ -111,7 +106,7 @@ class ExerciseLink extends AbstractLink
         }
         if (isset($result2)) {
             if (Database::num_rows($result2) > 0) {
-        		while ($row=Database::fetch_array($result2)) {
+                while ($row=Database::fetch_array($result2)) {
                     /*$path = $data['path'];
                     $fname = GetQuizName($path,$documentPath);
         			$cats[] = array ($data['id'], $fname);*/
@@ -134,7 +129,7 @@ class ExerciseLink extends AbstractLink
                 }
             }
         }
-		return $cats;
+        return $cats;
     }
 
     /**
@@ -142,15 +137,15 @@ class ExerciseLink extends AbstractLink
      */
     public function has_results()
     {
-    	$tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $session_id = api_get_session_id();
-		$sql = 'SELECT count(exe_id) AS number FROM '.$tbl_stats."
+        $sql = 'SELECT count(exe_id) AS number FROM '.$tbl_stats."
                     WHERE   session_id = $session_id AND
                             exe_cours_id = '".$this->get_course_code()."'".' AND
                             exe_exo_id   = '.(int)$this->get_ref_id();
-    	$result = Database::query($sql);
-		$number=Database::fetch_row($result);
-		return ($number[0] != 0);
+        $result = Database::query($sql);
+        $number=Database::fetch_row($result);
+        return ($number[0] != 0);
     }
 
     /**
@@ -178,7 +173,7 @@ class ExerciseLink extends AbstractLink
                         status      <> 'incomplete' AND
                         session_id = $session_id";
 
-    	    if (isset($stud_id)) {
+            if (isset($stud_id)) {
                 $course_code_exe = $this->get_course_code();
                 $sql .= " AND exe_cours_id = '$course_code_exe' AND exe_user_id = '$stud_id' ";
             }
@@ -187,7 +182,7 @@ class ExerciseLink extends AbstractLink
         } else {
             $course_code_exe = $this->get_course_code();
             $courseId =  $this->getCourseId();
-             $sql = "SELECT * FROM $tblHp hp, $tblDoc doc
+            $sql = "SELECT * FROM $tblHp hp, $tblDoc doc
                      WHERE
                         hp.exe_cours_id = '$course_code_exe' AND
                         hp.exe_user_id = '$stud_id'  AND
@@ -204,12 +199,12 @@ class ExerciseLink extends AbstractLink
                 return array ($data['exe_result'], $data['exe_weighting']);
             } else {
                 return null;
-       	    }
+            }
         } else {
             // all students -> get average
-      	    // normal way of getting the info
+            // normal way of getting the info
             $students = array();  // user list, needed to make sure we only
-                                  // take first attempts into account
+            // take first attempts into account
             $student_count = 0;
             $sum = 0;
             while ($data = Database::fetch_array($scores, 'ASSOC')) {
@@ -268,7 +263,7 @@ class ExerciseLink extends AbstractLink
                 return $title;
             }
         }
-    	return $data['title'];
+        return $data['title'];
     }
 
     /**
@@ -276,9 +271,9 @@ class ExerciseLink extends AbstractLink
      */
     public function get_description()
     {
-    	$data = $this->get_exercise_data();
+        $data = $this->get_exercise_data();
 
-    	return isset($data['description']) ? $data['description'] : null;
+        return isset($data['description']) ? $data['description'] : null;
     }
 
     /**
@@ -288,9 +283,9 @@ class ExerciseLink extends AbstractLink
     {
         $sql = 'SELECT count(id) from '.$this->get_exercise_table().'
                 WHERE c_id = '.$this->course_id.' AND id = '.(int)$this->get_ref_id().' ';
-		$result = Database::query($sql);
-		$number=Database::fetch_row($result);
-		return ($number[0] != 0);
+        $result = Database::query($sql);
+        $number=Database::fetch_row($result);
+        return ($number[0] != 0);
     }
 
     /**
@@ -305,24 +300,24 @@ class ExerciseLink extends AbstractLink
         }
     }
 
-	public function needs_name_and_description()
+    public function needs_name_and_description()
     {
-		return false;
-	}
+        return false;
+    }
 
-	public function needs_max()
+    public function needs_max()
     {
-		return false;
-	}
+        return false;
+    }
 
-	public function needs_results()
+    public function needs_results()
     {
-		return false;
-	}
+        return false;
+    }
 
-	public function is_allowed_to_change_name() {
-		return false;
-	}
+    public function is_allowed_to_change_name() {
+        return false;
+    }
 
     /**
      * Lazy load function to get the database table of the exercise
@@ -339,14 +334,14 @@ class ExerciseLink extends AbstractLink
     private function get_exercise_data()
     {
         if ($this->is_hp == 1) {
-           $tbl_exercise = Database :: get_course_table(TABLE_DOCUMENT);
-           $TBL_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+            $tbl_exercise = Database :: get_course_table(TABLE_DOCUMENT);
+            $TBL_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
         } else {
             $tbl_exercise = $this->get_exercise_table();
         }
         if ($tbl_exercise=='') {
-    		return false;
-    	} elseif (!isset($this->exercise_data)) {
+            return false;
+        } elseif (!isset($this->exercise_data)) {
             if ($this->is_hp == 1) {
                 $ref_id = intval($this->get_ref_id());
                 $sql = "SELECT * FROM $tbl_exercise ex, $TBL_ITEM_PROPERTY ip
@@ -365,10 +360,10 @@ class ExerciseLink extends AbstractLink
                             c_id = '.$this->course_id.' AND
                             id = '.(int)$this->get_ref_id().' ';
             }
-			$result = Database::query($sql);
-			$this->exercise_data=Database::fetch_array($result);
-    	}
-    	return $this->exercise_data;
+            $result = Database::query($sql);
+            $this->exercise_data=Database::fetch_array($result);
+        }
+        return $this->exercise_data;
     }
 
     /**
@@ -376,6 +371,6 @@ class ExerciseLink extends AbstractLink
      */
     public function get_icon_name()
     {
-		return 'exercise';
-	}
+        return 'exercise';
+    }
 }

+ 197 - 179
main/gradebook/lib/be/forumthreadlink.class.php

@@ -5,48 +5,46 @@
  * @author Bert Steppé
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class ForumThreadLink extends AbstractLink
 {
+	private $forum_thread_table = null;
+	private $itemprop_table = null;
 
-    // INTERNAL VARIABLES
-    private $forum_thread_table = null;
-    private $itemprop_table = null;
-
-    function __construct() {
-    	parent::__construct();
-    	$this->set_type(LINK_FORUM_THREAD);
-    }
+	public function __construct()
+	{
+		parent::__construct();
+		$this->set_type(LINK_FORUM_THREAD);
+	}
 
-    public function get_type_name() {
-    	return get_lang('ForumThreads');
-    }
+	public function get_type_name()
+	{
+		return get_lang('ForumThreads');
+	}
 
-	public function is_allowed_to_change_name() {
+	public function is_allowed_to_change_name()
+	{
 		return false;
 	}
 
-    // FUNCTIONS IMPLEMENTING ABSTRACTLINK
+	// FUNCTIONS IMPLEMENTING ABSTRACTLINK
 
 	/**
 	 * Generate an array of exercises that a teacher hasn't created a link for.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_not_created_links() {
-    	if (empty($this->course_code)) {
-    		die('Error in get_not_created_links() : course code not set');
-    	}
-    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+	public function get_not_created_links()
+	{
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 
 		$sql = 'SELECT thread_id,thread_title,thread_title_qualify from '.$this->get_forum_thread_table()
-				.' forum_thread WHERE thread_id NOT IN'
-				.' (SELECT ref_id FROM '.$tbl_grade_links
-				.' WHERE type = '.LINK_FORUM_THREAD
-				." AND course_code = '".Database::escape_string($this->get_course_code())."'"
-				.') AND forum_thread.session_id='.api_get_session_id().'';
+			.' forum_thread WHERE thread_id NOT IN'
+			.' (SELECT ref_id FROM '.$tbl_grade_links
+			.' WHERE type = '.LINK_FORUM_THREAD
+			." AND course_code = '".Database::escape_string($this->get_course_code())."'"
+			.') AND forum_thread.session_id='.api_get_session_id().'';
 
 		$result = Database::query($sql);
 
@@ -59,33 +57,35 @@ class ForumThreadLink extends AbstractLink
 			}
 		}
 		return $cats;
-    }
+	}
+
 	/**
 	 * Generate an array of all exercises available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links() {
-    	if (empty($this->course_code)) {
-    		die('Error in get_not_created_links() : course code not set');
-    	}    	
-    	$tbl_grade_links 	= Database :: get_course_table(TABLE_FORUM_THREAD);
-    	$tbl_item_property	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
-        $session_id = api_get_session_id();
-        
-        if ($session_id) {
-            $session_condition = 'tl.session_id='.api_get_session_id();
-        } else {
-            $session_condition = '(tl.session_id = 0 OR tl.session_id IS NULL)';
-        }
-    	
-		$sql = 'SELECT tl.thread_id, tl.thread_title, tl.thread_title_qualify 
-				FROM '.$tbl_grade_links.' tl ,'.$tbl_item_property.' ip 
+	public function get_all_links()
+	{
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_grade_links 	= Database :: get_course_table(TABLE_FORUM_THREAD);
+		$tbl_item_property	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
+		$session_id = api_get_session_id();
+
+		if ($session_id) {
+			$session_condition = 'tl.session_id='.api_get_session_id();
+		} else {
+			$session_condition = '(tl.session_id = 0 OR tl.session_id IS NULL)';
+		}
+
+		$sql = 'SELECT tl.thread_id, tl.thread_title, tl.thread_title_qualify
+				FROM '.$tbl_grade_links.' tl ,'.$tbl_item_property.' ip
 				WHERE 	tl.c_id 		= '.$this->course_id.' AND
-						ip.c_id 		= '.$this->course_id.' AND 
-						tl.thread_id	= ip.ref AND 
-						ip.tool			= "forum_thread" AND 
+						ip.c_id 		= '.$this->course_id.' AND
+						tl.thread_id	= ip.ref AND
+						ip.tool			= "forum_thread" AND
 						ip.visibility<>2 AND  '.$session_condition.' GROUP BY ip.ref ';
-        
+
 		$result = Database::query($sql);
 
 		while ($data=Database::fetch_array($result)) {
@@ -96,54 +96,61 @@ class ForumThreadLink extends AbstractLink
 			}
 		}
 		$my_cats=isset($cats)?$cats:null;
+
 		return $my_cats;
-    }
+	}
 
 
-    /**
-     * Has anyone done this exercise yet ?
-     */
-    public function has_results() {    	
-    	$tbl_grade_links = Database :: get_course_table(TABLE_FORUM_POST);
-		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." 
+	/**
+	 * Has anyone done this exercise yet ?
+	 */
+	public function has_results()
+	{
+		$tbl_grade_links = Database :: get_course_table(TABLE_FORUM_POST);
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links."
 				WHERE c_id = ".$this->course_id." AND thread_id = '".$this->get_ref_id()."'";
-    	$result = Database::query($sql);
+		$result = Database::query($sql);
 		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
-    }
+	}
 
-    public function calc_score($stud_id = null) {    			
-        $thread_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY);
+	/**
+	 * @param int $stud_id
+	 * @return array|null
+	 */
+	public function calc_score($stud_id = null)
+	{
+		$thread_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY);
 
-  		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD)." 
+		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD)."
   				WHERE c_id = ".$this->course_id." AND thread_id = '".$this->get_ref_id()."'";
 		$query = Database::query($sql);
 		$assignment = Database::fetch_array($query);
 
-  	    $sql = "SELECT * FROM $thread_qualify WHERE c_id = ".$this->course_id." AND thread_id = ".$this->get_ref_id();
-    	if (isset($stud_id)) {
-    		$sql .= ' AND user_id = '."'".intval($stud_id)."'";
-    	}
+		$sql = "SELECT * FROM $thread_qualify WHERE c_id = ".$this->course_id." AND thread_id = ".$this->get_ref_id();
+		if (isset($stud_id)) {
+			$sql .= ' AND user_id = '."'".intval($stud_id)."'";
+		}
 
-    	// order by id, that way the student's first attempt is accessed first
+		// order by id, that way the student's first attempt is accessed first
 		$sql .= ' ORDER BY qualify_time DESC';
 
-    	$scores = Database::query($sql);
+		$scores = Database::query($sql);
 
 		// for 1 student
-    	if (isset($stud_id)) {
-    	    
-    		if ($data = Database::fetch_array($scores)) {	    		    
-    			return array ($data['qualify'], $assignment['thread_qualify_max']);
+		if (isset($stud_id)) {
+
+			if ($data = Database::fetch_array($scores)) {
+				return array ($data['qualify'], $assignment['thread_qualify_max']);
 			} else {
-    			//We sent the 0/thread_qualify_max instead of null for correct calculations
-      			//return null;
-      			return array (0, $assignment['thread_qualify_max']);
-    		}
-    	} else {
-    	    // all students -> get average
-    		$students=array();  // user list, needed to make sure we only
-    							// take first attempts into account
+				//We sent the 0/thread_qualify_max instead of null for correct calculations
+				//return null;
+				return array (0, $assignment['thread_qualify_max']);
+			}
+		} else {
+			// all students -> get average
+			$students=array();  // user list, needed to make sure we only
+			// take first attempts into account
 			$rescount = 0;
 			$sum = 0;
 
@@ -154,127 +161,138 @@ class ForumThreadLink extends AbstractLink
 						$rescount++;
 						$sum += ($data['qualify'] / $assignment['thread_qualify_max']);
 					}
-				 }
+				}
 			}
 
 			if ($rescount == 0) {
-			    return null;
-		    } else {
-                return array ($sum , $rescount);
-   		    }    
-    	}
-    }
-
-// INTERNAL FUNCTIONS
-
-    /**
-     * Lazy load function to get the database table of the student publications
-     */
-    private function get_forum_thread_table () {
-    	return $this->forum_thread_table = Database :: get_course_table(TABLE_FORUM_THREAD);
-    }
-
-    /**
-     * Lazy load function to get the database table of the item properties
-     */
-    private function get_itemprop_table () {
-    	$this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-   		return $this->itemprop_table;
-    }
-
-   	public function needs_name_and_description() {
+				return null;
+			} else {
+				return array ($sum , $rescount);
+			}
+		}
+	}
+
+	/**
+	 * Lazy load function to get the database table of the student publications
+	 */
+	private function get_forum_thread_table()
+	{
+		return $this->forum_thread_table = Database :: get_course_table(TABLE_FORUM_THREAD);
+	}
+
+	/**
+	 * Lazy load function to get the database table of the item properties
+	 */
+	private function get_itemprop_table()
+	{
+		$this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+		return $this->itemprop_table;
+	}
+
+	public function needs_name_and_description()
+	{
+		return false;
+	}
+
+	public function needs_max()
+	{
+		return false;
+	}
+
+	public function needs_results()
+	{
 		return false;
 	}
-	
-    public function needs_max() {
-        return false;
-    }
-
-    public function needs_results() {
-        return false;
-    }
-
-    public function get_name() {
-    	$this->get_exercise_data();        
-    	$thread_title=isset($this->exercise_data['thread_title']) ? $this->exercise_data['thread_title'] : '';
-    	$thread_title_qualify=isset($this->exercise_data['thread_title_qualify']) ? $this->exercise_data['thread_title_qualify'] : '';
-    	if ( isset($thread_title_qualify) && $thread_title_qualify!="") {
-    		return $this->exercise_data['thread_title_qualify'];
-    	} else {
-    		return $thread_title;
-    	}
-    }
-
-    public function get_description() {
-    	return '';//$this->exercise_data['description'];
-    }
-    /**
-     * Check if this still links to an exercise
-     */
-    public function is_valid_link() {
-        $sql = 'SELECT count(id) from '.$this->get_forum_thread_table().' 
+
+	public function get_name()
+	{
+		$this->get_exercise_data();
+		$thread_title=isset($this->exercise_data['thread_title']) ? $this->exercise_data['thread_title'] : '';
+		$thread_title_qualify=isset($this->exercise_data['thread_title_qualify']) ? $this->exercise_data['thread_title_qualify'] : '';
+		if ( isset($thread_title_qualify) && $thread_title_qualify!="") {
+			return $this->exercise_data['thread_title_qualify'];
+		} else {
+			return $thread_title;
+		}
+	}
+
+	public function get_description()
+	{
+		return '';//$this->exercise_data['description'];
+	}
+	/**
+	 * Check if this still links to an exercise
+	 */
+	public function is_valid_link()
+	{
+		$sql = 'SELECT count(id) from '.$this->get_forum_thread_table().'
         		WHERE c_id = '.$this->course_id.' AND thread_id = '.$this->get_ref_id().' AND session_id='.api_get_session_id().'';
-        $result = Database::query($sql);
-        $number = Database::fetch_row($result);
-        return ($number[0] != 0);
-    }
-
-    public function get_test_id() {
-    	return 'DEBUG:ID';
-    }
-
-    public function get_link() {
-    	//it was extracts the forum id
-    	$sql = 'SELECT * FROM '.$this->get_forum_thread_table()." 
+		$result = Database::query($sql);
+		$number = Database::fetch_row($result);
+		return ($number[0] != 0);
+	}
+
+	public function get_test_id()
+	{
+		return 'DEBUG:ID';
+	}
+
+	public function get_link()
+	{
+		//it was extracts the forum id
+		$sql = 'SELECT * FROM '.$this->get_forum_thread_table()."
     			WHERE c_id = '.$this->course_id.' AND thread_id = '".$this->get_ref_id()."' AND session_id = ".api_get_session_id()."";
 		$result = Database::query($sql);
 		$row    = Database::fetch_array($result,'ASSOC');
 		$forum_id=$row['forum_id'];
 
-    	$url = api_get_path(WEB_PATH).'main/forum/viewthread.php?cidReq='.$this->get_course_code().'&thread='.$this->get_ref_id().'&gradebook=view&forum='.$forum_id;
+		$url = api_get_path(WEB_PATH).'main/forum/viewthread.php?cidReq='.$this->get_course_code().'&thread='.$this->get_ref_id().'&gradebook=view&forum='.$forum_id;
 		return $url;
-   		
 	}
-	private function get_exercise_data() {        
-        $session_id = api_get_session_id();        
-        if ($session_id) {
-            $session_condition = 'session_id='.api_get_session_id();
-        } else {
-            $session_condition = '(session_id = 0 OR session_id IS NULL)';
-        }
-        
+
+	private function get_exercise_data()
+	{
+		$session_id = api_get_session_id();
+		if ($session_id) {
+			$session_condition = 'session_id='.api_get_session_id();
+		} else {
+			$session_condition = '(session_id = 0 OR session_id IS NULL)';
+		}
+
 		if (!isset($this->exercise_data)) {
-    		$sql = 'SELECT * FROM '.$this->get_forum_thread_table().'
+			$sql = 'SELECT * FROM '.$this->get_forum_thread_table().'
                     WHERE c_id = '.$this->course_id.' AND  thread_id = '.$this->get_ref_id().' AND '.$session_condition;
 			$query = Database::query($sql);
 			$this->exercise_data = Database::fetch_array($query);
-    	}
-    	return $this->exercise_data;
-    }
+		}
+		return $this->exercise_data;
+	}
 
-    public function get_icon_name() {
+	public function get_icon_name()
+	{
 		return 'forum';
 	}
-    
-    function save_linked_data() {
-        $weight = (float)$this->get_weight();
-        $ref_id = $this->get_ref_id();
-        
-        if (!empty($ref_id)) {
-            $sql = 'UPDATE '.$this->get_forum_thread_table().' SET thread_weight='.$weight.'
-                    WHERE c_id = '.$this->course_id.' AND thread_id= '.$ref_id;
-            Database::query($sql);
-        }
-    }
 
+	function save_linked_data()
+	{
+		$weight = (float)$this->get_weight();
+		$ref_id = $this->get_ref_id();
+
+		if (!empty($ref_id)) {
+			$sql = 'UPDATE '.$this->get_forum_thread_table().' SET thread_weight='.$weight.'
+                    WHERE c_id = '.$this->course_id.' AND thread_id= '.$ref_id;
+			Database::query($sql);
+		}
+	}
 
-    function delete_linked_data() {
-        $ref_id = $this->get_ref_id();
-        if (!empty($ref_id)) {
-            //Cleans forum
-            $sql = 'UPDATE '.$this->get_forum_thread_table().' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" 
+	function delete_linked_data()
+	{
+		$ref_id = $this->get_ref_id();
+		if (!empty($ref_id)) {
+			//Cleans forum
+			$sql = 'UPDATE '.$this->get_forum_thread_table().' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify=""
                     WHERE c_id = '.$this->course_id.' AND thread_id= '.$ref_id;
-            Database::query($sql);
-        }
-    }
-}
+			Database::query($sql);
+		}
+	}
+}

+ 2 - 5
main/gradebook/lib/be/gradebookitem.class.php

@@ -1,14 +1,11 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Interface for all displayable items in the gradebook.
  * @author Bert Steppé
  * @package chamilo.gradebook
  */
-/**
- * Interface
- * @package chamilo.gradebook
- */
 interface GradebookItem
 {
 	public function get_item_type();
@@ -19,6 +16,6 @@ interface GradebookItem
 	public function get_weight();
 	public function get_date();
 	public function is_visible();
-	public function get_icon_name();    
+	public function get_icon_name();
 	public function calc_score($stud_id = null);
 }

+ 141 - 126
main/gradebook/lib/be/learnpathlink.class.php

@@ -1,47 +1,47 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Defines a gradebook LearnpathLink object.
  * @author Yannick Warnier <yannick.warnier@beeznest.com>
  * @author Bert Steppé
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class LearnpathLink extends AbstractLink
 {
-    // INTERNAL VARIABLES
-    private $course_info = null;
-    private $learnpath_table = null;
-    private $learnpath_data = null;
-
-    // CONSTRUCTORS
-    function __construct() {
-    	parent::__construct();
-    	$this->set_type(LINK_LEARNPATH);
-    }
-    
-    // FUNCTIONS IMPLEMENTING ABSTRACTLINK
+	private $course_info = null;
+	private $learnpath_table = null;
+	private $learnpath_data = null;
+
+	/**
+	 * Constructor
+	 */
+	public function __construct()
+	{
+		parent::__construct();
+		$this->set_type(LINK_LEARNPATH);
+	}
+
+	// FUNCTIONS IMPLEMENTING ABSTRACTLINK
 
 	/**
 	 * Generate an array of learnpaths that a teacher hasn't created a link for.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_not_created_links() {
-        return false;
-    	if (empty($this->course_code))
-    		die('Error in get_not_created_links() : course code not set');
+	public function get_not_created_links()
+	{
+		return false;
+		if (empty($this->course_code))
+			die('Error in get_not_created_links() : course code not set');
 
-    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 
-		$sql = 'SELECT id, name from '.$this->get_learnpath_table().' lp 
+		$sql = 'SELECT id, name from '.$this->get_learnpath_table().' lp
 				WHERE c_id = '.$this->course_id.' AND id NOT IN '
-				.' (SELECT ref_id FROM '.$tbl_grade_links
-				.' WHERE type = '.LINK_LEARNPATH
-				." AND course_code = '".$this->get_course_code()."'"
-				.') AND lp.session_id='.api_get_session_id().'';
+			.' (SELECT ref_id FROM '.$tbl_grade_links
+			.' WHERE type = '.LINK_LEARNPATH
+			." AND course_code = '".$this->get_course_code()."'"
+			.') AND lp.session_id='.api_get_session_id().'';
 
 		$result = Database::query($sql);
 
@@ -49,24 +49,27 @@ class LearnpathLink extends AbstractLink
 		while ($data=Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], $data['name']);
 		}
+
 		return $cats;
-    }
+	}
+
 	/**
 	 * Generate an array of all learnpaths available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links() {
-    	if (empty($this->course_code))
-    		die('Error in get_not_created_links() : course code not set');
-        
-        $session_id = api_get_session_id();
-        if (empty($session_id)) {
-            $session_condition = api_get_session_condition(0, true);
-        } else {
-            $session_condition = api_get_session_condition($session_id, true, true);
-        }
-
-		$sql = 'SELECT id, name FROM '.$this->get_learnpath_table().' 
+	public function get_all_links()
+	{
+		if (empty($this->course_code))
+			die('Error in get_not_created_links() : course code not set');
+
+		$session_id = api_get_session_id();
+		if (empty($session_id)) {
+			$session_condition = api_get_session_condition(0, true);
+		} else {
+			$session_condition = api_get_session_condition($session_id, true, true);
+		}
+
+		$sql = 'SELECT id, name FROM '.$this->get_learnpath_table().'
                 WHERE c_id = '.$this->course_id.' '.$session_condition.' ';
 		$result = Database::query($sql);
 
@@ -74,55 +77,58 @@ class LearnpathLink extends AbstractLink
 		while ($data=Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], $data['name']);
 		}
+
 		return $cats;
-    }
+	}
 
 
-    /**
-     * Has anyone used this learnpath yet ?
-     */
-    public function has_results() {
-    	$tbl_stats = Database::get_course_table(TABLE_LP_VIEW);
+	/**
+	 * Has anyone used this learnpath yet ?
+	 */
+	public function has_results()
+	{
+		$tbl_stats = Database::get_course_table(TABLE_LP_VIEW);
 		$sql = "SELECT count(id) AS number FROM $tbl_stats
 				WHERE c_id = ".$this->course_id." AND lp_id = ".$this->get_ref_id();
-    	$result = Database::query($sql);
+		$result = Database::query($sql);
 		$number = Database::fetch_array($result,'NUM');
 		return ($number[0] != 0);
-    }
+	}
 
-    /**
+	/**
 	 * Get the progress of this learnpath. Only the last attempt are taken into account.
 	 * @param $stud_id student id (default: all students who have results - then the average is returned)
 	 * @return	array (score, max) if student is given
 	 * 			array (sum of scores, number of scores) otherwise
 	 * 			or null if no scores available
 	 */
-    public function calc_score($stud_id = null) {    	
-    	$tbl_stats = Database::get_course_table(TABLE_LP_VIEW);    	
-        $session_id = api_get_session_id();
-        
-    	$sql = "SELECT * FROM $tbl_stats 
-                WHERE   c_id = ".$this->course_id." AND 
+	public function calc_score($stud_id = null)
+	{
+		$tbl_stats = Database::get_course_table(TABLE_LP_VIEW);
+		$session_id = api_get_session_id();
+
+		$sql = "SELECT * FROM $tbl_stats
+                WHERE   c_id = ".$this->course_id." AND
                         lp_id = ".$this->get_ref_id()." AND
                         session_id = $session_id ";
 
-    	if (isset($stud_id))
-    		$sql .= ' AND user_id = '.intval($stud_id);
+		if (isset($stud_id))
+			$sql .= ' AND user_id = '.intval($stud_id);
 
-    	// order by id, that way the student's first attempt is accessed first
-		$sql .= ' ORDER BY view_count DESC';		
-    	$scores = Database::query($sql);
+		// order by id, that way the student's first attempt is accessed first
+		$sql .= ' ORDER BY view_count DESC';
+		$scores = Database::query($sql);
 		// for 1 student
-    	if (isset($stud_id)) {
-    		if ($data = Database::fetch_array($scores)) {
-    			return array ($data['progress'], 100);
-    		} else
-    			return null;
-    	}
-    	// all students -> get average
-    	else {
-    		$students=array();  // user list, needed to make sure we only
-    							// take first attempts into account
+		if (isset($stud_id)) {
+			if ($data = Database::fetch_array($scores)) {
+				return array ($data['progress'], 100);
+			} else
+				return null;
+		}
+		// all students -> get average
+		else {
+			$students=array();  // user list, needed to make sure we only
+			// take first attempts into account
 			$rescount = 0;
 			$sum = 0;
 
@@ -138,15 +144,16 @@ class LearnpathLink extends AbstractLink
 				return null;
 			else
 				return array ($sum , $rescount);
-    	}
-    }
+		}
+	}
 
-    /**
-     * Get URL where to go to if the user clicks on the link.
-     */
-	public function get_link() {
+	/**
+	 * Get URL where to go to if the user clicks on the link.
+	 */
+	public function get_link()
+	{
 		$url = api_get_path(WEB_PATH).'main/newscorm/lp_controller.php?cidReq='.$this->get_course_code().'&gradebook=view';
-        $session_id = api_get_session_id();
+		$session_id = api_get_session_id();
 		if (!api_is_allowed_to_edit() || $this->calc_score(api_get_user_id()) == null) {
 			$url .= '&action=view&session_id='.$session_id.'&lp_id='.$this->get_ref_id();
 		} else {
@@ -155,79 +162,87 @@ class LearnpathLink extends AbstractLink
 		return $url;
 	}
 
-    /**
-     * Get name to display: same as learnpath title
-     */
-    public function get_name()
-    {
-    	$data = $this->get_learnpath_data();
-    	return $data['name'];
-    }
-
-    /**
-     * Get description to display: same as learnpath description
-     */
-    public function get_description()
-    {
-    	$data = $this->get_learnpath_data();
-    	return $data['description'];
-    }
-
-    /**
-     * Check if this still links to a learnpath
-     */
-    public function is_valid_link() {
-    	$sql = 'SELECT count(id) FROM '.$this->get_learnpath_table().' 
+	/**
+	 * Get name to display: same as learnpath title
+	 */
+	public function get_name()
+	{
+		$data = $this->get_learnpath_data();
+		return $data['name'];
+	}
+
+	/**
+	 * Get description to display: same as learnpath description
+	 */
+	public function get_description()
+	{
+		$data = $this->get_learnpath_data();
+		return $data['description'];
+	}
+
+	/**
+	 * Check if this still links to a learnpath
+	 */
+	public function is_valid_link() {
+		$sql = 'SELECT count(id) FROM '.$this->get_learnpath_table().'
                 WHERE c_id = '.$this->course_id.' AND id = '.$this->get_ref_id().' ';
 		$result = Database::query($sql);
 		$number = Database::fetch_row($result,'NUM');
 		return ($number[0] != 0);
-    }
+	}
 
-    public function get_type_name() {
-    	return get_lang('LearningPaths');
-    }
+	public function get_type_name()
+	{
+		return get_lang('LearningPaths');
+	}
 
-	public function needs_name_and_description() {
+	public function needs_name_and_description()
+	{
 		return false;
 	}
 
-	public function needs_max() {
+	public function needs_max()
+	{
 		return false;
 	}
 
-	public function needs_results() {
+	public function needs_results()
+	{
 		return false;
 	}
 
-	public function is_allowed_to_change_name() {
+	public function is_allowed_to_change_name()
+	{
 		return false;
 	}
 
-    // INTERNAL FUNCTIONS
+	// INTERNAL FUNCTIONS
 
-    /**
-     * Lazy load function to get the database table of the learnpath
-     */
-    private function get_learnpath_table() {
-    	$this->learnpath_table = Database :: get_course_table(TABLE_LP_MAIN);
-   		return $this->learnpath_table;
-    }
+	/**
+	 * Lazy load function to get the database table of the learnpath
+	 */
+	private function get_learnpath_table()
+	{
+		$this->learnpath_table = Database :: get_course_table(TABLE_LP_MAIN);
+		return $this->learnpath_table;
+	}
 
-    /**
-     * Lazy load function to get the database contents of this learnpath
-     */
-    private function get_learnpath_data() {
-    	if (!isset($this->learnpath_data)) {
-			$sql = 'SELECT * FROM '.$this->get_learnpath_table().' 
+	/**
+	 * Lazy load function to get the database contents of this learnpath
+	 */
+	private function get_learnpath_data()
+	{
+		if (!isset($this->learnpath_data)) {
+			$sql = 'SELECT * FROM '.$this->get_learnpath_table().'
                     WHERE c_id = '.$this->course_id.' AND id = '.$this->get_ref_id().' ';
 			$result = Database::query($sql);
 			$this->learnpath_data=Database::fetch_array($result);
-    	}
-    	return $this->learnpath_data;
-    }
+		}
+		return $this->learnpath_data;
+	}
 
-    public function get_icon_name() {
+	public function get_icon_name()
+	{
 		return 'learnpath';
 	}
-}
+}

+ 54 - 54
main/gradebook/lib/be/linkfactory.class.php

@@ -20,16 +20,16 @@ require_once 'surveylink.class.php';
  */
 class LinkFactory
 {
-	/**
-	 * Retrieve links and return them as an array of extensions of AbstractLink.
-	 * @param int $id link id
-	 * @param int $type link type
-	 * @param int $ref_id reference id
-	 * @param int $user_id user id (link owner)
-	 * @param string $course_code course code
-	 * @param int $category_id parent category
-	 * @param int $visible visible
-	 */
+    /**
+     * Retrieve links and return them as an array of extensions of AbstractLink.
+     * @param int $id link id
+     * @param int $type link type
+     * @param int $ref_id reference id
+     * @param int $user_id user id (link owner)
+     * @param string $course_code course code
+     * @param int $category_id parent category
+     * @param int $visible visible
+     */
     public static function load(
         $id = null,
         $type = null,
@@ -48,21 +48,21 @@ class LinkFactory
             $category_id,
             $visible
         );
-	}
+    }
 
-	/**
-	 * Get the link object referring to an evaluation
-	 */
-	public function get_evaluation_link ($eval_id)
+    /**
+     * Get the link object referring to an evaluation
+     */
+    public function get_evaluation_link ($eval_id)
     {
-		$links = AbstractLink :: load(null, null, $eval_id);
-		foreach ($links as $link) {
-			if (is_a($link, 'EvalLink')) {
-				return $link;
-			}
-		}
-		return null;
-	}
+        $links = AbstractLink :: load(null, null, $eval_id);
+        foreach ($links as $link) {
+            if (is_a($link, 'EvalLink')) {
+                return $link;
+            }
+        }
+        return null;
+    }
 
     /**
      * Find links by name
@@ -71,45 +71,45 @@ class LinkFactory
      */
     public function find_links ($name_mask,$selectcat)
     {
-    	return AbstractLink::find_links($name_mask, $selectcat);
+        return AbstractLink::find_links($name_mask, $selectcat);
     }
 
-	/**
-	 * Static method to create specific link objects
-	 * @param $type link type
-	 */
-	public static function create ($type)
+    /**
+     * Static method to create specific link objects
+     * @param $type link type
+     */
+    public static function create ($type)
     {
         $type = intval($type);
-		switch ($type) {
-			case LINK_EXERCISE:
-				return new ExerciseLink();
+        switch ($type) {
+            case LINK_EXERCISE:
+                return new ExerciseLink();
             case LINK_HOTPOTATOES:
                 return new ExerciseLink(1);
-			case LINK_DROPBOX:
-				return new DropboxLink();
-			case LINK_STUDENTPUBLICATION:
-				return new StudentPublicationLink();
-			case LINK_LEARNPATH:
-				return new LearnpathLink();
-			case LINK_FORUM_THREAD:
-				return new ForumThreadLink();
-			case LINK_ATTENDANCE:
-				return new AttendanceLink();
-			case LINK_SURVEY:
-				return new SurveyLink();
-		}
-		return null;
-	}
+            case LINK_DROPBOX:
+                return new DropboxLink();
+            case LINK_STUDENTPUBLICATION:
+                return new StudentPublicationLink();
+            case LINK_LEARNPATH:
+                return new LearnpathLink();
+            case LINK_FORUM_THREAD:
+                return new ForumThreadLink();
+            case LINK_ATTENDANCE:
+                return new AttendanceLink();
+            case LINK_SURVEY:
+                return new SurveyLink();
+        }
+        return null;
+    }
 
-	/**
-	 * Return an array of all known link types
+    /**
+     * Return an array of all known link types
      * @return array
-	 */
-	public static function get_all_types ()
+     */
+    public static function get_all_types ()
     {
-		//LINK_DROPBOX,
-		return array (
+        //LINK_DROPBOX,
+        return array (
             LINK_EXERCISE,
             //LINK_DROPBOX,
             LINK_HOTPOTATOES,
@@ -119,7 +119,7 @@ class LinkFactory
             LINK_ATTENDANCE,
             LINK_SURVEY
         );
-	}
+    }
 
     public function delete()
     {

+ 12 - 16
main/gradebook/lib/be/result.class.php

@@ -5,10 +5,6 @@
  * @author Bert Steppé, Stijn Konings
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class Result
 {
     private $id;
@@ -17,7 +13,7 @@ class Result
     private $created_at;
     private $score;
 
-    function Result()
+    public function Result()
     {
         $this->created_at = api_get_utc_datetime();
     }
@@ -97,7 +93,7 @@ class Result
 
                 $sql_course_rel_user = '';
                 if (api_get_session_id()) {
-                    $sql_course_rel_user = 'SELECT course_code, id_user as user_id, status FROM ' . $tbl_session_rel_course_user . ' 
+                    $sql_course_rel_user = 'SELECT course_code, id_user as user_id, status FROM ' . $tbl_session_rel_course_user . '
 												 WHERE status=0 AND course_code="' . api_get_course_id() . '" AND id_session=' . api_get_session_id();
                 } else {
                     $sql_course_rel_user = 'SELECT course_code,user_id,status FROM ' . $tbl_course_rel_course . ' WHERE status ="' . STUDENT . '" AND course_code="' . api_get_course_id() . '" ';
@@ -115,7 +111,7 @@ class Result
                     $res_verified = Database::query($sql_verified);
                     $info_verified = Database::result($res_verified, 0, 0);
                     if ($info_verified == 0) {
-                        $sql_insert = 'INSERT INTO ' . $tbl_grade_results . '(user_id,evaluation_id,created_at,score) 
+                        $sql_insert = 'INSERT INTO ' . $tbl_grade_results . '(user_id,evaluation_id,created_at,score)
 									 VALUES ("' . intval($list_user_course_list[$i]['user_id']) . '","' . intval($evaluation_id) . '","' . $current_date . '",0);';
                         $res_insert = Database::query($sql_insert);
                     }
@@ -124,7 +120,7 @@ class Result
             }
         }
 
-        $sql = "SELECT gr.id, gr.user_id, gr.evaluation_id, gr.created_at, gr.score 
+        $sql = "SELECT gr.id, gr.user_id, gr.evaluation_id, gr.created_at, gr.score
                 FROM $tbl_grade_results gr
                 LEFT JOIN $tbl_user u ON gr.user_id = u.user_id ";
         $paramcount = 0;
@@ -172,14 +168,14 @@ class Result
         if (isset($this->user_id) && isset($this->evaluation)) {
             $tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
             $sql = "INSERT INTO " . $tbl_grade_results
-                    . " (user_id, evaluation_id,
+                . " (user_id, evaluation_id,
 					created_at";
             if (isset($this->score)) {
                 $sql .= ",score";
             }
             $sql .= ") VALUES
 					(" . (int) $this->get_user_id() . ", " . (int) $this->get_evaluation_id()
-                    . ", '" . $this->get_date() . "' ";
+                . ", '" . $this->get_date() . "' ";
             if (isset($this->score)) {
                 $sql .= ", " . $this->get_score();
             }
@@ -204,13 +200,13 @@ class Result
             $arr = get_object_vars($arr_result[0]);
 
             $sql = 'INSERT INTO ' . $tbl_grade_results_log
-                    . ' (id_result,user_id, evaluation_id,created_at';
+                . ' (id_result,user_id, evaluation_id,created_at';
             if (isset($arr['score'])) {
                 $sql .= ',score';
             }
             $sql .= ') VALUES
 					(' . (int) $arr['id'] . ',' . (int) $arr['user_id'] . ', ' . (int) $arr['evaluation']
-                    . ", '" . api_get_utc_datetime() . "'";
+                . ", '" . api_get_utc_datetime() . "'";
             if (isset($arr['score'])) {
                 $sql .= ', ' . $arr['score'];
             }
@@ -228,17 +224,17 @@ class Result
     public function save()
     {
         $tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
-        $sql = 'UPDATE ' . $tbl_grade_results . ' 
+        $sql = 'UPDATE ' . $tbl_grade_results . '
                 SET user_id = ' . $this->get_user_id()
-                . ', evaluation_id = ' . $this->get_evaluation_id()
-                . ', score = ';
+            . ', evaluation_id = ' . $this->get_evaluation_id()
+            . ', score = ';
         if (isset($this->score)) {
             $sql .= $this->get_score();
         } else {
             $sql .= 'null';
         }
         $sql .= ' WHERE id = ' . $this->id;
-        // no need to update creation date        
+        // no need to update creation date
         Database::query($sql);
     }
 

+ 221 - 179
main/gradebook/lib/be/studentpublicationlink.class.php

@@ -1,88 +1,89 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Gradebook link to student publication item
  * @author Bert Steppé
  * @package chamilo.gradebook
  */
-/**
- * Class
- * @package chamilo.gradebook
- */
 class StudentPublicationLink extends AbstractLink
 {
+	private $studpub_table = null;
+	private $itemprop_table = null;
 
-    // INTERNAL VARIABLES
-    private $studpub_table = null;
-    private $itemprop_table = null;
-
-    // CONSTRUCTORS
-    public function __construct() {
-    	parent::__construct();
-    	$this->set_type(LINK_STUDENTPUBLICATION);
-    }
-
-    /**
-     * 
-     * Returns the URL of a document
-     * This funcion is loaded when using a gradebook as a tab (gradebook = -1), see issue #2705
-     * 
-     */
+	/**
+	 * Constructor
+	 */
+	public function __construct()
+	{
+		parent::__construct();
+		$this->set_type(LINK_STUDENTPUBLICATION);
+	}
 
-	public function get_view_url ($stud_id) {
+	/**
+	 *
+	 * Returns the URL of a document
+	 * This function is loaded when using a gradebook as a tab (gradebook = -1)
+	 * see issue #2705
+	 *
+	 */
+	public function get_view_url($stud_id)
+	{
 		// find a file uploaded by the given student,
 		// with the same title as the evaluation name
 
-    	$eval = $this->get_evaluation();
-        $stud_id = intval($stud_id);
+		$eval = $this->get_evaluation();
+		$stud_id = intval($stud_id);
 
-		$sql = 'SELECT pub.url FROM '.$this->get_itemprop_table().' prop, '.$this->get_studpub_table().' pub'
-				." WHERE
+		$sql = 'SELECT pub.url
+				FROM '.$this->get_itemprop_table().' prop, '.$this->get_studpub_table().' pub'
+			." WHERE
 					prop.c_id = ".$this->course_id." AND
-					pub.c_id = ".$this->course_id." AND  
+					pub.c_id = ".$this->course_id." AND
 					prop.tool = 'work'"
-				.' AND prop.insert_user_id = '.$stud_id
-				.' AND prop.ref = pub.id'
-				." AND pub.title = '".Database::escape_string($eval->get_name())."' AND pub.session_id=".api_get_session_id()."";
+			.' AND prop.insert_user_id = '.$stud_id
+			.' AND prop.ref = pub.id'
+			." AND pub.title = '".Database::escape_string($eval->get_name())."' AND pub.session_id=".api_get_session_id()."";
 
 		$result = Database::query($sql);
 		if ($fileurl = Database::fetch_row($result)) {
-	    	$course_info = Database :: get_course_info($this->get_course_code());
+			$course_info = Database :: get_course_info($this->get_course_code());
 			//$url = api_get_path(WEB_PATH).'main/gradebook/open_document.php?file='.$course_info['directory'].'/'.$fileurl[0];
 			//return $url;
-            return null;      
-		 } else {
+			return null;
+		} else {
 			return null;
 		}
 	}
 
-    public function get_type_name() {
-    	return get_lang('Works');
-    }
+	public function get_type_name()
+	{
+		return get_lang('Works');
+	}
 
-	public function is_allowed_to_change_name() {
+	public function is_allowed_to_change_name()
+	{
 		return false;
 	}
 
-    // FUNCTIONS IMPLEMENTING ABSTRACTLINK
-
 	/**
 	 * Generate an array of exercises that a teacher hasn't created a link for.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_not_created_links() {
-        return false;
-    	if (empty($this->course_code)) {
-    		die('Error in get_not_created_links() : course code not set');
-    	}
-    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+	public function get_not_created_links()
+	{
+		return false;
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 
 		$sql = 'SELECT id, url from '.$this->get_studpub_table()
-				.' pup WHERE c_id = '.$this->course_id.' AND has_properties != '."''".' AND id NOT IN'
-				.' (SELECT ref_id FROM '.$tbl_grade_links
-				.' WHERE type = '.LINK_STUDENTPUBLICATION
-				." AND course_code = '".Database::escape_string($this->get_course_code())."'"
-				.') AND pub.session_id='.api_get_session_id().'';
+			.' pup WHERE c_id = '.$this->course_id.' AND has_properties != '."''".' AND id NOT IN'
+			.' (SELECT ref_id FROM '.$tbl_grade_links
+			.' WHERE type = '.LINK_STUDENTPUBLICATION
+			." AND course_code = '".Database::escape_string($this->get_course_code())."'"
+			.') AND pub.session_id='.api_get_session_id().'';
 
 		$result = Database::query($sql);
 
@@ -91,97 +92,123 @@ class StudentPublicationLink extends AbstractLink
 			$cats[] = array ($data['id'], $data['url']);
 		}
 		return $cats;
-    }
-    
+	}
+
 	/**
 	 * Generate an array of all exercises available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links() {
-        
-    	if (empty($this->course_code)) {
-     		die('Error in get_not_created_links() : course code not set');
-    	}    	
-    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
-        
-        $session_id = api_get_session_id();
-        /*
+	public function get_all_links()
+	{
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+
+		$session_id = api_get_session_id();
+		/*
         if (empty($session_id)) {
             $session_condition = api_get_session_condition(0, true);
         } else {
             $session_condition = api_get_session_condition($session_id, true, true);
-        }     
-		$sql = "SELECT id, url, title FROM $tbl_grade_links         
-				WHERE c_id = {$this->course_id}  AND filetype='folder' AND active = 1 $session_condition ";*/
-        
-        //Only show works from the session
-        //AND has_properties != ''
-        $sql = "SELECT id, url, title FROM $tbl_grade_links 
-				WHERE c_id = {$this->course_id} AND active = 1 AND filetype='folder' AND session_id = ".api_get_session_id()."";
-	                
+        }
+        $sql = "SELECT id, url, title FROM $tbl_grade_links
+                WHERE c_id = {$this->course_id}  AND filetype='folder' AND active = 1 $session_condition ";*/
+
+		//Only show works from the session
+		//AND has_properties != ''
+		$sql = "SELECT id, url, title FROM $tbl_grade_links
+				WHERE
+					c_id = {$this->course_id} AND
+					active = 1 AND
+					filetype='folder' AND
+					session_id = ".api_get_session_id()."";
 
 		$result = Database::query($sql);
 		while ($data = Database::fetch_array($result)) {
-            $work_name = $data['title'];
-            if (empty($work_name)) {
-                $work_name = basename($data['url']);
-            }            
+			$work_name = $data['title'];
+			if (empty($work_name)) {
+				$work_name = basename($data['url']);
+			}
 			$cats[] = array ($data['id'], $work_name);
 		}
 		$cats=isset($cats) ? $cats : array();
 		return $cats;
-    }
-
-    /**
-     * Has anyone done this exercise yet ?
-     */
-    public function has_results() {
-    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
-		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." 
-				WHERE 	c_id 		= {$this->course_id} AND 
-						parent_id 	= '".intval($this->get_ref_id())."' AND 
+	}
+
+	/**
+	 * Has anyone done this exercise yet ?
+	 */
+	public function has_results()
+	{
+		$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links."
+				WHERE 	c_id 		= {$this->course_id} AND
+						parent_id 	= '".intval($this->get_ref_id())."' AND
 						session_id	=".api_get_session_id()."";
-    	$result = Database::query($sql);
+		$result = Database::query($sql);
 		$number = Database::fetch_row($result);
 		return ($number[0] != 0);
-    }
-
-    public function calc_score($stud_id = null) {
-    	$stud_id 	= intval($stud_id);
-		$tbl_stats 	= Database::get_course_table(TABLE_STUDENT_PUBLICATION);		
-    	$sql = 'SELECT * FROM '.$tbl_stats." 
-    			WHERE 	c_id 		= {$this->course_id} AND  
-    					id 			= '".intval($this->get_ref_id())."' AND 
-    					session_id	= ".api_get_session_id()."";
+	}
+
+	/**
+	 * @param null $stud_id
+	 * @return array|null
+	 */
+	public function calc_score($stud_id = null)
+	{
+		$stud_id = intval($stud_id);
+		$tbl_stats = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
+		$sql = 'SELECT * FROM '.$tbl_stats."
+    			WHERE
+    				c_id = {$this->course_id} AND
+    				id  = '".intval($this->get_ref_id())."' AND
+    				session_id	= ".api_get_session_id()."";
 		$query = Database::query($sql);
 		$assignment = Database::fetch_array($query);
 
-    	if (count($assignment)==0) {
-    		 $v_assigment_id ='0';
-    	} else {
-    		 $v_assigment_id = $assignment['id'];
-    	}
-    	$sql = 'SELECT * FROM '.$tbl_stats.' 
-    			WHERE c_id = '.$this->course_id.' AND active = 1 AND parent_id ="'.$v_assigment_id.'" AND session_id='.api_get_session_id().'';
-    	
-    	if (!empty($stud_id)) {
-    		$sql .= " AND user_id = $stud_id ";
-    	}
-    	// order by id, that way the student's first attempt is accessed first
-		$sql .= ' ORDER BY id';
-        
-    	$scores = Database::query($sql);
+		if (count($assignment)==0) {
+			$v_assigment_id ='0';
+		} else {
+			$v_assigment_id = $assignment['id'];
+		}
+		$sql = 'SELECT * FROM '.$tbl_stats.'
+    			WHERE
+    				c_id = '.$this->course_id.' AND
+    				active = 1 AND
+    				parent_id ="'.$v_assigment_id.'" AND
+    				session_id='.api_get_session_id().'';
+
+		if (!empty($stud_id)) {
+			$sql .= " AND user_id = $stud_id ";
+		}
+
+		$order = api_get_configuration_value('student_publication_to_take_in_gradebook');
+
+		switch ($order) {
+			case 'last':
+				// latest attempt
+				$sql .= ' ORDER BY sent_date DESC';
+				break;
+			case 'first':
+			default:
+				// first attempt
+				$sql .= ' ORDER BY id';
+				break;
+		}
+
+		$scores = Database::query($sql);
 
 		// for 1 student
-    	if (!empty($stud_id)) {
-    		if ($data = Database::fetch_array($scores)) {
-     			return array($data['qualification'], $assignment['qualification']);
-    		} else {
-     			return '';
-    		}
-    	} else {
-    		$students = array();  // user list, needed to make sure we only
-    							// take first attempts into account
+		if (!empty($stud_id)) {
+			if ($data = Database::fetch_array($scores)) {
+				return array($data['qualification'], $assignment['qualification']);
+			} else {
+				return '';
+			}
+		} else {
+			$students = array();  // user list, needed to make sure we only
+			// take first attempts into account
 			$rescount = 0;
 			$sum = 0;
 			while ($data = Database::fetch_array($scores)) {
@@ -199,101 +226,116 @@ class StudentPublicationLink extends AbstractLink
 			} else {
 				return array ($sum , $rescount);
 			}
-    	}
-    }
-
-	// INTERNAL FUNCTIONS
+		}
+	}
 
-    /**
-     * Lazy load function to get the database table of the student publications
-     */
-    private function get_studpub_table() {    	
+	/**
+	 * Lazy load function to get the database table of the student publications
+	 */
+	private function get_studpub_table()
+	{
 		return $this->studpub_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
-    }
+	}
 
-    /**
-     * Lazy load function to get the database table of the item properties
-     */
-    private function get_itemprop_table () {
-    	return $this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-    }
+	/**
+	 * Lazy load function to get the database table of the item properties
+	 */
+	private function get_itemprop_table()
+	{
+		return $this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+	}
 
-   	public function needs_name_and_description() {
+	public function needs_name_and_description()
+	{
 		return false;
 	}
 
-	public function get_name() {
-    	$this->get_exercise_data();    	
-    	return (isset($this->exercise_data['title']) && !empty($this->exercise_data['title'])) ? $this->exercise_data['title'] : get_lang('Untitled');
-    }
+	public function get_name()
+	{
+		$this->get_exercise_data();
+		return (isset($this->exercise_data['title']) && !empty($this->exercise_data['title'])) ? $this->exercise_data['title'] : get_lang('Untitled');
+	}
 
-    public function get_description() {
-    	$this->get_exercise_data();
-    	return isset($this->exercise_data['description']) ? $this->exercise_data['description'] : null;
-    }
+	public function get_description()
+	{
+		$this->get_exercise_data();
+		return isset($this->exercise_data['description']) ? $this->exercise_data['description'] : null;
+	}
 
-    public function get_test_id() {
-    	return 'DEBUG:ID';
-    }
+	public function get_test_id()
+	{
+		return 'DEBUG:ID';
+	}
 
-    public function get_link() {
-        $session_id = api_get_session_id();
-		$url = api_get_path(WEB_PATH).'main/work/work.php?session_id='.$session_id.'&cidReq='.$this->get_course_code().'&id='.$this->exercise_data['id'].'&gradebook=view';		
+	public function get_link()
+	{
+		$session_id = api_get_session_id();
+		$url = api_get_path(WEB_PATH).'main/work/work.php?session_id='.$session_id.'&cidReq='.$this->get_course_code().'&id='.$this->exercise_data['id'].'&gradebook=view';
 		return $url;
 	}
 
-	private function get_exercise_data() {
+	private function get_exercise_data()
+	{
 		$tbl_name = $this->get_studpub_table();
 		$course_info = Database :: get_course_info($this->get_course_code());
 		if ($tbl_name=='') {
 			return false;
 		} elseif (!isset($this->exercise_data)) {
-    		$sql = 'SELECT * FROM '.$this->get_studpub_table()." WHERE c_id ='".$course_info['real_id']."' AND id = '".intval($this->get_ref_id())."' ";
+			$sql = 'SELECT * FROM '.$this->get_studpub_table()."
+					WHERE
+					 	c_id ='".$course_info['real_id']."' AND
+					 	id = '".intval($this->get_ref_id())."' ";
 			$query = Database::query($sql);
 			$this->exercise_data = Database::fetch_array($query);
-    	}
-    	return $this->exercise_data;
-    }
+		}
+		return $this->exercise_data;
+	}
 
-    public function needs_max() {
+	public function needs_max()
+	{
 		return false;
 	}
 
-	public function needs_results() {
+	public function needs_results()
+	{
 		return false;
 	}
 
-    public function is_valid_link() {    	    	
-    	$sql = 'SELECT count(id) FROM '.$this->get_studpub_table().' 
+	public function is_valid_link()
+	{
+		$sql = 'SELECT count(id) FROM '.$this->get_studpub_table().'
     			WHERE c_id = "'.$this->course_id.'" AND id = '.intval($this->get_ref_id()).'';
 		$result = Database::query($sql);
 		$number = Database::fetch_row($result);
 		return ($number[0] != 0);
-    }
+	}
 
-    public function get_icon_name() {
+	public function get_icon_name()
+	{
 		return 'studentpublication';
 	}
-    
-    function save_linked_data() {
-        $weight = (float)$this->get_weight();        
-        $ref_id = $this->get_ref_id();
-        
-        if (!empty($ref_id)) {
-            //Cleans works            
-            $sql = 'UPDATE '.$this->get_studpub_table().' SET weight= '.$weight.'
+
+	public function save_linked_data()
+	{
+		$weight = (float)$this->get_weight();
+		$ref_id = $this->get_ref_id();
+
+		if (!empty($ref_id)) {
+			//Cleans works
+			$sql = 'UPDATE '.$this->get_studpub_table().' SET weight= '.$weight.'
                     WHERE c_id = '.$this->course_id.' AND id ='.$ref_id;
-            Database::query($sql);
-        }
-    }
-    
-    function delete_linked_data() {
-        $ref_id = $this->get_ref_id();
-        if (!empty($ref_id)) {
-            //Cleans works            
-            $sql = 'UPDATE '.$this->get_studpub_table().' SET weight=0
+			Database::query($sql);
+		}
+	}
+
+	public function delete_linked_data()
+	{
+		$ref_id = $this->get_ref_id();
+		if (!empty($ref_id)) {
+			//Cleans works
+			$sql = 'UPDATE '.$this->get_studpub_table().' SET weight=0
                     WHERE c_id = '.$this->course_id.' AND id ='.$ref_id;
-            Database::query($sql);
-        }
-    }
-}
+			Database::query($sql);
+		}
+	}
+}

+ 152 - 125
main/gradebook/lib/be/surveylink.class.php

@@ -6,149 +6,169 @@
  * @author Ivan Tcholakov <ivantcholakov@gmail.com>, 2010
  * @package chamilo.gradebook
  */
-
-/**
- * Class
- * @package chamilo.gradebook
- */
 class SurveyLink extends AbstractLink
 {
-    private $survey_table = null;
+	private $survey_table = null;
 
-    public function __construct() {
-    	parent::__construct();
-    	$this->set_type(LINK_SURVEY);
-    }
+	public function __construct()
+	{
+		parent::__construct();
+		$this->set_type(LINK_SURVEY);
+	}
 
-	public function get_name() {
-    	$this->get_survey_data();
-    	return $this->survey_data['code'].': '.self::html_to_text($this->survey_data['title']);
-    }
+	public function get_name()
+	{
+		$this->get_survey_data();
+		return $this->survey_data['code'].': '.self::html_to_text($this->survey_data['title']);
+	}
 
-    public function get_description() {
-    	$this->get_survey_data();
-    	return $this->survey_data['subtitle'];
-    }
+	public function get_description()
+	{
+		$this->get_survey_data();
+		return $this->survey_data['subtitle'];
+	}
 
-    public function get_type_name() {
-    	return get_lang('Survey');
-    }
+	public function get_type_name()
+	{
+		return get_lang('Survey');
+	}
 
-	public function is_allowed_to_change_name() {
+	public function is_allowed_to_change_name()
+	{
 		return false;
 	}
 
-	public function needs_name_and_description() {
+	public function needs_name_and_description()
+	{
 		return false;
 	}
 
-    public function needs_max() {
-        return false;
-    }
+	public function needs_max()
+	{
+		return false;
+	}
 
-    public function needs_results() {
-        return false;
-    }
+	public function needs_results()
+	{
+		return false;
+	}
 
-    /**
+	/**
 	 * Generates an array of all surveys available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links() {
-    	if (empty($this->course_code)) {
-    		die('Error in get_all_links() : course code not set');
-    	}
-    	$tbl_survey = $this->get_survey_table();
-    	$session_id = api_get_session_id();
-    	$course_id = api_get_course_int_id();
-    	$sql = 'SELECT survey_id, title, code FROM '.$tbl_survey.' WHERE c_id = '.$course_id.' AND session_id = '.intval($session_id).'';
+	public function get_all_links()
+	{
+		if (empty($this->course_code)) {
+			die('Error in get_all_links() : course code not set');
+		}
+		$tbl_survey = $this->get_survey_table();
+		$session_id = api_get_session_id();
+		$course_id = api_get_course_int_id();
+		$sql = 'SELECT survey_id, title, code FROM '.$tbl_survey.'
+				WHERE c_id = '.$course_id.' AND session_id = '.intval($session_id).'';
 		$result = Database::query($sql);
 		while ($data = Database::fetch_array($result)) {
 			$links[] = array($data['survey_id'], api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
 		};
 		return isset($links) ? $links : null;
-    }
+	}
 
-    /**
+	/**
 	 * Generates an array of surveys that a teacher hasn't created a link for.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_not_created_links() {
-    	if (empty($this->course_code)) {
-    		die('Error in get_not_created_links() : course code not set');
-    	}
-    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+	public function get_not_created_links()
+	{
+		if (empty($this->course_code)) {
+			die('Error in get_not_created_links() : course code not set');
+		}
+		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 
-    	$sql = 'SELECT survey_id, title, code
+		$sql = 'SELECT survey_id, title, code
     			FROM '.$this->get_survey_table().' AS srv
 				WHERE survey_id NOT IN
 					(SELECT ref_id FROM '.$tbl_grade_links.'
 					WHERE type = '.LINK_SURVEY." AND course_code = '".$this->get_course_code()."'"
-				.') AND srv.session_id='.api_get_session_id().'';
+			.') AND srv.session_id='.api_get_session_id().'';
 		$result = Database::query($sql);
 
 		$links = array();
 		while ($data = Database::fetch_array($result)) {
-			$links[] = array($data['survey_id'], api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
+			$links[] = array(
+				$data['survey_id'],
+				api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80)
+			);
 		}
 		return $links;
-    }
+	}
 
-    /**
-     * Has anyone done this survey yet?
-     */
-    public function has_results($stud_id=null) {
-    	$ref_id = intval($this->get_ref_id());
+	/**
+	 * Has anyone done this survey yet?
+	 */
+	public function has_results($stud_id=null)
+	{
+		$ref_id = intval($this->get_ref_id());
 		$session_id = api_get_session_id();
 		$tbl_survey = Database::get_course_table(TABLE_SURVEY);
 		$tbl_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
 		$get_individual_score = !is_null($stud_id);
-		$sql = "SELECT COUNT(i.answered) FROM $tbl_survey AS s JOIN $tbl_survey_invitation AS i ON s.code = i.survey_code
-				WHERE 	s.c_id = {$this->course_id} AND
-						i.c_id = {$this->course_id} AND 
-						s.survey_id = $ref_id AND 
-						i.session_id = $session_id";
+		$sql = "SELECT
+				COUNT(i.answered)
+				FROM $tbl_survey AS s
+				JOIN $tbl_survey_invitation AS i ON s.code = i.survey_code
+				WHERE
+					s.c_id = {$this->course_id} AND
+					i.c_id = {$this->course_id} AND
+					s.survey_id = $ref_id AND
+					i.session_id = $session_id";
 
 		$sql_result = Database::query($sql);
 		$data = Database::fetch_array($sql_result);
+
 		return ($data[0] != 0);
-	
-    }
+	}
 
-    public function calc_score($stud_id = null) {
+	/**
+	 * @param int $stud_id
+	 * @return array|null
+	 */
+	public function calc_score($stud_id = null)
+	{
+		// Note: Max score is assumed to be always 1 for surveys,
+		// only student's participation is to be taken into account.
+		$max_score = 1;
 
-    	// Note: Max score is assumed to be always 1 for surveys,
-    	// only student's participation is to be taken into account.
-    	$max_score = 1;
-    	
-    	$ref_id = intval($this->get_ref_id());
+		$ref_id = intval($this->get_ref_id());
 		$session_id = api_get_session_id();
-		$tbl_survey = Database::get_course_table(TABLE_SURVEY, $database_name);
-		$tbl_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION, $database_name);
+		$tbl_survey = Database::get_course_table(TABLE_SURVEY);
+		$tbl_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
 
 		$get_individual_score = !is_null($stud_id);
 
-		$sql = "SELECT i.answered FROM $tbl_survey AS s JOIN $tbl_survey_invitation AS i
+		$sql = "SELECT i.answered
+				FROM $tbl_survey AS s
+				JOIN $tbl_survey_invitation AS i
 				ON s.code = i.survey_code
-				WHERE 	s.c_id = {$this->course_id} AND
-						i.c_id = {$this->course_id} AND 
-						s.survey_id = $ref_id AND i.session_id = $session_id";
+				WHERE
+					s.c_id = {$this->course_id} AND
+					i.c_id = {$this->course_id} AND
+					s.survey_id = $ref_id AND i.session_id = $session_id";
 
 		if ($get_individual_score) {
-	    	$sql .= ' AND i.user = '.intval($stud_id);
-	    }
+			$sql .= ' AND i.user = '.intval($stud_id);
+		}
 
 		$sql_result = Database::query($sql);
 
 		if ($get_individual_score) {
-				// for 1 student
+			// for 1 student
 			if ($data = Database::fetch_array($sql_result)) {
 				return array ($data['answered'] ? $max_score : 0, $max_score);
 			}
 			return array(0, $max_score);
 		} else {
 			// for all the students -> get average
-			$students = array();
 			$rescount = 0;
 			$sum = 0;
 			while ($data = Database::fetch_array($sql_result)) {
@@ -160,50 +180,55 @@ class SurveyLink extends AbstractLink
 				return null;
 			}
 			return array($sum, $rescount);
-		}		
-    }
-
-    /**
-     * Lazy load function to get the database table of the surveys
-     */
-    private function get_survey_table() {
-    	$this->survey_table = Database :: get_course_table(TABLE_SURVEY);
-   		return $this->survey_table;		
-    }
-
-    /**
-     * Check if this still links to a survey
-     */
-    public function is_valid_link() {
-    	$session_id = api_get_session_id();
-        $sql = 'SELECT count(survey_id) FROM '.$this->get_survey_table().'
+		}
+	}
+
+	/**
+	 * Lazy load function to get the database table of the surveys
+	 */
+	private function get_survey_table()
+	{
+		$this->survey_table = Database :: get_course_table(TABLE_SURVEY);
+		return $this->survey_table;
+	}
+
+	/**
+	 * Check if this still links to a survey
+	 */
+	public function is_valid_link()
+	{
+		$session_id = api_get_session_id();
+		$sql = 'SELECT count(survey_id) FROM '.$this->get_survey_table().'
         		 WHERE c_id = '.$this->course_id.' AND survey_id = '.intval($this->get_ref_id()).' AND session_id='.intval($session_id).'';
-        $result = Database::query($sql);
-        $number = Database::fetch_row($result);
-        return ($number[0] != 0);
-    }
-
-    public function get_test_id() {
-    	return 'DEBUG:ID';
-    }
-
-    public function get_link() {
-   		if (api_is_allowed_to_edit()) { // Let students make access only through "Surveys" tool.
-   			$tbl_name = $this->get_survey_table();
-   			$session_id = api_get_session_id();
-   			if ($tbl_name != '') {
-   				$sql = 'SELECT survey_id FROM '.$this->get_survey_table().'
+		$result = Database::query($sql);
+		$number = Database::fetch_row($result);
+		return ($number[0] != 0);
+	}
+
+	public function get_test_id()
+	{
+		return 'DEBUG:ID';
+	}
+
+	public function get_link()
+	{
+		if (api_is_allowed_to_edit()) { // Let students make access only through "Surveys" tool.
+			$tbl_name = $this->get_survey_table();
+			$session_id = api_get_session_id();
+			if ($tbl_name != '') {
+				$sql = 'SELECT survey_id FROM '.$this->get_survey_table().'
     					WHERE c_id = '.$this->course_id.' AND survey_id = '.intval($this->get_ref_id()).' AND session_id = '.intval($session_id).' ';
-   				$result = Database::query($sql);
-   				$row = Database::fetch_array($result, 'ASSOC');
-   				$survey_id = $row['survey_id'];
-   				return api_get_path(WEB_PATH).'main/survey/reporting.php?cidReq='.$this->get_course_code().'&survey_id='.$survey_id;
-   			}
-   		}
-   		return null;
-    }
-
-	private function get_survey_data() {
+				$result = Database::query($sql);
+				$row = Database::fetch_array($result, 'ASSOC');
+				$survey_id = $row['survey_id'];
+				return api_get_path(WEB_PATH).'main/survey/reporting.php?cidReq='.$this->get_course_code().'&survey_id='.$survey_id;
+			}
+		}
+		return null;
+	}
+
+	private function get_survey_data()
+	{
 		$tbl_name = $this->get_survey_table();
 		$session_id = api_get_session_id();
 		if ($tbl_name == '') {
@@ -212,15 +237,17 @@ class SurveyLink extends AbstractLink
 			$sql = 'SELECT * FROM '.$tbl_name.' WHERE c_id = '.$this->course_id.' AND survey_id = '.intval($this->get_ref_id()).' AND session_id='.intval($session_id).'';
 			$query = Database::query($sql);
 			$this->survey_data = Database::fetch_array($query);
-    	}
-    	return $this->survey_data;
-    }
+		}
+		return $this->survey_data;
+	}
 
-    public function get_icon_name() {
+	public function get_icon_name()
+	{
 		return 'survey';
 	}
 
-	private static function html_to_text($string) {
+	private static function html_to_text($string)
+	{
 		return trim(api_html_entity_decode(strip_tags(str_ireplace(array('<p>', '</p>', '<br />', '<br/>', '<br>'), array('', ' ', ' ', ' ', ' '), $string)), ENT_QUOTES));
 	}
-}
+}

+ 30 - 32
main/gradebook/lib/fe/catform.class.php

@@ -12,12 +12,10 @@ require_once dirname(__FILE__).'/../be.inc.php';
  */
 class CatForm extends FormValidator
 {
-
-    const TYPE_ADD              = 1;
-    const TYPE_EDIT             = 2;
-    const TYPE_MOVE             = 3;
-    const TYPE_SELECT_COURSE    = 4;
-
+    const TYPE_ADD = 1;
+    const TYPE_EDIT = 2;
+    const TYPE_MOVE = 3;
+    const TYPE_SELECT_COURSE = 4;
     private $category_object;
 
     /**
@@ -132,16 +130,16 @@ class CatForm extends FormValidator
         $this->build_basic_form();
     }
 
-	/**
-	 * Builds an form to edit a category
-	 */
+    /**
+     * Builds an form to edit a category
+     */
     protected function build_editing_form()
     {
         $skills = $this->category_object->get_skills_for_select();
 
         $course_code = api_get_course_id();
         $session_id = api_get_session_id();
-         //Freeze or not
+        //Freeze or not
         $test_cats = Category::load(
             null,
             null,
@@ -388,37 +386,37 @@ class CatForm extends FormValidator
             $visibility_default = 0;
         }
         $this->setDefaults(array('visible' => $visibility_default));
-   	}
+    }
 
     /**
-	 * This function builds an 'select course' form in the add category process,
-	 * if parent id is 0, it will only show courses
-	 */
+     * This function builds an 'select course' form in the add category process,
+     * if parent id is 0, it will only show courses
+     */
     protected function build_select_course_form()
     {
-		$select = $this->addElement('select','select_course',array(get_lang('PickACourse'),'test'), null);
-		$coursecat = Category :: get_all_courses(api_get_user_id());
-		//only return courses that are not yet created by the teacher
-
-		foreach($coursecat as $row) {
-			$select->addoption($row[1],$row[0]);
-		}
-		$this->setDefaults(array(
-		   'hid_user_id' => $this->category_object->get_user_id(),
-		   'hid_parent_id' => $this->category_object->get_parent_id()
-		));
-   		$this->addElement('hidden','hid_user_id');
-   		$this->addElement('hidden','hid_parent_id');
-		$this->addElement('submit', null, get_lang('Ok'));
-   	}
+        $select = $this->addElement('select','select_course',array(get_lang('PickACourse'),'test'), null);
+        $coursecat = Category :: get_all_courses(api_get_user_id());
+        //only return courses that are not yet created by the teacher
+
+        foreach($coursecat as $row) {
+            $select->addoption($row[1],$row[0]);
+        }
+        $this->setDefaults(array(
+            'hid_user_id' => $this->category_object->get_user_id(),
+            'hid_parent_id' => $this->category_object->get_parent_id()
+        ));
+        $this->addElement('hidden','hid_user_id');
+        $this->addElement('hidden','hid_parent_id');
+        $this->addElement('submit', null, get_lang('Ok'));
+    }
 
     function display()
     {
-   		parent :: display();
-   	}
+        parent :: display();
+    }
 
     function setDefaults($defaults = array(), $filter = null)
     {
         parent::setDefaults($defaults, $filter);
-   	}
+    }
 }

+ 24 - 27
main/gradebook/lib/fe/dataform.class.php

@@ -1,24 +1,18 @@
 <?php
 /* For licensing terms, see /license.txt */
-/**
- * Script
- * @package chamilo.gradebook
- */
-/**
- * Init
- */
+
 require_once dirname(__FILE__).'/../../../inc/global.inc.php';
 require_once dirname(__FILE__).'/../be.inc.php';
 require_once dirname(__FILE__).'/../gradebook_functions.inc.php';
 require_once api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php';
 
 /**
- * Extends formvalidator with import and export forms
+ * Extends FormValidator with import and export forms
  * @author Stijn Konings
  * @package chamilo.gradebook
  */
-class DataForm extends FormValidator {
-
+class DataForm extends FormValidator
+{
 	const TYPE_IMPORT = 1;
 	const TYPE_EXPORT = 2;
 	const TYPE_EXPORT_PDF = 3;
@@ -32,27 +26,26 @@ class DataForm extends FormValidator {
 	 * @param method
 	 * @param action
 	 */
-	function DataForm($form_type, $form_name, $method = 'post', $action = null, $target='', $locked_status) {
+	public function DataForm($form_type, $form_name, $method = 'post', $action = null, $target='', $locked_status)
+	{
 		parent :: __construct($form_name, $method, $action,$target);
 		$this->form_type = $form_type;
 		if ($this->form_type == self :: TYPE_IMPORT) {
 			$this->build_import_form();
-		}
-		elseif ($this->form_type == self :: TYPE_EXPORT) {
+		} elseif ($this->form_type == self :: TYPE_EXPORT) {
 			if ($locked_status == 0) {
 				$this->build_export_form_option(false);
 			} else {
 				$this->build_export_form();
-			}			
-		}
-		elseif ($this->form_type == self :: TYPE_EXPORT_PDF) {
+			}
+		} elseif ($this->form_type == self :: TYPE_EXPORT_PDF) {
 			$this->build_pdf_export_form();
 		}
 		$this->setDefaults();
 	}
 
-
-	protected function build_pdf_export_form() {
+	protected function build_pdf_export_form()
+	{
 		$renderer =& $this->defaultRenderer();
 		$renderer->setElementTemplate('<span>{element}</span>');
 		$this->addElement('header', get_lang('ChooseOrientation'));
@@ -64,8 +57,8 @@ class DataForm extends FormValidator {
 		));
 	}
 
-
-	protected function build_export_form() {
+	protected function build_export_form()
+	{
 		$this->addElement('header', get_lang('ChooseFormat'));
 		$this->addElement('radio', 'file_type', get_lang('OutputFileType'), 'CSV (Comma-Separated Values)', 'csv');
 		$this->addElement('radio', 'file_type', null, 'XML (Extensible Markup Language)', 'xml');
@@ -76,18 +69,20 @@ class DataForm extends FormValidator {
 		));
 	}
 
-	protected function build_export_form_option($show_pdf=true) {
+	protected function build_export_form_option($show_pdf=true)
+	{
 		$this->addElement('header', get_lang('ChooseFormat'));
 		$this->addElement('radio', 'file_type', get_lang('OutputFileType'), 'CSV (Comma-Separated Values)', 'csv');
 		$this->addElement('radio', 'file_type', null, 'XML (Extensible Markup Language)', 'xml');
-		$this->addElement('radio', 'file_type', Display::return_icon('info3.gif',get_lang('ToExportMustLockEvaluation')), 'PDF (Portable Document Format)', 'pdf', array('disabled'));			
+		$this->addElement('radio', 'file_type', Display::return_icon('info3.gif',get_lang('ToExportMustLockEvaluation')), 'PDF (Portable Document Format)', 'pdf', array('disabled'));
 		$this->addElement('style_submit_button', 'submit', get_lang('Export'), 'class="upload"');
 		$this->setDefaults(array (
 			'file_type' => 'csv'
 		));
 	}
 
-	protected function build_import_form() {
+	protected function build_import_form()
+	{
 		$this->addElement('hidden', 'formSent');
 		$this->addElement('header', get_lang('ImportFileLocation'));
 		$this->addElement('file', 'import_file',get_lang('Location'));
@@ -102,16 +97,18 @@ class DataForm extends FormValidator {
 		$this->addElement('checkbox','ignoreerrors',null,get_lang('IgnoreErrors'));
 		$this->addElement('style_submit_button', 'submit', get_lang('Ok'));
 		$this->setDefaults(array(
-		'formSent' => '1',
-		'file_type' => 'csv'
+			'formSent' => '1',
+			'file_type' => 'csv'
 		));
 	}
 
-	function display() {
+	public function display()
+	{
 		parent :: display();
 	}
 
-	function setDefaults($defaults = array(), $filter = null) {
+	public function setDefaults($defaults = array(), $filter = null)
+	{
 		parent :: setDefaults($defaults, $filter);
 	}
 }

+ 107 - 71
main/gradebook/lib/fe/displaygradebook.php

@@ -1,16 +1,12 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
- * Script
- * @package chamilo.gradebook
- */
-/**
- * Class
+ * Class DisplayGradebook
  * @package chamilo.gradebook
  */
 class DisplayGradebook
 {
-
     /**
      * Displays the header for the result page containing the navigation tree and links
      * @param $evalobj
@@ -18,37 +14,43 @@ class DisplayGradebook
      * @param $shownavbar 1=show navigation bar
      * @param $forpdf only output for pdf file
      */
-    static function display_header_result($evalobj, $selectcat, $page)
+    public static function display_header_result($evalobj, $selectcat, $page)
     {
         $header = null;
         if (api_is_allowed_to_edit(null, true)) {
             $header = '<div class="actions">';
             if ($page != 'statistics') {
-                $header .= '<a href="' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $selectcat . '">' . Display::return_icon(('back.png'), get_lang('FolderView'), '', ICON_SIZE_MEDIUM) . '</a>';
+                $header .= '<a href="' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $selectcat . '">' .
+                    Display::return_icon(('back.png'), get_lang('FolderView'), '', ICON_SIZE_MEDIUM) . '</a>';
                 if ($evalobj->get_course_code() == null) {
-                    //Disabling code when course code is null see issue #2705
-                    //$header .= '<a href="gradebook_add_user.php?selecteval=' . $evalobj->get_id() . '"><img src="../img/add_user_big.gif" alt="' . get_lang('AddStudent') . '" align="absmiddle" /> ' . get_lang('AddStudent') . '</a>';
+
                 } elseif (!$evalobj->has_results()) {
                     $header .= '<a href="gradebook_add_result.php?selectcat=' . $selectcat . '&selecteval=' . $evalobj->get_id() . '">
     				' . Display::return_icon('evaluation_rate.png', get_lang('AddResult'), '', ICON_SIZE_MEDIUM) . '</a>';
                 }
 
                 if (api_is_platform_admin() || $evalobj->is_locked() == false) {
-                    $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&import=">' . Display::return_icon('import_evaluation.png', get_lang('ImportResult'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&import=">' .
+                        Display::return_icon('import_evaluation.png', get_lang('ImportResult'), '', ICON_SIZE_MEDIUM) . '</a>';
                 }
 
                 if ($evalobj->has_results()) {
-                    $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&export=">' . Display::return_icon('export_evaluation.png', get_lang('ExportResult'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&export=">' .
+                        Display::return_icon('export_evaluation.png', get_lang('ExportResult'), '', ICON_SIZE_MEDIUM) . '</a>';
 
                     if (api_is_platform_admin() || $evalobj->is_locked() == false) {
-                        $header .= '<a href="gradebook_edit_result.php?selecteval=' . $evalobj->get_id() . '">' . Display::return_icon('edit.png', get_lang('EditResult'), '', ICON_SIZE_MEDIUM) . '</a>';
-                        $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&deleteall=" onclick="return confirmationall();">' . Display::return_icon('delete.png', get_lang('DeleteResult'), '', ICON_SIZE_MEDIUM) . '</a>';
+                        $header .= '<a href="gradebook_edit_result.php?selecteval=' . $evalobj->get_id() . '">' .
+                            Display::return_icon('edit.png', get_lang('EditResult'), '', ICON_SIZE_MEDIUM) . '</a>';
+                        $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&deleteall=" onclick="return confirmationall();">' .
+                            Display::return_icon('delete.png', get_lang('DeleteResult'), '', ICON_SIZE_MEDIUM) . '</a>';
                     }
                 }
 
-                $header .= '<a href="' . api_get_self() . '?print=&selecteval=' . $evalobj->get_id() . '" target="_blank">' . Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM) . '</a>';
+                $header .= '<a href="' . api_get_self() . '?print=&selecteval=' . $evalobj->get_id() . '" target="_blank">' .
+                    Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM) . '</a>';
             } else {
-                $header .= '<a href="gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '"> ' . Display::return_icon(('back.png'), get_lang('FolderView'), '', ICON_SIZE_MEDIUM) . '</a>';
+                $header .= '<a href="gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '"> ' .
+                    Display::return_icon(('back.png'), get_lang('FolderView'), '', ICON_SIZE_MEDIUM) . '</a>';
             }
             $header .= '</div>';
         }
@@ -69,7 +71,10 @@ class DisplayGradebook
             if ($score != null) {
                 $average = get_lang('Average') . ' :<b> ' . $scoredisplay->display_score($score, SCORE_AVERAGE) . '</b>';
                 $student_score = $evalobj->calc_score(api_get_user_id());
-                $student_score = Display::tag('h3', get_lang('Score') . ': ' . $scoredisplay->display_score($student_score, SCORE_DIV_PERCENT));
+                $student_score = Display::tag(
+                    'h3',
+                    get_lang('Score') . ': ' . $scoredisplay->display_score($student_score, SCORE_DIV_PERCENT)
+                );
             }
         }
         $description = "";
@@ -119,7 +124,7 @@ class DisplayGradebook
      * @param $showeval
      * @param $showlink
      */
-    function display_header_flatview($catobj, $showeval, $showlink, $simple_search_form)
+    public function display_header_flatview($catobj, $showeval, $showlink, $simple_search_form)
     {
         $header = '<table border="0" cellpadding="5">';
         $header .= '<td style="vertical-align: top;"><a href="' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . Security::remove_XSS($_GET['selectcat']) . '">' . Display::return_icon('gradebook.gif') . get_lang('Gradebook') . '</a></td>';
@@ -162,7 +167,7 @@ class DisplayGradebook
      * @param $showeval
      * @param $showlink
      */
-    static function display_header_reduce_flatview($catobj, $showeval, $showlink, $simple_search_form)
+    public static function display_header_reduce_flatview($catobj, $showeval, $showlink, $simple_search_form)
     {
         $header = '<div class="actions">';
         if ($catobj->get_parent_id() == 0) {
@@ -172,7 +177,8 @@ class DisplayGradebook
             $select_cat = $catobj->get_parent_id();
             $url = 'gradebook_flatview.php';
         }
-        $header .= '<a href="' . $url . '?' . api_get_cidreq() . '&selectcat=' . $select_cat . '">' . Display::return_icon('back.png', get_lang('FolderView'), '', ICON_SIZE_MEDIUM) . '</a>';
+        $header .= '<a href="' . $url . '?' . api_get_cidreq() . '&selectcat=' . $select_cat . '">' .
+            Display::return_icon('back.png', get_lang('FolderView'), '', ICON_SIZE_MEDIUM) . '</a>';
 
 
         // this MUST be a GET variable not a POST
@@ -181,16 +187,26 @@ class DisplayGradebook
         } else {
             $show = '';
         }
-        $header .= '<a href="' . api_get_self() . '?export_format=csv&export_report=export_report&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), '', ICON_SIZE_MEDIUM) . '</a>';
-        $header .= '<a href="' . api_get_self() . '?export_format=xls&export_report=export_report&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), '', ICON_SIZE_MEDIUM) . '</a>';
-        $header .= '<a href="' . api_get_self() . '?export_format=doc&export_report=export_report&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('export_doc.png', get_lang('ExportAsDOC'), '', ICON_SIZE_MEDIUM) . '</a>';
-        $header .= '<a href="' . api_get_self() . '?print=&selectcat=' . $catobj->get_id() . '" target="_blank">' . Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM) . '</a>';
-        $header .= '<a href="' . api_get_self() . '?exportpdf=&selectcat=' . $catobj->get_id() . '" >' . Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_MEDIUM) . '</a>';
+        $header .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&export_format=csv&export_report=export_report&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), '', ICON_SIZE_MEDIUM) . '</a>';
+        $header .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&export_format=xls&export_report=export_report&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), '', ICON_SIZE_MEDIUM) . '</a>';
+        $header .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&export_format=doc&export_report=export_report&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('export_doc.png', get_lang('ExportAsDOC'), '', ICON_SIZE_MEDIUM) . '</a>';
+        $header .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&print=&selectcat=' . $catobj->get_id() . '" target="_blank">' . Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM) . '</a>';
+        $header .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&exportpdf=&selectcat=' . $catobj->get_id().'" >' . Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_MEDIUM) . '</a>';
         $header .= '</div>';
         echo $header;
     }
 
-    function display_header_gradebook_per_gradebook($catobj, $showtree, $selectcat, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true)
+    /**
+     * @param Category $catobj
+     * @param $showtree
+     * @param $selectcat
+     * @param $is_course_admin
+     * @param $is_platform_admin
+     * @param $simple_search_form
+     * @param bool $show_add_qualification
+     * @param bool $show_add_link
+     */
+    public function display_header_gradebook_per_gradebook($catobj, $showtree, $selectcat, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true)
     {
         // Student
         $status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
@@ -372,7 +388,8 @@ class DisplayGradebook
         $is_platform_admin,
         $simple_search_form,
         $show_add_qualification = true,
-        $show_add_link = true
+        $show_add_link = true,
+        $certificateLinkInfo = null
     ) {
         // Student.
         $status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
@@ -434,7 +451,12 @@ class DisplayGradebook
             $total_score = array($item_value_total, $item_total);
             $scorecourse_display = $scoredisplay->display_score($total_score, SCORE_DIV_PERCENT);
             if ((!$catobj->get_id() == '0') && (!isset($_GET['studentoverview'])) && (!isset($_GET['search']))) {
-                $scoreinfo .= '<h2>' . get_lang('Total') . ' : ' . $scorecourse_display . '</h2>';
+                $certificateLink = null;
+                if (!empty($certificateLinkInfo) && isset($certificateLinkInfo['certificate_link'])) {
+                    $certificateLink .= '<span style="float:right"> ' . $certificateLinkInfo['certificate_link']."</span>";
+                }
+                $scoreinfo .= '<h3>' . get_lang('Total') . ' : ' . $scorecourse_display . $certificateLink. '</h3>';
+
             }
             Display :: display_normal_message($scoreinfo, false);
         }
@@ -444,7 +466,8 @@ class DisplayGradebook
             $header = '<div class="actions"><table>';
             $header .= '<tr>';
             if (!$selectcat == '0') {
-                $header .= '<td><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '">' . Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('RootCat'), '', ICON_SIZE_MEDIUM) . '</a></td>';
+                $header .= '<td><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '">' .
+                    Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('RootCat'), '', ICON_SIZE_MEDIUM) . '</a></td>';
             }
             $header .= '<td>' . get_lang('CurrentCategory') . '</td>' .
                     '<td><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
@@ -493,66 +516,56 @@ class DisplayGradebook
 
         $my_category = $catobj->shows_all_information_an_category($catobj->get_id());
         $user_id = api_get_user_id();
+        $my_api_cidreq = api_get_cidreq();
 
         //$course_code = $my_category['course_code'];
         //$status_user = api_get_status_of_user_in_course ($user_id,$course_code);
 
         if (api_is_allowed_to_edit(null, true)) {
-
             if (empty($grade_model_id) || $grade_model_id == -1) {
-                $header .= '<a href="gradebook_add_cat.php?' . api_get_cidreq() . '&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('new_folder.png', get_lang('AddGradebook'), array(), ICON_SIZE_MEDIUM) . '</a></td>';
+                $header .= '<a href="gradebook_add_cat.php?' . api_get_cidreq() . '&selectcat=' . $catobj->get_id() . '">' .
+                    Display::return_icon('new_folder.png', get_lang('AddGradebook'), array(), ICON_SIZE_MEDIUM) . '</a></td>';
             }
-
             if ($selectcat == '0') {
-                if ($show_add_qualification === true) {
 
-                }
-                if ($show_add_link) {
-                    //$header .= '<td><a href="gradebook_add_eval.php?'.api_get_cidreq().'"><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" /> ' . get_lang('NewEvaluation') . '</a>';
-                }
             } else {
-                if ($show_add_qualification === true && $message_resource === false) {
-                    //$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '" ><img src="../img/folder_new.gif" alt="' . get_lang('NewSubCategory') . '" align="absmiddle" /> ' . get_lang('NewSubCategory') . '</a></td>';
-                }
                 $my_category = $catobj->shows_all_information_an_category($catobj->get_id());
-
-                $my_api_cidreq = api_get_cidreq();
                 if ($my_api_cidreq == '') {
                     $my_api_cidreq = 'cidReq=' . $my_category['course_code'];
                 }
                 if ($show_add_link && !$message_resource) {
-                    $header .= '<td><a href="gradebook_add_eval.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '" >' . Display::return_icon('new_evaluation.png', get_lang('NewEvaluation'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    $header .= '<td><a href="gradebook_add_eval.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '" >' .
+                        Display::return_icon('new_evaluation.png', get_lang('NewEvaluation'), '', ICON_SIZE_MEDIUM) . '</a>';
                     $cats = Category :: load($selectcat);
+
                     if ($cats[0]->get_course_code() != null && !$message_resource) {
-                        //$header .= '<td><a href="gradebook_add_link.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
-                        $header .= '<td><a href="gradebook_add_link.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'), '', ICON_SIZE_MEDIUM) . '</a>';
+                        $header .= '<td><a href="gradebook_add_link.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' .
+                            Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'), '', ICON_SIZE_MEDIUM) . '</a>';
                     } else {
-                        $header .= '<td><a href="gradebook_add_link_select_course.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'), '', ICON_SIZE_MEDIUM) . '</a>';
+                        $header .= '<td><a href="gradebook_add_link_select_course.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' .
+                            Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'), '', ICON_SIZE_MEDIUM) . '</a>';
                     }
                 }
 
                 if (!$message_resource) {
-                    //$myname = $catobj->shows_all_information_an_category($catobj->get_id());
-                    //$my_course_id=api_get_course_id();
-                    //$my_file= substr($_SESSION['gradebook_dest'],0,5);
-
-                    $header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('stats.png', get_lang('FlatView'), '', ICON_SIZE_MEDIUM) . '</a>';
-                    $header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?' . $my_api_cidreq . '&amp;cat_id=' . (int) $_GET['selectcat'] . '">' . Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'), '', ICON_SIZE_MEDIUM) . '</a>';
-
-                    //$visibility_icon    = ($catobj->is_visible() == 0) ? 'invisible' : 'visible';
-                    //$visibility_command = ($catobj->is_visible() == 0) ? 'set_visible' : 'set_invisible';
-                    //Right icons
-
-                    $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '">' . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    $header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' .
+                        Display::return_icon('stats.png', get_lang('FlatView'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    $header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?' . $my_api_cidreq . '&amp;cat_id=' . (int) $_GET['selectcat'] . '">' .
+                        Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    // Right icons
+                    $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '">' .
+                        Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_MEDIUM) . '</a>';
                     $modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&' . $my_api_cidreq . '&origin=gradebook&selectcat=' . $catobj->get_id() . '">' .
                             Display::return_icon('certificate.png', get_lang('AttachCertificate'), '', ICON_SIZE_MEDIUM) . '</a>';
 
                     if (empty($categories)) {
-                        $modify_icons .= '<a href="gradebook_edit_all.php?id_session=' . api_get_session_id() . '&amp;' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('percentage.png', get_lang('EditAllWeights'), '', ICON_SIZE_MEDIUM) . '</a>';
+                        $modify_icons .= '<a href="gradebook_edit_all.php?id_session=' . api_get_session_id() . '&amp;' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' .
+                            Display::return_icon('percentage.png', get_lang('EditAllWeights'), '', ICON_SIZE_MEDIUM) . '</a>';
                     }
                     $score_display_custom = api_get_setting('gradebook_score_display_custom');
                     if (api_get_setting('teachers_can_change_score_settings') == 'true' && $score_display_custom['my_display_custom'] == 'true') {
-                        $modify_icons .= '<a href="gradebook_scoring_system.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' . Display::return_icon('ranking.png', get_lang('ScoreEdit'), '', ICON_SIZE_MEDIUM) . '</a>';
+                        $modify_icons .= '<a href="gradebook_scoring_system.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' .
+                            Display::return_icon('ranking.png', get_lang('ScoreEdit'), '', ICON_SIZE_MEDIUM) . '</a>';
                     }
                     $header .= Display::div($modify_icons, array('class' => 'right'));
                 }
@@ -560,6 +573,19 @@ class DisplayGradebook
         } elseif (isset($_GET['search'])) {
             $header .= '<b>' . get_lang('SearchResults') . ' :</b>';
         }
+
+        $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
+            api_get_user_id(),
+            api_get_course_info()
+        );
+
+        if ($isDrhOfCourse) {
+            $header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?' . $my_api_cidreq . '&selectcat=' . $catobj->get_id() . '">' .
+                Display::return_icon('stats.png', get_lang('FlatView'), '', ICON_SIZE_MEDIUM) . '</a>';
+            /*$header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?' . $my_api_cidreq . '&amp;cat_id=' . (int) $_GET['selectcat'] . '">' .
+                Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'), '', ICON_SIZE_MEDIUM) . '</a>';*/
+        }
+
         $header .= '</div>';
 
         echo $header;
@@ -570,7 +596,8 @@ class DisplayGradebook
 
             $min_certification = (intval($catobj->get_certificate_min_score() > 0) ? $catobj->get_certificate_min_score() : 0);
             $min_certification = get_lang('CertificateMinScore') . ' : ' . $min_certification;
-            $edit_icon = '<a class="right_link" href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '">' . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
+            $edit_icon = '<a class="right_link" href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '">' .
+                Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
             //$msg = Display::tag('h3', $weight.' - '.$min_certification);
             $msg = Display::tag('h4', $weight . ' - ' . $min_certification . $edit_icon);
             //@todo show description
@@ -582,11 +609,19 @@ class DisplayGradebook
         }
     }
 
-    function display_reduce_header_gradebook($catobj, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true)
+    /**
+     * @param Category $catobj
+     * @param $is_course_admin
+     * @param $is_platform_admin
+     * @param $simple_search_form
+     * @param bool $show_add_qualification
+     * @param bool $show_add_link
+     */
+    public function display_reduce_header_gradebook($catobj, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true)
     {
         //student
         if (!$is_course_admin) {
-            $user = get_user_info_from_id(api_get_user_id());
+            $user = api_get_user_info(api_get_user_id());
             $catcourse = Category :: load($catobj->get_id());
             $scoredisplay = ScoreDisplay :: instance();
             $scorecourse = $catcourse[0]->calc_score(api_get_user_id());
@@ -594,7 +629,7 @@ class DisplayGradebook
             $cattotal = Category :: load(0);
             $scoretotal = $cattotal[0]->calc_score(api_get_user_id());
             $scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal, SCORE_PERCENT) : get_lang('NoResultsAvailable'));
-            $scoreinfo = get_lang('StatsStudent') . ' :<b> ' . api_get_person_name($user['firstname'], $user['lastname']) . '</b><br />';
+            $scoreinfo = get_lang('StatsStudent') . ' :<b> ' . $user['complete_name']. '</b><br />';
             if ((!$catobj->get_id() == '0') && (!isset($_GET['studentoverview'])) && (!isset($_GET['search'])))
                 $scoreinfo.= '<br />' . get_lang('TotalForThisCategory') . ' : <b>' . $scorecourse_display . '</b>';
             $scoreinfo.= '<br />' . get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
@@ -615,11 +650,14 @@ class DisplayGradebook
         echo $header;
     }
 
-    function display_header_user($userid)
+    /**
+     * @param int $userid
+     */
+    public static function display_header_user($userid)
     {
         $select_cat = intval($_GET['selectcat']);
         $user_id = $userid;
-        $user = get_user_info_from_id($user_id);
+        $user = api_get_user_info($user_id);
 
         $catcourse = Category :: load($select_cat);
         $scoredisplay = ScoreDisplay :: instance();
@@ -653,7 +691,7 @@ class DisplayGradebook
         //Web path
         $image_path = UserManager::get_user_picture_path_by_id($userid, 'web', false, true);
         $image_file = $image_path['dir'] . $image_path['file'];
-        $img_attributes = 'src="' . $image_file . '?rand=' . time() . '" ' . 'alt="' . api_get_person_name($user['firstname'], $user['lastname']) . '" ';
+        $img_attributes = 'src="' . $image_file . '?rand=' . time() . '" ' . 'alt="' . $user['complete_name'] . '" ';
         if ($image_size[0] > 200) {
             //limit display width to 200px
             $img_attributes .= 'width="200" ';
@@ -662,7 +700,8 @@ class DisplayGradebook
         $info .= '<div class="thumbnail"><img ' . $img_attributes . '/></div>';
         $info .= '</div>';
         $info .= '<div class="span6">';
-        $info .= get_lang('Name') . ' :  <a target="_blank" href="' . api_get_path(WEB_CODE_PATH) . 'social/profile.php?u=' . $userid . '"> ' . api_get_person_name($user['firstname'], $user['lastname']) . '</a><br />';
+        $info .= get_lang('Name') . ' :  <a target="_blank" href="' . api_get_path(WEB_CODE_PATH) . 'social/profile.php?u=' . $userid . '"> ' .
+            $user['complete_name'] . '</a><br />';
 
         if (api_get_setting('show_email_addresses') == 'true') {
             $info .= get_lang('Email') . ' : <a href="mailto:' . $user['email'] . '">' . $user['email'] . '</a><br />';
@@ -672,9 +711,6 @@ class DisplayGradebook
         $info .= '</div>';
         $info .= '</div>';
 
-        //$scoreinfo = get_lang('StatsStudent') . ' :<b> '.api_get_person_name($user['lastname'], $user['firstname']).'</b><br />';
-        //$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scorecourse_display . '</b>';
-        //$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
         echo $info;
     }
 

+ 8 - 14
main/gradebook/lib/fe/evalform.class.php

@@ -1,23 +1,11 @@
 <?php
-
 /* For licensing terms, see /license.txt */
-/**
- * Script
- * @package chamilo.gradebook
- */
-/**
- * Init
- */
+
 require_once dirname(__FILE__) . '/../../../inc/global.inc.php';
 require_once dirname(__FILE__) . '/../be.inc.php';
 require_once dirname(__FILE__) . '/../gradebook_functions.inc.php';
 require_once api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php';
 
-/**
- * Extends formvalidator with add&edit forms for evaluations
- * @author Stijn Konings
- * @package chamilo.gradebook
- */
 $htmlHeadXtra[] = '<script type="text/javascript">
 function setFocus(){
     $("#evaluation_title").focus();
@@ -27,9 +15,15 @@ $(document).ready(function () {
 });
 </script>';
 
+/**
+ * Class EvalForm
+ *
+ * Extends FormValidator with add&edit forms for evaluations
+ * @author Stijn Konings
+ * @package chamilo.gradebook
+ */
 class EvalForm extends FormValidator
 {
-
     const TYPE_ADD = 1;
     const TYPE_EDIT = 2;
     const TYPE_MOVE = 3;

+ 117 - 117
main/gradebook/lib/fe/exportgradebook.php

@@ -94,15 +94,15 @@ a:active {text-decoration: none; font-weight : bold;  color : black;}
  * @return void
  */
 function export_pdf_attendance($headers_table, $data_table, $headers_pdf, $footers_pdf, $title_pdf) {
-    require_once api_get_path(LIBRARY_PATH).'mpdf/mpdf.php';
+	require_once api_get_path(LIBRARY_PATH).'mpdf/mpdf.php';
 
-    $mpdf = new mPDF('UTF-8', 'A4-L', '', '', 15, 10, 35, 20, 4, 2, 'L');
-    $mpdf->useOnlyCoreFonts = true;
-    $mpdf->mirrorMargins = 0;      // Use different Odd/Even headers and footers and mirror margins
+	$mpdf = new mPDF('UTF-8', 'A4-L', '', '', 15, 10, 35, 20, 4, 2, 'L');
+	$mpdf->useOnlyCoreFonts = true;
+	$mpdf->mirrorMargins = 0;      // Use different Odd/Even headers and footers and mirror margins
 
-    if (is_array($headers_pdf)) {
-        // preparing headers pdf
-        $header = '<table width="100%"  cellspacing="1" cellpadding="1" border="0" class="strong">
+	if (is_array($headers_pdf)) {
+		// preparing headers pdf
+		$header = '<table width="100%"  cellspacing="1" cellpadding="1" border="0" class="strong">
                                 <tr>
                                    <td ROWSPAN="3" style="text-align: left;" class="title"><img src="'.api_get_path(WEB_CSS_PATH).api_get_setting('stylesheets').'/images/header-logo.png"></td><td  colspan="3"><h1>'.$title_pdf.'</h1></td>
                                 <tr>
@@ -122,92 +122,92 @@ function export_pdf_attendance($headers_table, $data_table, $headers_pdf, $foote
                                     <td><strong>'.$headers_pdf[5][0].'</strong> </td><td> <strong>'.$headers_pdf[5][1].'</strong></td>
                                 </tr>
                             </table>';
-    }
+	}
 
-    // preparing footer pdf
-    $footer = '<table width="100%" cellspacing="2" cellpadding="10" border="0">';
-    if (is_array($footers_pdf)) {
-        $footer .= '<tr>';
-        foreach ($footers_pdf as $foot_pdf) {
-            $footer .= '<td width="33%" style="text-align: center;">'.$foot_pdf.'</td>';
-        }
-        $footer .= '</tr>';
-    }
-    $footer .= '</table>';
+	// preparing footer pdf
+	$footer = '<table width="100%" cellspacing="2" cellpadding="10" border="0">';
+	if (is_array($footers_pdf)) {
+		$footer .= '<tr>';
+		foreach ($footers_pdf as $foot_pdf) {
+			$footer .= '<td width="33%" style="text-align: center;">'.$foot_pdf.'</td>';
+		}
+		$footer .= '</tr>';
+	}
+	$footer .= '</table>';
 
-    $footer .= '<div align="right" style="font-weight: bold;">{PAGENO}/{nb}</div>';
+	$footer .= '<div align="right" style="font-weight: bold;">{PAGENO}/{nb}</div>';
 
-    // preparing content pdf
-    $css_file = api_get_path(TO_SYS, WEB_CSS_PATH).api_get_setting('stylesheets').'/print.css';
-    if (file_exists($css_file)) {
-        $css = @file_get_contents($css_file);
-    } else {
-        $css = '';
-    }
+	// preparing content pdf
+	$css_file = api_get_path(TO_SYS, WEB_CSS_PATH).api_get_setting('stylesheets').'/print.css';
+	if (file_exists($css_file)) {
+		$css = @file_get_contents($css_file);
+	} else {
+		$css = '';
+	}
 
-    if(count($data_table) > 30)
-            $items_per_page = (count($data_table)/2);
-        else
-            $items_per_page = count($data_table);
+	if(count($data_table) > 30)
+		$items_per_page = (count($data_table)/2);
+	else
+		$items_per_page = count($data_table);
 
-    $count_pages = ceil(count($data_table) / $items_per_page);
-    for ($x = 0; $x<$count_pages; $x++) {
-        $content_table .= '<table width="100%" border="1" style="border-collapse:collapse">';
-        // header table
-        $content_table .= '<tr>';
-        $i = 0;
-        if (is_array($headers_table)) {
+	$count_pages = ceil(count($data_table) / $items_per_page);
+	for ($x = 0; $x<$count_pages; $x++) {
+		$content_table .= '<table width="100%" border="1" style="border-collapse:collapse">';
+		// header table
+		$content_table .= '<tr>';
+		$i = 0;
+		if (is_array($headers_table)) {
 
-            foreach ($headers_table as $head_table) {
-                if (!empty($head_table[0])) {
-                    $width = (!empty($head_table[1])?$head_table[1].'%':'');
-                    $content_table .= '<th width="'.$width.'">'.$head_table[0].'</th>';
-                    $i++;
-                }
-            }
-        }
-        $content_table .= '</tr>';
-        // body table
-        if (is_array($data_table) && count($data_table) > 0) {
-            $offset = $x*$items_per_page;
-            $data_table = array_slice ($data_table, $offset, count($data_table));
-            $i = 1;
-            $item = $offset+1;
-            foreach ($data_table as $data) {
-                $content_table .= '<tr>';
-                $content_table .= '<td>'.($item<10?'0'.$item:$item).'</td>';
-                foreach ($data as  $key => $content) {
-                    if (isset($content)) {
-                        $key == 1 ? $align='align="left"':$align='align="center"';
-                        $content_table .= '<td '.$align.' style="padding:4px;" >'.$content.'</td>';
-                    }
-                }
-                $content_table .= '</tr>';
-                $i++;
-                $item++;
-                if ($i > $items_per_page) { break; }
-            }
-        } else {
-            $content_table .= '<tr colspan="'.$i.'"><td>'.get_lang('Empty').'</td></tr>';
-        }
-        $content_table .= '</table>';
-        if ($x < ($count_pages - 1)) { $content_table .= '<pagebreak />'; }
-    }
+			foreach ($headers_table as $head_table) {
+				if (!empty($head_table[0])) {
+					$width = (!empty($head_table[1])?$head_table[1].'%':'');
+					$content_table .= '<th width="'.$width.'">'.$head_table[0].'</th>';
+					$i++;
+				}
+			}
+		}
+		$content_table .= '</tr>';
+		// body table
+		if (is_array($data_table) && count($data_table) > 0) {
+			$offset = $x*$items_per_page;
+			$data_table = array_slice ($data_table, $offset, count($data_table));
+			$i = 1;
+			$item = $offset+1;
+			foreach ($data_table as $data) {
+				$content_table .= '<tr>';
+				$content_table .= '<td>'.($item<10?'0'.$item:$item).'</td>';
+				foreach ($data as  $key => $content) {
+					if (isset($content)) {
+						$key == 1 ? $align='align="left"':$align='align="center"';
+						$content_table .= '<td '.$align.' style="padding:4px;" >'.$content.'</td>';
+					}
+				}
+				$content_table .= '</tr>';
+				$i++;
+				$item++;
+				if ($i > $items_per_page) { break; }
+			}
+		} else {
+			$content_table .= '<tr colspan="'.$i.'"><td>'.get_lang('Empty').'</td></tr>';
+		}
+		$content_table .= '</table>';
+		if ($x < ($count_pages - 1)) { $content_table .= '<pagebreak />'; }
+	}
 
-    $html = $content_table;
+	$html = $content_table;
 
 
-    // set attributes for pdf
-    $mpdf->SetHTMLHeader($header);
-    $mpdf->SetHTMLFooter($footer);
-    if (!empty($css)) {
-        $mpdf->WriteHTML($css, 1);
-        $mpdf->WriteHTML($html, 2);
-    } else {
-        $mpdf->WriteHTML($html);
-    }
-    $mpdf->Output(replace_dangerous_char($title_pdf.'.pdf'), 'D');
-    exit;
+	// set attributes for pdf
+	$mpdf->SetHTMLHeader($header);
+	$mpdf->SetHTMLFooter($footer);
+	if (!empty($css)) {
+		$mpdf->WriteHTML($css, 1);
+		$mpdf->WriteHTML($html, 2);
+	} else {
+		$mpdf->WriteHTML($html);
+	}
+	$mpdf->Output(replace_dangerous_char($title_pdf.'.pdf'), 'D');
+	exit;
 }
 
 
@@ -220,45 +220,45 @@ function export_pdf_attendance($headers_table, $data_table, $headers_pdf, $foote
  * @return void
  */
 function export_pdf_with_html($headers_table, $data_table, $headers_pdf, $footers_pdf, $title_pdf) {
-	
+
 	require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
 	$headers_in_pdf = '<img src="'.api_get_path(WEB_CSS_PATH).api_get_setting('stylesheets').'/images/header-logo.png">';
-    
+
 	if (is_array($headers_pdf)) {
 		// preparing headers pdf
-		$header = '<br/><br/><table width="100%" cellspacing="1" cellpadding="5" border="0" class="strong">							
-					        <tr><td width="100%" style="text-align: center;" class="title" colspan="4"><h1>'.$title_pdf.'</h1></td></tr>';		
-		foreach($headers_pdf as $header_pdf) {			
+		$header = '<br/><br/><table width="100%" cellspacing="1" cellpadding="5" border="0" class="strong">
+					        <tr><td width="100%" style="text-align: center;" class="title" colspan="4"><h1>'.$title_pdf.'</h1></td></tr>';
+		foreach($headers_pdf as $header_pdf) {
 			if (!empty($header_pdf[0]) && !empty($header_pdf[1])) {
 				$header.= '<tr><td><strong>'.$header_pdf[0].'</strong> </td><td>'.$header_pdf[1].'</td></tr>';
 			}
-		}		
+		}
 		$header.='</table><br />';
 	}
-		
+
 	// preparing footer pdf
 	$footer = '<table width="100%" cellspacing="2" cellpadding="10" border="0">';
 	if (is_array($footers_pdf)) {
-		$footer .= '<tr>';	
+		$footer .= '<tr>';
 		foreach ($footers_pdf as $foot_pdf) {
 			$footer .= '<td width="33%" style="text-align: center;">'.$foot_pdf.'</td>';
 		}
-		$footer .= '</tr>';	
+		$footer .= '</tr>';
 	}
-	$footer .= '</table>';	
+	$footer .= '</table>';
 	$footer .= '<div align="right" style="font-weight: bold;">{PAGENO}/{nb}</div>';
-	
-	// preparing content pdf		
+
+	// preparing content pdf
 	$css_file = api_get_path(TO_SYS, WEB_CSS_PATH).api_get_setting('stylesheets').'/print.css';
 	if (file_exists($css_file)) {
 		$css = @file_get_contents($css_file);
 	} else {
 		$css = '';
-	}	
+	}
 	$items_per_page = 30;
-	$count_pages = ceil(count($data_table) / $items_per_page);  
+	$count_pages = ceil(count($data_table) / $items_per_page);
 	for ($x = 0; $x<$count_pages; $x++) {
-		$content_table .= '<table width="100%" border="1" style="border-collapse:collapse">';	
+		$content_table .= '<table width="100%" border="1" style="border-collapse:collapse">';
 		// header table
 		$content_table .= '<tr>';
 		$i = 0;
@@ -267,41 +267,41 @@ function export_pdf_with_html($headers_table, $data_table, $headers_pdf, $footer
 				if (!empty($head_table[0])) {
 					$width = (!empty($head_table[1])?$head_table[1].'%':'');
 					$content_table .= '<th width="'.$width.'">'.$head_table[0].'</th>';
-					$i++;	
-				}			
-			}		
-		}	
-		$content_table .= '</tr>';			
+					$i++;
+				}
+			}
+		}
+		$content_table .= '</tr>';
 		// body table
-		
+
 		if (is_array($data_table) && count($data_table) > 0) {
-			$offset = $x*$items_per_page;				
+			$offset = $x*$items_per_page;
 			$data_table = array_slice ($data_table, $offset, count($data_table));
 			$i = 1;
 			$item = $offset+1;
-			foreach ($data_table as $data) {			
+			foreach ($data_table as $data) {
 				$content_table .= '<tr>';
 				$content_table .= '<td>'.($item<10?'0'.$item:$item).'</td>';
-				foreach ($data as  $key => $content) {							
+				foreach ($data as  $key => $content) {
 					if (isset($content)) {
 						$key == 1 ? $align='align="left"':$align='align="center"';
-						$content_table .= '<td '.$align.' style="padding:4px;" >'.$content.'</td>';	
-					}					
+						$content_table .= '<td '.$align.' style="padding:4px;" >'.$content.'</td>';
+					}
 				}
 				$content_table .= '</tr>';
 				$i++;
 				$item++;
 				if ($i > $items_per_page) { break; }
-			}			
+			}
 		} else {
 			$content_table .= '<tr colspan="'.$i.'"><td>'.get_lang('Empty').'</td></tr>';
-		}	
-		$content_table .= '</table>';				
-		if ($x < ($count_pages - 1)) { $content_table .= '<pagebreak />'; }		
-	}	
+		}
+		$content_table .= '</table>';
+		if ($x < ($count_pages - 1)) { $content_table .= '<pagebreak />'; }
+	}
 	$pdf = new PDF();
-    $pdf->set_custom_footer($footer);
-    $pdf->set_custom_header($headers_in_pdf);
+	$pdf->set_custom_footer($footer);
+	$pdf->set_custom_header($headers_in_pdf);
 	$pdf->content_to_pdf($header.$content_table, $css, $title_pdf );
 	exit;
 

+ 16 - 16
main/gradebook/lib/fe/flatviewtable.class.php

@@ -69,7 +69,7 @@ class FlatViewTable extends SortableTable
      */
     public function setLimitEnabled($value)
     {
-       $this->limit_enabled = (bool) $value;
+        $this->limit_enabled = (bool) $value;
     }
 
     /**
@@ -81,8 +81,8 @@ class FlatViewTable extends SortableTable
     }
 
     /**
-    * Display the graph of the total results of all students
-    * */
+     * Display the graph of the total results of all students
+     * */
     public function display_graph()
     {
         include_once api_get_path(LIBRARY_PATH) . 'pchart/pData.class.php';
@@ -505,33 +505,33 @@ class FlatViewTable extends SortableTable
         $header = null;
         if ($this->limit_enabled && $totalitems > LIMIT) {
             $header .= '<table style="width: 100%; text-align: right; margin-left: auto; margin-right: auto;" border="0" cellpadding="2">'
-                    . '<tbody>'
-                    . '<tr>';
+                . '<tbody>'
+                . '<tr>';
 
             // previous X
             $header .= '<td style="width:100%;">';
             if ($this->offset >= LIMIT) {
                 $header .= '<a href="' . api_get_self()
-                        . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
-                        . '&offset=' . (($this->offset) - LIMIT)
-                        . (isset($_GET['search']) ? '&search=' . Security::remove_XSS($_GET['search']) : '') . '">'
-                        . Display::return_icon('action_prev.png', get_lang('PreviousPage'), array(), 32)
-                        . '</a>';
+                    . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
+                    . '&offset=' . (($this->offset) - LIMIT)
+                    . (isset($_GET['search']) ? '&search=' . Security::remove_XSS($_GET['search']) : '') . '">'
+                    . Display::return_icon('action_prev.png', get_lang('PreviousPage'), array(), 32)
+                    . '</a>';
             } else {
                 $header .= Display::return_icon('action_prev_na.png', get_lang('PreviousPage'), array(), 32);
             }
             $header .= ' ';
             // next X
             $calcnext = (($this->offset + (2 * LIMIT)) > $totalitems) ?
-                    ($totalitems - (LIMIT + $this->offset)) : LIMIT;
+                ($totalitems - (LIMIT + $this->offset)) : LIMIT;
 
             if ($calcnext > 0) {
                 $header .= '<a href="' . api_get_self()
-                        . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
-                        . '&offset=' . ($this->offset + LIMIT)
-                        . (isset($_GET['search']) ? '&search=' . Security::remove_XSS($_GET['search']) : '') . '">'
-                        . Display::return_icon('action_next.png', get_lang('NextPage'), array(), 32)
-                        . '</a>';
+                    . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
+                    . '&offset=' . ($this->offset + LIMIT)
+                    . (isset($_GET['search']) ? '&search=' . Security::remove_XSS($_GET['search']) : '') . '">'
+                    . Display::return_icon('action_next.png', get_lang('NextPage'), array(), 32)
+                    . '</a>';
             } else {
                 $header .= Display::return_icon('action_next_na.png', get_lang('NextPage'), array(), 32);
             }

+ 146 - 144
main/gradebook/lib/fe/gradebooktable.class.php

@@ -20,10 +20,15 @@ class GradebookTable extends SortableTable
 
     /**
      * Constructor
+     * @param Category $currentcat
+     * @param array $cats
+     * @param array $evals
+     * @param array $links
+     * @param null $addparams
      */
     public function GradebookTable($currentcat, $cats = array(), $evals = array(), $links = array(), $addparams = null)
     {
-        parent::__construct ('gradebooklist', null, null, (api_is_allowed_to_edit()?1:0));
+        parent::__construct('gradebooklist', null, null, (api_is_allowed_to_edit()?1:0));
         $this->evals_links = array_merge($evals, $links);
         $this->currentcat = $currentcat;
         $this->cats = $cats;
@@ -40,7 +45,6 @@ class GradebookTable extends SortableTable
 
         $this->set_header($column++, get_lang('Type'), '', 'width="35px"');
         $this->set_header($column++, get_lang('Name'), false);
-
         $this->set_header($column++, get_lang('Description'), false);
 
         if (api_is_allowed_to_edit(null, true)) {
@@ -60,18 +64,18 @@ class GradebookTable extends SortableTable
         }
 
         // Deactivates the odd/even alt rows in order that the +/- buttons work see #4047
-
         $this->odd_even_rows_enabled = false;
 
         // Admins get an edit column.
         if (api_is_allowed_to_edit(null, true)) {
             $this->set_header($column++, get_lang('Modify'), false, 'width="195px"');
             // Actions on multiple selected documents.
-            $this->set_form_actions(array (
-                'setvisible' => get_lang('SetVisible'),
-                'setinvisible' => get_lang('SetInvisible'),
-                'deleted' => get_lang('DeleteSelected')
-                ));
+            $this->set_form_actions(array(
+                    'setvisible' => get_lang('SetVisible'),
+                    'setinvisible' => get_lang('SetInvisible'),
+                    'deleted' => get_lang('DeleteSelected')
+                )
+            );
         } else {
             if (empty($_GET['selectcat']) && !api_is_allowed_to_edit()) {
                 $this->set_header($column++, get_lang('Certificates'), false);
@@ -87,14 +91,14 @@ class GradebookTable extends SortableTable
         return $this->datagen;
     }
 
-	/**
-	 * Function used by SortableTable to get total number of items in the table
+    /**
+     * Function used by SortableTable to get total number of items in the table
      * @return int
-	 */
+     */
     public function get_total_number_of_items()
     {
-		return $this->datagen->get_total_items_count();
-	}
+        return $this->datagen->get_total_items_count();
+    }
 
     /**
      * Function used by SortableTable to generate the data to display
@@ -142,19 +146,21 @@ class GradebookTable extends SortableTable
         }
 
         // Status of user in course.
-        $user_id        = api_get_user_id();
-        $course_code    = api_get_course_id();
-        $session_id     = api_get_session_id();
-        $status_user    = api_get_status_of_user_in_course($user_id, $course_code);
-        $data_array     = $this->datagen->get_data($sorting, $from, $this->per_page);
+        $user_id = api_get_user_id();
+        $course_code = api_get_course_id();
+        $session_id = api_get_session_id();
+        $status_user = api_get_status_of_user_in_course($user_id, $course_code);
+        $data_array = $this->datagen->get_data(
+            $sorting,
+            $from,
+            $this->per_page
+        );
 
         // generate the data to display
         $sortable_data = array();
         $weight_total_links = 0;
-
         $main_categories = array();
         $main_cat =  Category::load(null, null, $course_code, null, null, $session_id, false);
-
         $total_categories_weight = 0;
         $scoredisplay = ScoreDisplay :: instance();
 
@@ -204,6 +210,7 @@ class GradebookTable extends SortableTable
                 true
             );
 
+            // Weight
             if (api_is_allowed_to_edit(null, true)) {
                 $row[] = $invisibility_span_open .Display::tag('h4', $average).$invisibility_span_close;
             } else {
@@ -258,14 +265,11 @@ class GradebookTable extends SortableTable
             $sortable_data[] = $row;
 
             // Loading children
-
             if (get_class($item) == 'Category') {
-
-                $stud_id        = api_get_user_id();
-                $course_code    = api_get_course_id();
-                $session_id     = api_get_session_id();
-                $parent_id      = $item->get_id();
-
+                $stud_id = api_get_user_id();
+                $course_code = api_get_course_id();
+                $session_id = api_get_session_id();
+                $parent_id = $item->get_id();
                 $cats = Category::load($parent_id, null, null, null, null, null);
 
                 if (isset($cats[0])) {
@@ -275,13 +279,11 @@ class GradebookTable extends SortableTable
 
                     $sub_cat_info = new GradebookDataGenerator($allcat, $alleval, $alllink);
                     $data_array  =  $sub_cat_info->get_data($sorting, $from, $this->per_page);
-
                     $total_weight = 0;
 
                     // Links.
-
                     foreach ($data_array as $data) {
-                        $row  = array();
+                        $row = array();
                         $item = $data[0];
 
                         //if the item is invisible, wrap it in a span with class invisible
@@ -341,7 +343,6 @@ class GradebookTable extends SortableTable
                             }
                         }
                         $row['child_of'] = $parent_id;
-
                         $sortable_data[] = $row;
                     }
 
@@ -406,7 +407,8 @@ class GradebookTable extends SortableTable
                     $weight_total_links > $weight_category
                 ) {
                     $warning_message = sprintf(get_lang('TotalWeightMustBeX'), $weight_category);
-                    $modify_icons  = '<a class="right_link" href="gradebook_edit_cat.php?editcat='.$id_cat.'&cidReq='.$course_code.'">'.Display::return_icon('edit.png', $warning_message, array(), ICON_SIZE_SMALL).'</a>';
+                    $modify_icons  = '<a class="right_link" href="gradebook_edit_cat.php?editcat='.$id_cat.'&cidReq='.$course_code.'">'.
+                            Display::return_icon('edit.png', $warning_message, array(), ICON_SIZE_SMALL).'</a>';
                     $warning_message .= $modify_icons;
                     Display::display_warning_message($warning_message, false);
                 }
@@ -493,7 +495,7 @@ class GradebookTable extends SortableTable
      */
     private function build_course_code ($item)
     {
-    	return $item->get_course_code();
+        return $item->get_course_code();
     }
 
     /**
@@ -502,18 +504,18 @@ class GradebookTable extends SortableTable
      */
     private function build_id_column ($item)
     {
-		switch ($item->get_item_type()) {
-			// category
-			case 'C' :
-				return 'CATE' . $item->get_id();
-			// evaluation
-			case 'E' :
-				return 'EVAL' . $item->get_id();
-			// link
-			case 'L' :
-				return 'LINK' . $item->get_id();
-		}
-	}
+        switch ($item->get_item_type()) {
+            // category
+            case 'C' :
+                return 'CATE' . $item->get_id();
+            // evaluation
+            case 'E' :
+                return 'EVAL' . $item->get_id();
+            // link
+            case 'L' :
+                return 'LINK' . $item->get_id();
+        }
+    }
 
     /**
      * @param $item
@@ -522,95 +524,95 @@ class GradebookTable extends SortableTable
      */
     private function build_type_column ($item, $attributes = array())
     {
-		return build_type_icon_tag($item->get_icon_name(), $attributes);
-	}
-
-	/**
-	 * Generate name column
-	 * @param unknown_type $item
-	 * @return string
-	 */
-	private function build_name_link ($item)
+        return build_type_icon_tag($item->get_icon_name(), $attributes);
+    }
+
+    /**
+     * Generate name column
+     * @param unknown_type $item
+     * @return string
+     */
+    private function build_name_link($item)
     {
         $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : null;
-		switch ($item->get_item_type()) {
-			// category
-			case 'C' :
-				$prms_uri='?selectcat=' . $item->get_id() . '&amp;view='.$view;
-
-				if (isset($_GET['isStudentView'])) {
-					if ( isset($is_student) || ( isset($_SESSION['studentview']) && $_SESSION['studentview']=='studentview') ) {
-						$prms_uri=$prms_uri.'&amp;isStudentView='.Security::remove_XSS($_GET['isStudentView']);
-					}
-				}
-
-				$cat = new Category();
-				$show_message=$cat->show_message_resource_delete($item->get_course_code());
-				return '&nbsp;<a href="'.Security::remove_XSS($_SESSION['gradebook_dest']).$prms_uri.'">'
-				 		. $item->get_name()
-				 		. '</a>'
-				 		. ($item->is_course() ? ' &nbsp;[' . $item->get_course_code() . ']'.$show_message : '');
-			// evaluation
-			case 'E' :
-				$cat = new Category();
-				$course_id = Database::get_course_by_category($_GET['selectcat']);
-
-				$show_message = $cat->show_message_resource_delete($course_id);
-
-				// course/platform admin can go to the view_results page
-
-				if (api_is_allowed_to_edit() && $show_message===false) {
-					if ($item->get_type() == 'presence') {
-						return '&nbsp;'
-							. '<a href="gradebook_view_result.php?cidReq='.$course_id.'&amp;selecteval=' . $item->get_id() . '">'
-							. $item->get_name()
-							. '</a>';
-					} else {
-						return '&nbsp;'
-							. '<a href="gradebook_view_result.php?cidReq='.$course_id.'&amp;selecteval=' . $item->get_id() . '">'
-							. $item->get_name()
-							. '</a>&nbsp;'.Display::label(get_lang('Evaluation'));
-					}
-				} elseif (ScoreDisplay :: instance()->is_custom() && $show_message===false) {
-					// students can go to the statistics page (if custom display enabled)
-					return '&nbsp;'
-						. '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">'
-						. $item->get_name()
-						. '</a>';
-
-				} elseif ($show_message===false && !api_is_allowed_to_edit() && !(ScoreDisplay :: instance()->is_custom())) {
-					return '&nbsp;'
-						. '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">'
-						. $item->get_name()
-						. '</a>';
-
-				} else {
-					return '['.get_lang('Evaluation').']&nbsp;&nbsp;'.$item->get_name().$show_message;
-				}
-			// link
-			case 'L' :
-				$cat 			= new Category();
-				$course_id	 	= Database::get_course_by_category($_GET['selectcat']);
-				$show_message	= $cat->show_message_resource_delete($course_id);
-
-				$url = $item->get_link();
-
-				if (isset($url) && $show_message===false) {
-					$text = '&nbsp;<a href="' . $item->get_link() . '">'
-							. $item->get_name()
-							. '</a>';
-				} else {
-					$text = $item->get_name();
-				}
-
-				$text .= "&nbsp;".Display::label($item->get_type_name(), 'info').$show_message;
-				$cc = $this->currentcat->get_course_code();
-				if (empty($cc)) {
-					$text .= '&nbsp;[<a href="'.api_get_path(REL_COURSE_PATH).$item->get_course_code().'/">'.$item->get_course_code().'</a>]';
-				}
-				return $text;
-		}
-	}
+        switch ($item->get_item_type()) {
+            // category
+            case 'C' :
+                $prms_uri='?selectcat=' . $item->get_id() . '&amp;view='.$view;
+
+                if (isset($_GET['isStudentView'])) {
+                    if ( isset($is_student) || ( isset($_SESSION['studentview']) && $_SESSION['studentview']=='studentview') ) {
+                        $prms_uri=$prms_uri.'&amp;isStudentView='.Security::remove_XSS($_GET['isStudentView']);
+                    }
+                }
+
+                $cat = new Category();
+                $show_message=$cat->show_message_resource_delete($item->get_course_code());
+                return '&nbsp;<a href="'.Security::remove_XSS($_SESSION['gradebook_dest']).$prms_uri.'">'
+                . $item->get_name()
+                . '</a>'
+                . ($item->is_course() ? ' &nbsp;[' . $item->get_course_code() . ']'.$show_message : '');
+            // evaluation
+            case 'E' :
+                $cat = new Category();
+                $course_id = Database::get_course_by_category($_GET['selectcat']);
+
+                $show_message = $cat->show_message_resource_delete($course_id);
+
+                // course/platform admin can go to the view_results page
+
+                if (api_is_allowed_to_edit() && $show_message===false) {
+                    if ($item->get_type() == 'presence') {
+                        return '&nbsp;'
+                        . '<a href="gradebook_view_result.php?cidReq='.$course_id.'&amp;selecteval=' . $item->get_id() . '">'
+                        . $item->get_name()
+                        . '</a>';
+                    } else {
+                        return '&nbsp;'
+                        . '<a href="gradebook_view_result.php?cidReq='.$course_id.'&amp;selecteval=' . $item->get_id() . '">'
+                        . $item->get_name()
+                        . '</a>&nbsp;'.Display::label(get_lang('Evaluation'));
+                    }
+                } elseif (ScoreDisplay :: instance()->is_custom() && $show_message===false) {
+                    // students can go to the statistics page (if custom display enabled)
+                    return '&nbsp;'
+                    . '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">'
+                    . $item->get_name()
+                    . '</a>';
+
+                } elseif ($show_message===false && !api_is_allowed_to_edit() && !(ScoreDisplay :: instance()->is_custom())) {
+                    return '&nbsp;'
+                    . '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">'
+                    . $item->get_name()
+                    . '</a>';
+
+                } else {
+                    return '['.get_lang('Evaluation').']&nbsp;&nbsp;'.$item->get_name().$show_message;
+                }
+            // link
+            case 'L' :
+                $cat 			= new Category();
+                $course_id	 	= Database::get_course_by_category($_GET['selectcat']);
+                $show_message	= $cat->show_message_resource_delete($course_id);
+
+                $url = $item->get_link();
+
+                if (isset($url) && $show_message===false) {
+                    $text = '&nbsp;<a href="' . $item->get_link() . '">'
+                        . $item->get_name()
+                        . '</a>';
+                } else {
+                    $text = $item->get_name();
+                }
+
+                $text .= "&nbsp;".Display::label($item->get_type_name(), 'info').$show_message;
+                $cc = $this->currentcat->get_course_code();
+                if (empty($cc)) {
+                    $text .= '&nbsp;[<a href="'.api_get_path(REL_COURSE_PATH).$item->get_course_code().'/">'.$item->get_course_code().'</a>]';
+                }
+                return $text;
+        }
+    }
 
     /**
      * @param $item
@@ -618,16 +620,16 @@ class GradebookTable extends SortableTable
      */
     private function build_edit_column($item)
     {
-		switch ($item->get_item_type()) {
-			// category
-			case 'C' :
-				return build_edit_icons_cat($item, $this->currentcat);
-			// evaluation
-			case 'E' :
-				return build_edit_icons_eval($item, $this->currentcat->get_id());
-			// link
-			case 'L' :
-				return build_edit_icons_link($item, $this->currentcat->get_id());
-		}
-	}
+        switch ($item->get_item_type()) {
+            // category
+            case 'C' :
+                return build_edit_icons_cat($item, $this->currentcat);
+            // evaluation
+            case 'E' :
+                return build_edit_icons_eval($item, $this->currentcat->get_id());
+            // link
+            case 'L' :
+                return build_edit_icons_link($item, $this->currentcat->get_id());
+        }
+    }
 }

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