Browse Source

Merge branch '1.11.x' into 1.11.x

Julio Montoya 7 years ago
parent
commit
ba0d988fcc
84 changed files with 1441 additions and 1294 deletions
  1. 1 8
      custompages/first_login-dist.php
  2. 1 7
      custompages/index-unlogged-dist.php
  3. 1 7
      custompages/loggedout-dist.php
  4. 1 7
      custompages/lostpassword-dist.php
  5. 1 14
      custompages/registration-dist.php
  6. 1 9
      custompages/registration-feedback-dist.php
  7. 0 218
      custompages/style-ie6.css
  8. 0 198
      custompages/style.css
  9. 68 68
      main/admin/dashboard_add_courses_to_user.php
  10. 2 2
      main/admin/dashboard_add_sessions_to_user.php
  11. 63 22
      main/admin/index.php
  12. 6 5
      main/admin/skill_badge.php
  13. 5 10
      main/admin/skill_badge_create.php
  14. 2 3
      main/admin/skill_badge_list.php
  15. 1 5
      main/admin/skill_create.php
  16. 1 4
      main/admin/skill_edit.php
  17. 6 9
      main/admin/skill_list.php
  18. 1 4
      main/admin/skills.php
  19. 8 16
      main/admin/skills_gradebook.php
  20. 4 9
      main/admin/skills_profile.php
  21. 6 5
      main/admin/skills_wheel.php
  22. 1 1
      main/admin/user_export.php
  23. 31 10
      main/admin/user_information.php
  24. 47 25
      main/attendance/attendance_controller.php
  25. 63 31
      main/attendance/index.php
  26. 61 13
      main/badge/assign.php
  27. 9 9
      main/badge/issued.php
  28. 16 13
      main/badge/issued_all.php
  29. 2 1
      main/badge/issuer.php
  30. 2 6
      main/course_progress/thematic_advance.php
  31. 5 7
      main/course_progress/thematic_controller.php
  32. 1 1
      main/coursecopy/recycle_course.php
  33. 3 1
      main/cron/scheduled_announcement.php
  34. 14 11
      main/dropbox/dropbox_class.inc.php
  35. 1 1
      main/exercise/Draggable.php
  36. 4 4
      main/exercise/question_pool.php
  37. 2 3
      main/forum/viewforumcategory.php
  38. 3 0
      main/glossary/index.php
  39. 7 10
      main/gradebook/get_badges.php
  40. 171 55
      main/gradebook/gradebook_display_certificate.php
  41. 1 2
      main/gradebook/lib/be/category.class.php
  42. 1 2
      main/gradebook/lib/fe/catform.class.php
  43. 2 4
      main/inc/ajax/skill.ajax.php
  44. 2 2
      main/inc/introductionSection.inc.php
  45. 2 2
      main/inc/lib/CourseChatUtils.php
  46. 3 1
      main/inc/lib/ScheduledAnnouncement.php
  47. 1 0
      main/inc/lib/SmsPlugin.php
  48. 1 1
      main/inc/lib/attendance.lib.php
  49. 1 1
      main/inc/lib/auth.lib.php
  50. 6 9
      main/inc/lib/course.lib.php
  51. 8 2
      main/inc/lib/course_home.lib.php
  52. 47 21
      main/inc/lib/document.lib.php
  53. 36 0
      main/inc/lib/glossary.lib.php
  54. 13 3
      main/inc/lib/message.lib.php
  55. 1 1
      main/inc/lib/myspace.lib.php
  56. 6 7
      main/inc/lib/notification.lib.php
  57. 74 26
      main/inc/lib/sessionmanager.lib.php
  58. 125 16
      main/inc/lib/skill.lib.php
  59. 2 2
      main/inc/lib/social.lib.php
  60. 5 6
      main/inc/lib/tracking.lib.php
  61. 88 28
      main/inc/lib/usermanager.lib.php
  62. 8 2
      main/inc/lib/userportal.lib.php
  63. 9 6
      main/install/configuration.dist.php
  64. 10 0
      main/lang/english/trad4all.inc.php
  65. 2 3
      main/mySpace/myStudents.php
  66. 1 1
      main/session/scheduled_announcement.php
  67. 4 2
      main/social/message_for_group_form.inc.php
  68. 31 15
      main/social/my_skills_report.php
  69. 15 14
      main/social/profile.php
  70. 4 6
      main/social/profile_friends_and_groups.inc.php
  71. 3 2
      main/social/skills_ranking.php
  72. 1 5
      main/social/skills_tree.php
  73. 11 11
      main/social/skills_wheel.php
  74. 2 2
      main/template/default/skill/drh_report.tpl
  75. 1 1
      main/template/default/skill/student_boss_report.tpl
  76. 1 1
      main/template/default/skill/student_report.tpl
  77. 69 30
      main/tracking/courseLog.php
  78. 2 1
      main/work/work.lib.php
  79. 1 3
      plugin/clockworksms/install.php
  80. 89 88
      plugin/clockworksms/lang/english.php
  81. 88 88
      plugin/clockworksms/lang/spanish.php
  82. 41 42
      plugin/clockworksms/lib/clockworksms.lib.php
  83. 1 0
      plugin/clockworksms/sms_templates/certificate_notification.tpl
  84. 0 3
      plugin/clockworksms/uninstall.php

+ 1 - 8
custompages/first_login-dist.php

@@ -67,14 +67,7 @@ $www = api_get_path('WEB_PATH');
 <head>
     <title>Custompage - login</title>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-    <!--[if !IE 6]><!-->
-    <link rel="stylesheet" type="text/css" href="/custompages/style.css" />
-    <!--<![endif]-->
-    <!--[if IE 6]>
-    <link rel="stylesheet" type="text/css" href="/custompages/style-ie6.css" />
-    <![endif]-->
-
-    <script type="text/javascript" src="<?php echo $www ?>web/assets/jquery/jquery.min.js"></script>
+    <script type="text/javascript" src="<?php echo $www ?>web/assets/jquery/dist/jquery.min.js"></script>
     <script type="text/javascript">
         $(document).ready(function() {
             if (top.location != location)

+ 1 - 7
custompages/index-unlogged-dist.php

@@ -44,13 +44,7 @@ $rootWeb = api_get_path('WEB_PATH');
 <head>
 	<title>Custompage - login</title>
 	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-	<!--[if !IE 6]><!-->
-	<link rel="stylesheet" type="text/css" href="<?php echo $rootWeb ?>custompages/style.css" />
-	<!--<![endif]-->
-	<!--[if IE 6]>
-	<link rel="stylesheet" type="text/css" href="/custompages/style-ie6.css" />
-	<![endif]-->
-    <script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/jquery.min.js"></script>
+    <script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/dist/jquery.min.js"></script>
 	<script type="text/javascript">
 		$(document).ready(function() {
 			if (top.location != location) {

+ 1 - 7
custompages/loggedout-dist.php

@@ -23,13 +23,7 @@ $www = api_get_path('WEB_PATH');
     <head>
         <title>Custompage - logged out</title>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-        <!--[if !IE 6]><!-->
-        <link rel="stylesheet" type="text/css" href="<?php echo $www ?>custompages/style.css" />
-        <!--<![endif]-->
-        <!--[if IE 6]>
-        <link rel="stylesheet" type="text/css" href="/custompages/style-ie6.css" />
-        <![endif]-->
-        <script type="text/javascript" src="<?php echo $www ?>web/assets/jquery/jquery.min.js"></script>
+        <script type="text/javascript" src="<?php echo $www ?>web/assets/jquery/dist/jquery.min.js"></script>
         <script type="text/javascript">
             $(document).ready(function() {
                 if (top.location != location)

+ 1 - 7
custompages/lostpassword-dist.php

@@ -14,13 +14,7 @@ $rootWeb = api_get_path('WEB_PATH');
 <head>
 	<title><?php echo custompages_get_lang('LostPassword'); ?></title>
 	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-	<!--[if !IE 6]><!-->
-	<link rel="stylesheet" type="text/css" href="../../custompages/style.css" />
-	<!--<![endif]-->
-	<!--[if IE 6]>
-	<link rel="stylesheet" type="text/css" href="../../custompages/style-ie6.css" />
-	<![endif]-->
-	<script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/jquery.min.js"></script>
+	<script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/dist/jquery.min.js"></script>
 
 	<script type="text/javascript">
 		$(document).ready(function() {

+ 1 - 14
custompages/registration-dist.php

@@ -84,20 +84,7 @@ EOT;
     <title><?php echo custompages_get_lang('Registration'); ?></title>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <link href="/custompages/css/vendor/bootstrap.min.css" rel="stylesheet">
-    <!--[if !IE 6]><!-->
-    <link rel="stylesheet" type="text/css" href="/custompages/style.css" />
-    <!--<![endif]-->
-    <!--[if IE 6]>
-    <link rel="stylesheet" type="text/css" href="/custompages/style-ie6.css" />
-    <![endif]-->
-    <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
-    <!--[if lt IE 9]>
-    <script src="js/vendor/html5shiv.js"></script>
-    <script src="js/vendor/respond.min.js"></script>
-    <![endif]-->
-    <script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/jquery.min.js"></script>
+    <script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/dist/jquery.min.js"></script>
 </head>
 <body>
 <img id="backgroundimage" src="/custompages/images/page-background.png"">

+ 1 - 9
custompages/registration-feedback-dist.php

@@ -18,15 +18,7 @@ $rootWeb = api_get_path('WEB_PATH');
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <link href="/custompages/css/vendor/bootstrap.min.css" rel="stylesheet">
-    <link href="/custompages/style.css" rel="stylesheet">
-
-    <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
-    <!--[if lt IE 9]>
-    <script src="js/vendor/html5shiv.js"></script>
-    <script src="js/vendor/respond.min.js"></script>
-    <![endif]-->
-    <script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/jquery.min.js"></script>
+    <script type="text/javascript" src="<?php echo $rootWeb ?>web/assets/jquery/dist/jquery.min.js"></script>
 </head>
 <body>
 <img src="/custompages/images/page-background.png" class="backgroundimage" />

+ 0 - 218
custompages/style-ie6.css

@@ -1,218 +0,0 @@
-/* Color easy change */
-body, .form, #links a, .form-info {
-  color: #DF002A;
-}
-.form-submit, input, select {
-  background-color: #DF002A;
-}
-.form-error {
-	color: red;
-	font-size: 9pt;
-}
-.form-submit {
-	margin: 0;
-	padding: 0;
-	width: 310px;
-	height: 27px;
-	background-color: #DF002A;
-	/*background-image: url(/custompages/images/login-form-submit-bg.jpg);*/
-	color: white;
-	cursor: pointer;
-	cursor: hand;
-}
-/* end easy change */
-/* Registration form */
-#registration-form-box {
-	width: 400px;
-	margin-left: auto;
-	margin-right: auto;
-	margin-top: 50px;
-	border: solid 1px #CCCCCC;
-	text-align: left;
-	background-color: white;
-}
-#registration-form-box .form-submit{
-  width: 400px;
-}
-div.row {
-  clear: both;
-  padding-top: 5px;
-}
-div.row div.form_header {
-  white-space: nowrap;
-  padding: 2px;
-  background-color: #f0f0f0;
-  border: 1px solid #bbb;
-}
-div.row div.label {
-  float: left;
-  width: 53%;
-  text-align: right;
-  padding-right:1%
-}
-div.row div.formw {
-  width: 46%;
-  float:left;
-}
-[dir=ltr] div.row div.label, [dir=rtl] div.row div.formw {
-  float: left;
-  text-align: right;
-}
-[dir=rtl] div.row div.label, [dir=ltr] div.row div.formw {
-  float: right;
-  text-align: left;
-}
-span.form_required {
-  color: #f00;
-}
-span.form_error {
-  color: #f00;
-  font-size: x-small;
-  margin: 2px;
-}
-html, body {
-	margin: 0;
-	padding: 0;
-}
-
-body {
-	font-family: "Arial Black",sans-serif;
-	font-size: 10pt;
-	width: 100%;
-	text-align: center;
-	color: #1F3660;
-	/*background-image: url(images/page-background.png);
-	background-repeat: no-repeat;
-	background-size: 100%;
-	*/
-}
-
-#backgroundimage {
-	background-attachment:fixed;
-	width: 100%;
-	height: 100%;
-	position: absolute;
-	left: 0;
-	top: 30px;
-	z-index:-1;
-}
-
-.backgroundimage {
-	width: 100%;
-	height: auto;
-}
-
-#wrapper {
-	position: absolute;
-	top: 0;
-	left: 0;
-	width: 100%;
-	z-index: 1;
-}
-
-#header {
-	width: 520px;
-	margin-left: auto;
-	margin-right: auto;
-	margin-top: 30px;
-}
-
-#footer {
-	position: relative;
-	/*margin-top: 50px;*/
-	text-align: center;
-}
-
-.form-box {
-	width: 310px;
-	margin-left: auto;
-	margin-right: auto;
-	margin-top: 50px;
-	border: solid 1px #CCCCCC;
-	text-align: left;
-	/*background-color: white;*/
-}
-
-.form {
-	margin-left: 15px;
-	margin-right: 15px;
-	margin-top: 30px;
-	/*color: #1F3660;*/
-	/*position: relative;*/
-	text-align: left;
-}
-
-
-label {
-	width: 100px;
-	float: left;
-	margin-right: 1em;
-	display: block;
-	text-align: right;
-	line-height: 2ex;
-}
-
-input {
-	text-align: left;
-	vertical-align: baseline;
-	margin-bottom: 2em;
-	width: 150px;
-	color: white;
-	/*background-color: #1F3660;*/
-	border: none;
-}
-.radiobutton {
-  width: 20px;
-  background-color: white;
-  margin: 0;  
-} 
-.radiogroup { 
-   margin-bottom: 2em;
- } 
-
-select {
-	width: 150px;
-	color: white;
-	/*background-color: #1F3660;*/
-	border: none;
-	margin-bottom: 2em;
-  width: 150px;
-}
-label {
-  clear: both;
-}
-input, select, .radiogroup {
-  float: right;
-  clear: both;
-}
-.radiogroup input, .radiogroup label {
-   float: none;
- }
-
-#links {
-	margin-left: 15px;
-	margin-right: 15px;
-	margin-top: 10px;
-	margin-bottom: 50px;
-	/*color: #1F3660;*/
-}
-
-
-#links a {
-	text-decoration: none;
-}
-
-#links a:hover {
-	text-decoration: underline;
-}
-
-span {
-	margin-right: 30px;
-	margin-top: 3px;
-	float: right;
-}
-
-.form-info {
-	/*color: #1F3660;*/
-	font-size: 9pt;
-}

+ 0 - 198
custompages/style.css

@@ -1,198 +0,0 @@
-/* Color easy change */
-body, .form, #links a, .form-info {
-  color: #DF002A;
-}
-.form-submit, input, select {
-  background-color: #DF002A;
-}
-.form-error {
-	color: red;
-	font-size: 9pt;
-}
-.form-submit {
-	margin: 0;
-	padding: 0;
-	width: 310px;
-	height: 27px;
-	background-color: #DF002A;
-	/*background-image: url(/custompages/images/login-form-submit-bg.jpg);*/
-	color: white;
-	cursor: pointer;
-	cursor: hand;
-}
-/* end easy change */
-/* Registration form */
-#registration-form-box {
-	width: 400px;
-	margin-left: auto;
-	margin-right: auto;
-	margin-top: 50px;
-	border: solid 1px #CCCCCC;
-	text-align: left;
-	background-color: white;
-}
-#registration-form-box .form-submit{
-  width: 400px;
-}
-div.row {
-  clear: both;
-  padding-top: 5px;
-}
-div.row div.form_header {
-  white-space: nowrap;
-  padding: 2px;
-  background-color: #f0f0f0;
-  border: 1px solid #bbb;
-}
-div.row div.label {
-  float: left;
-  width: 53%;
-  text-align: right;
-  padding-right:1%
-}
-div.row div.formw {
-  width: 46%;
-  float:left;
-}
-[dir=ltr] div.row div.label, [dir=rtl] div.row div.formw {
-  float: left;
-  text-align: right;
-}
-[dir=rtl] div.row div.label, [dir=ltr] div.row div.formw {
-  float: right;
-  text-align: left;
-}
-span.form_required {
-  color: #f00;
-}
-span.form_error {
-  color: #f00;
-  font-size: x-small;
-  margin: 2px;
-}
-html, body {
-	margin: 0;
-	padding: 0;
-}
-
-body {
-	font-family: "Arial Black",sans-serif;
-	font-size: 10pt;
-	width: 100%;
-	text-align: center;
-	/*color: #1F3660;*/
-	/*background-image: url(images/page-background.png);
-	background-repeat: no-repeat;
-	background-size: 100%;
-	*/
-}
-
-#backgroundimage {        
-	background-attachment:fixed;
-	width: 100%;
-	height: 100%;
-	position: absolute;
-	left: 0;
-	top: 30px;
-	z-index:-1;
-}
-
-.backgroundimage {
-	width: 100%;
-	height: auto;
-}
-
-#wrapper {
-	position: absolute;
-	top: 0;
-	left: 0;
-	width: 100%;
-	z-index: 1;
-}
-
-#header {
-	width: 520px;
-	margin-left: auto;
-	margin-right: auto;
-	margin-top: 30px;
-}
-
-#footer {
-	position: relative;
-	margin-top: 50px;
-	text-align: center;
-}
-
-.form-box {
-	width: 310px;
-	margin-left: auto;
-	margin-right: auto;
-	margin-top: 50px;
-	border: solid 1px #CCCCCC;
-	text-align: left;
-	background-color: white;
-}
-
-.form {
-	margin-left: 15px;
-	margin-right: 15px;
-	margin-top: 30px;
-	/*color: #1F3660;*/
-	position: relative;
-	text-align: left;
-}
-
-
-label {
-	width: 100px;
-	float: left;
-	margin-right: 1em;
-	display: block;
-	text-align: right;
-	line-height: 2ex;
-}
-
-input {
-	text-align: left;
-	vertical-align: baseline;
-	margin-bottom: 2em;
-	width: 150px;
-	color: white;
-	/*background-color: #1F3660;*/
-	border: none;
-}
-
-select {
-	width: 150px;
-	color: white;
-	/*background-color: #1F3660;*/
-	border: none;
-	margin-bottom: 2em;
-}
-#links {
-	margin-left: 15px;
-	margin-right: 15px;
-	margin-top: 10px;
-	margin-bottom: 50px;
-	/*color: #1F3660;*/
-}
-
-
-#links a {
-	text-decoration: none;
-}
-
-#links a:hover {
-	text-decoration: underline;
-}
-
-span {
-	margin-right: 30px;
-	margin-top: 3px;
-	float: right;
-}
-
-.form-info {
-	/*color: #1F3660;*/
-	font-size: 9pt;
-}

+ 68 - 68
main/admin/dashboard_add_courses_to_user.php

@@ -36,11 +36,11 @@ $current_user_id = api_get_user_id();
 
 // setting the name of the tool
 if (UserManager::is_admin($user_id)) {
-	$tool_name = get_lang('AssignCoursesToPlatformAdministrator');
-} else if ($user_info['status'] == SESSIONADMIN) {
-	$tool_name = get_lang('AssignCoursesToSessionsAdministrator');
+    $tool_name = get_lang('AssignCoursesToPlatformAdministrator');
+} elseif ($user_info['status'] == SESSIONADMIN) {
+    $tool_name = get_lang('AssignCoursesToSessionsAdministrator');
 } else {
-	$tool_name = get_lang('AssignCoursesToHumanResourcesManager');
+    $tool_name = get_lang('AssignCoursesToHumanResourcesManager');
 }
 
 $add_type = 'multiple';
@@ -74,20 +74,20 @@ function search_courses($needle, $type)
         if (api_is_multiple_url_enabled()) {
             $sql = "SELECT c.code, c.title
                     FROM $tbl_course c
-					LEFT JOIN $tbl_course_rel_access_url a
+                    LEFT JOIN $tbl_course_rel_access_url a
                     ON (a.c_id = c.id)
-                	WHERE
-                		c.code LIKE '$needle%' $without_assigned_courses AND
-                		access_url_id = ".api_get_current_access_url_id();
+                    WHERE
+                        c.code LIKE '$needle%' $without_assigned_courses AND
+                        access_url_id = ".api_get_current_access_url_id();
         } else {
             $sql = "SELECT c.code, c.title
-            		FROM $tbl_course c
-                	WHERE
-                		c.code LIKE '$needle%'
-                		$without_assigned_courses ";
+                    FROM $tbl_course c
+                    WHERE
+                        c.code LIKE '$needle%'
+                        $without_assigned_courses ";
         }
 
-		$rs = Database::query($sql);
+        $rs = Database::query($sql);
 
         $return .= '<select id="origin" name="NoAssignedCoursesList[]" multiple="multiple" size="20" >';
         while ($course = Database :: fetch_array($rs)) {
@@ -103,51 +103,51 @@ $xajax->processRequests();
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '<script>
 function moveItem(origin , destination) {
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
+    for(var i = 0 ; i<origin.options.length ; i++) {
+        if(origin.options[i].selected) {
+            destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+            origin.options[i]=null;
+            i = i-1;
+        }
+    }
+    destination.selectedIndex = -1;
+    sortOptions(destination.options);
 }
 function sortOptions(options) {
-	var newOptions = new Array();
-	for (i = 0 ; i<options.length ; i++) {
-		newOptions[i] = options[i];
-	}
-	newOptions = newOptions.sort(mysort);
-	options.length = 0;
-	for(i = 0 ; i < newOptions.length ; i++){
-		options[i] = newOptions[i];
-	}
+    var newOptions = new Array();
+    for (i = 0 ; i<options.length ; i++) {
+        newOptions[i] = options[i];
+    }
+    newOptions = newOptions.sort(mysort);
+    options.length = 0;
+    for(i = 0 ; i < newOptions.length ; i++){
+        options[i] = newOptions[i];
+    }
 }
 function mysort(a, b) {
-	if (a.text.toLowerCase() > b.text.toLowerCase()) {
-		return 1;
-	}
-	if (a.text.toLowerCase() < b.text.toLowerCase()) {
-		return -1;
-	}
-	return 0;
+    if (a.text.toLowerCase() > b.text.toLowerCase()) {
+        return 1;
+    }
+    if (a.text.toLowerCase() < b.text.toLowerCase()) {
+        return -1;
+    }
+    return 0;
 }
 
 function valide() {
-	var options = document.getElementById("destination").options;
-	for (i = 0 ; i<options.length ; i++) {
-		options[i].selected = true;
-	}
-	document.forms.formulaire.submit();
+    var options = document.getElementById("destination").options;
+    for (i = 0 ; i<options.length ; i++) {
+        options[i].selected = true;
+    }
+    document.forms.formulaire.submit();
 }
 function remove_item(origin) {
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
+    for(var i = 0 ; i<origin.options.length ; i++) {
+        if(origin.options[i].selected) {
+            origin.options[i]=null;
+            i = i-1;
+        }
+    }
 }
 </script>';
 
@@ -184,23 +184,23 @@ echo Display::page_header(
 $assigned_courses_to_hrm = CourseManager::get_courses_followed_by_drh($user_id);
 $assigned_courses_code = array_keys($assigned_courses_to_hrm);
 foreach ($assigned_courses_code as &$value) {
-	$value = "'".$value."'";
+    $value = "'".$value."'";
 }
 
 $without_assigned_courses = '';
 if (count($assigned_courses_code) > 0) {
-	$without_assigned_courses = " AND c.code NOT IN(".implode(',', $assigned_courses_code).")";
+    $without_assigned_courses = " AND c.code NOT IN(".implode(',', $assigned_courses_code).")";
 }
 
 $needle = '%';
 $firstLetter = null;
 if (isset($_POST['firstLetterCourse'])) {
-	$firstLetter = $_POST['firstLetterCourse'];
-	$needle = Database::escape_string($firstLetter.'%');
+    $firstLetter = $_POST['firstLetterCourse'];
+    $needle = Database::escape_string($firstLetter.'%');
 }
 
 if (api_is_multiple_url_enabled()) {
-	$sql = " SELECT c.code, c.title
+    $sql = " SELECT c.code, c.title
             FROM $tbl_course c
             LEFT JOIN $tbl_course_rel_access_url a
             ON (a.c_id = c.id)
@@ -210,8 +210,8 @@ if (api_is_multiple_url_enabled()) {
             ORDER BY c.title";
 
 } else {
-	$sql = " SELECT c.code, c.title
-	        FROM $tbl_course c
+    $sql = " SELECT c.code, c.title
+            FROM $tbl_course c
             WHERE  c.code LIKE '$needle' $without_assigned_courses
             ORDER BY c.title";
 }
@@ -223,7 +223,7 @@ $result = Database::query($sql);
 <input type="hidden" name="formSent" value="1" />
 <?php
 if (!empty($msg)) {
-	echo Display::return_message($msg, 'normal'); //main API
+    echo Display::return_message($msg, 'normal'); //main API
 }
 ?>
 
@@ -232,11 +232,11 @@ if (!empty($msg)) {
         <h5><?php echo get_lang('CoursesListInPlatform') ?> :</h5>
 
         <div id="ajax_list_courses_multiple">
-	<select id="origin" name="NoAssignedCoursesList[]" multiple="multiple" size="20" style="width:340px;">
-	<?php while ($enreg = Database::fetch_array($result)) { ?>
+    <select id="origin" name="NoAssignedCoursesList[]" multiple="multiple" size="20" style="width:340px;">
+    <?php while ($enreg = Database::fetch_array($result)) { ?>
             <option value="<?php echo $enreg['code']; ?>" <?php echo 'title="'.htmlspecialchars($enreg['title'], ENT_QUOTES).'"'; ?>><?php echo $enreg['title'].' ('.$enreg['code'].')'; ?></option>
-	<?php } ?>
-	</select>
+    <?php } ?>
+    </select>
         </div>
 
     </div>
@@ -268,13 +268,13 @@ if (!empty($msg)) {
     </div>
     <div class="col-md-4">
         <h5><?php
-	  	if (UserManager::is_admin($user_id)) {
-			echo get_lang('AssignedCoursesListToPlatformAdministrator');
-		} else if ($user_info['status'] == SESSIONADMIN) {
-			echo get_lang('AssignedCoursesListToSessionsAdministrator');
-		} else {
-			echo get_lang('AssignedCoursesListToHumanResourcesManager');
-		}
+        if (UserManager::is_admin($user_id)) {
+            echo get_lang('AssignedCoursesListToPlatformAdministrator');
+        } elseif ($user_info['status'] == SESSIONADMIN) {
+            echo get_lang('AssignedCoursesListToSessionsAdministrator');
+        } else {
+            echo get_lang('AssignedCoursesListToHumanResourcesManager');
+        }
             ?>: </h5>
 
         <select id='destination' name="CoursesList[]" multiple="multiple" size="20" style="width:320px;">

+ 2 - 2
main/admin/dashboard_add_sessions_to_user.php

@@ -39,7 +39,7 @@ $ajax_search = false;
 // Setting the name of the tool
 if (UserManager::is_admin($user_id)) {
     $tool_name = get_lang('AssignSessionsToPlatformAdministrator');
-} else if ($user_info['status'] == SESSIONADMIN) {
+} elseif ($user_info['status'] == SESSIONADMIN) {
     $tool_name = get_lang('AssignSessionsToSessionsAdministrator');
 } else {
     $tool_name = get_lang('AssignSessionsToHumanResourcesManager');
@@ -276,7 +276,7 @@ $result = Database::query($sql);
                 <?php
                 if (UserManager::is_admin($user_id)) {
                     echo get_lang('AssignedSessionsListToPlatformAdministrator');
-                } else if ($user_info['status'] == SESSIONADMIN) {
+                } elseif ($user_info['status'] == SESSIONADMIN) {
                     echo get_lang('AssignedSessionsListToSessionsAdministrator');
                 } else {
                     echo get_lang('AssignedSessionsListToHumanResourcesManager');

+ 63 - 22
main/admin/index.php

@@ -321,10 +321,13 @@ $items[] = array(
     'url' => $sessionPath.'session_export.php',
     'label' => get_lang('ExportSessionListXMLCSV'),
 );
-$items[] = array(
-    'url' => '../coursecopy/copy_course_session.php',
-    'label' => get_lang('CopyFromCourseInSessionToAnotherSession')
-);
+
+if (api_is_global_platform_admin()) {
+    $items[] = array(
+        'url' => '../coursecopy/copy_course_session.php',
+        'label' => get_lang('CopyFromCourseInSessionToAnotherSession')
+    );
+}
 
 if (api_is_platform_admin()) {
     // option only visible in development mode. Enable through code if required
@@ -340,7 +343,6 @@ $blocks['sessions']['extra'] = null;
 
 /* Settings */
 if (api_is_platform_admin()) {
-
     $blocks['settings']['icon'] = Display::return_icon(
         'settings.png',
         get_lang('System'),
@@ -352,21 +354,44 @@ if (api_is_platform_admin()) {
     $blocks['settings']['class'] = 'block-admin-settings';
 
     $items = array();
-    $items[] = array('url' => 'special_exports.php', 'label' => get_lang('SpecialExports'));
-    $items[] = array('url' => 'system_status.php', 'label' => get_lang('SystemStatus'));
+    $items[] = array(
+        'url' => 'special_exports.php',
+        'label' => get_lang('SpecialExports')
+    );
+    $items[] = array(
+        'url' => 'system_status.php',
+        'label' => get_lang('SystemStatus')
+    );
     if (is_dir(api_get_path(SYS_TEST_PATH).'datafiller/')) {
-        $items[] = array('url' => 'filler.php', 'label' => get_lang('DataFiller'));
+        $items[] = array(
+            'url' => 'filler.php',
+            'label' => get_lang('DataFiller')
+        );
     }
 
-    $items[] = array('url' => 'archive_cleanup.php', 'label' => get_lang('ArchiveDirCleanup'));
-    $items[] = array('url' => 'resource_sequence.php', 'label' => get_lang('ResourcesSequencing'));
+    $items[] = array(
+        'url' => 'archive_cleanup.php',
+        'label' => get_lang('ArchiveDirCleanup')
+    );
+    $items[] = array(
+        'url' => 'resource_sequence.php',
+        'label' => get_lang('ResourcesSequencing')
+    );
     if (is_dir(api_get_path(SYS_TEST_PATH))) {
-        $items[] = ['url' => 'email_tester.php', 'label' => get_lang('EMailTester')];
+        $items[] = [
+            'url' => 'email_tester.php',
+            'label' => get_lang('EMailTester')
+        ];
     }
 
-    $items[] = ['url' => api_get_path(WEB_CODE_PATH).'ticket/tickets.php', 'label' => get_lang('TicketSystem')];
+    $items[] = [
+        'url' => api_get_path(WEB_CODE_PATH).'ticket/tickets.php',
+        'label' => get_lang('TicketSystem')
+    ];
 
-    if (api_get_configuration_value('db_manager_enabled') == true && api_is_global_platform_admin()) {
+    if (api_get_configuration_value('db_manager_enabled') == true &&
+        api_is_global_platform_admin()
+    ) {
         $host = $_configuration['db_host'];
         $username = $_configuration['db_user'];
         $databaseName = $_configuration['main_database'];
@@ -382,7 +407,7 @@ if (api_is_platform_admin()) {
     $blocks['settings']['search_form'] = null;
 
     // Skills
-    if (api_get_setting('allow_skills_tool') == 'true') {
+    if (Skill::isToolAvailable()) {
         $blocks['skills']['icon'] = Display::return_icon(
             'skill-badges.png',
             get_lang('Skills'),
@@ -394,17 +419,31 @@ if (api_is_platform_admin()) {
         $blocks['skills']['class'] = 'block-admin-skills';
 
         $items = array();
-        //$items[] = array('url'=>'skills.php',           'label' => get_lang('SkillsTree'));
-        $items[] = array('url' => 'skills_wheel.php', 'label' => get_lang('SkillsWheel'));
-        $items[] = array('url' => 'skills_import.php', 'label' => get_lang('SkillsImport'));
-        $items[] = array('url' => 'skill_list.php', 'label' => get_lang('ManageSkills'));
-        $items[] = array('url'=>'skill.php', 'label' => get_lang('ManageSkillsLevels'));
-        //$items[] = array('url'=>'skills_profile.php',   'label' => get_lang('SkillsProfile'));
+        $items[] = array(
+            'url' => 'skills_wheel.php',
+            'label' => get_lang('SkillsWheel')
+        );
+        $items[] = array(
+            'url' => 'skills_import.php',
+            'label' => get_lang('SkillsImport')
+        );
+        $items[] = array(
+            'url' => 'skill_list.php',
+            'label' => get_lang('ManageSkills')
+        );
+        $items[] = array(
+            'url' => 'skill.php',
+            'label' => get_lang('ManageSkillsLevels')
+        );
+
         $items[] = array(
             'url' => api_get_path(WEB_CODE_PATH).'social/skills_ranking.php',
             'label' => get_lang('SkillsRanking')
         );
-        $items[] = array('url' => 'skills_gradebook.php', 'label' => get_lang('SkillsAndGradebooks'));
+        $items[] = array(
+            'url' => 'skills_gradebook.php',
+            'label' => get_lang('SkillsAndGradebooks')
+        );
         $items[] = array(
             'url' => api_get_path(WEB_CODE_PATH).'admin/skill_badge.php',
             'label' => get_lang('Badges')
@@ -413,7 +452,9 @@ if (api_is_platform_admin()) {
         $blocks['skills']['extra'] = null;
         $blocks['skills']['search_form'] = null;
     }
+}
 
+if (api_is_platform_admin()) {
     /* Plugins */
     global $_plugins;
     if (isset($_plugins['menu_administrator']) && count($_plugins['menu_administrator']) > 0) {
@@ -569,7 +610,7 @@ $useCookieValidation = api_get_setting('cookie_warning');
 if ($useCookieValidation === 'true') {
     if (isset($_POST['acceptCookies'])) {
         api_set_site_use_cookie_warning_cookie();
-    } else if (!api_site_use_cookie_warning_cookie_exist()) {
+    } elseif (!api_site_use_cookie_warning_cookie_exist()) {
         if (Template::isToolBarDisplayedForUser()) {
             $tpl->assign('toolBarDisplayed', true);
         } else {

+ 6 - 5
main/admin/skill_badge.php

@@ -11,9 +11,9 @@ require_once __DIR__.'/../inc/global.inc.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 
-if (!api_is_platform_admin() || api_get_setting('allow_skills_tool') !== 'true') {
-    api_not_allowed(true);
-}
+api_protect_admin_script();
+Skill::isAllow();
+
 $backpack = 'https://backpack.openbadges.org/';
 
 $configBackpack = api_get_setting('openbadges_backpack');
@@ -33,10 +33,11 @@ $toolbar = Display::url(
         'list_badges.png',
         get_lang('ManageSkills'),
         null,
-        ICON_SIZE_MEDIUM),
+        ICON_SIZE_MEDIUM
+    ),
     api_get_path(WEB_CODE_PATH).'admin/skill_list.php',
     ['title' => get_lang('ManageSkills')]
-    );
+);
 
 $tpl = new Template(get_lang('Badges'));
 $tpl->assign('backpack', $backpack);

+ 5 - 10
main/admin/skill_badge_create.php

@@ -13,21 +13,18 @@ $cidReset = true;
 
 require_once __DIR__.'/../inc/global.inc.php';
 
-if (!api_is_platform_admin() || api_get_setting('allow_skills_tool') !== 'true') {
-    api_not_allowed(true);
-}
+api_protect_admin_script();
+Skill::isAllow();
 
 $this_section = SECTION_PLATFORM_ADMIN;
 
 $skillId = intval($_GET['id']);
-
 $objSkill = new Skill();
 $skill = $objSkill->get($skillId);
 
 $htmlHeadXtra[] = '<link  href="'.api_get_path(WEB_LIBRARY_JS_PATH).'badge-studio/media/css/core.css" rel="stylesheet">';
 
 // Add badge studio paths
-
 $badgeStudio = [
     'core' => api_get_path(WEB_LIBRARY_JS_PATH).'badge-studio/',
     'media' => api_get_path(WEB_LIBRARY_JS_PATH).'badge-studio/media/',
@@ -45,13 +42,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         'id' => $skillId
     );
 
-    if ((isset($_FILES['image']) && $_FILES['image']['error'] == 0) || !empty($_POST['badge_studio_image'])) {
+    if ((isset($_FILES['image']) && $_FILES['image']['error'] == 0) ||
+        !empty($_POST['badge_studio_image'])
+    ) {
         $dirPermissions = api_get_permissions_for_new_directories();
-
         $fileName = sha1($_POST['name']);
-
         $badgePath = api_get_path(SYS_UPLOAD_PATH).'badges/';
-
         $existsBadgesDirectory = is_dir($badgePath);
 
         if (!$existsBadgesDirectory) {
@@ -68,7 +64,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
             }
 
             $skillImagePath = sprintf("%s%s.png", $badgePath, $fileName);
-
             if (!empty($_POST['badge_studio_image'])) {
                 $badgeImage = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $_POST['badge_studio_image']));
                 file_put_contents($skillImagePath, $badgeImage);

+ 2 - 3
main/admin/skill_badge_list.php

@@ -13,9 +13,8 @@ $cidReset = true;
 
 require_once __DIR__.'/../inc/global.inc.php';
 
-if (!api_is_platform_admin() || api_get_setting('allow_skills_tool') !== 'true') {
-    api_not_allowed(true);
-}
+api_protect_admin_script();
+Skill::isAllow();
 
 $this_section = SECTION_PLATFORM_ADMIN;
 

+ 1 - 5
main/admin/skill_create.php

@@ -16,10 +16,7 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'skill_list.php', 'name' => get_lang('ManageSkills'));
@@ -49,7 +46,6 @@ $allSkills = $objSkill->get_all();
 $allGradebooks = $objGradebook->find('all');
 
 // This procedure is for check if there is already a Skill with no Parent (Root by default)
-
 $isAlreadyRootSkill = false;
 
 foreach ($allSkills as $checkedSkill) {

+ 1 - 4
main/admin/skill_edit.php

@@ -16,10 +16,7 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'skill_list.php', 'name' => get_lang('ManageSkills'));

+ 6 - 9
main/admin/skill_list.php

@@ -14,10 +14,7 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 $action = isset($_GET['action']) ? $_GET['action'] : 'list';
 $skillId = isset($_GET['id']) ? intval($_GET['id']) : 0;
@@ -115,7 +112,7 @@ switch ($action) {
         //no break
     default:
         $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-        
+
         $toolbar = Display::url(
             Display::return_icon(
                 'add.png',
@@ -125,7 +122,7 @@ switch ($action) {
             api_get_path(WEB_CODE_PATH).'admin/skill_create.php',
             ['title' => get_lang('CreateSkill')]
             );
-        
+
         $toolbar .= Display::url(
             Display::return_icon(
                 'wheel_skill.png',
@@ -135,7 +132,7 @@ switch ($action) {
             api_get_path(WEB_CODE_PATH).'admin/skills_wheel.php',
             ['title' => get_lang('SkillsWheel')]
             );
-              
+
         $toolbar .= Display::url(
             Display::return_icon(
                 'edit-skill.png',
@@ -145,7 +142,7 @@ switch ($action) {
             api_get_path(WEB_CODE_PATH).'admin/skill_badge_list.php',
             ['title' => get_lang('BadgesManagement')]
             );
-        
+
         $toolbar .= Display::url(
             Display::return_icon(
                 'import_csv.png',
@@ -155,7 +152,7 @@ switch ($action) {
             api_get_path(WEB_CODE_PATH).'admin/skills_import.php',
             ['title' => get_lang('ImportSkillsListCSV')]
             );
-        
+
         $extraField = new ExtraField('skill');
         $arrayVals = $extraField->get_handler_field_info_by_tags('tags');
         $tags = [];

+ 1 - 4
main/admin/skills.php

@@ -11,10 +11,7 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 //Adds the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_js('jquery.jsPlumb.all.js');

+ 8 - 16
main/admin/skills_gradebook.php

@@ -11,19 +11,14 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 //Adds the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
 $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'display';
 
-
 // setting breadcrumbs
-
 $tool_name = get_lang('SkillsAndGradebooks');
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 if ($action == 'add_skill') {
@@ -31,11 +26,9 @@ if ($action == 'add_skill') {
     $tool_name = get_lang('Add');
 }
 
-
 Display::display_header($tool_name);
 
 //jqgrid will use this URL to do the selects
-
 $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_gradebooks';
 
 //The order is important you need to check the the $column variable in the model.ajax.php file
@@ -84,13 +77,13 @@ $extra_params['height'] = 'auto';
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
-                        //certificates
-                        if (rowObject[4] == 1) {
-                            return \'<a href="?action=add_skill&id=\'+options.rowId+\'">'.Display::return_icon('add.png', get_lang('AddSkill'), '', ICON_SIZE_SMALL).'</a>'.'\';
-                        } else {
-                            return \''.Display::return_icon('add_na.png', get_lang('YourGradebookFirstNeedsACertificateInOrderToBeLinkedToASkill'), '', ICON_SIZE_SMALL).''.'\';
-                        }
-                 }';
+    //certificates
+    if (rowObject[4] == 1) {
+        return \'<a href="?action=add_skill&id=\'+options.rowId+\'">'.Display::return_icon('add.png', get_lang('AddSkill'), '', ICON_SIZE_SMALL).'</a>'.'\';
+    } else {
+        return \''.Display::return_icon('add_na.png', get_lang('YourGradebookFirstNeedsACertificateInOrderToBeLinkedToASkill'), '', ICON_SIZE_SMALL).''.'\';
+    }
+}';
 ?>
 <script>
 $(function() {
@@ -120,7 +113,6 @@ switch ($action) {
             }
         }
         $form->display();
-        //echo Display::tag('h2',$gradebook_info['name']);
         break;
 }
 Display::display_footer();

+ 4 - 9
main/admin/skills_profile.php

@@ -12,24 +12,19 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 $interbreadcrumb[] = array(
     'url' => 'index.php',
     "name" => get_lang('PlatformAdmin'),
 );
 
-$skill           = new Skill();
-$skill_profile   = new SkillProfile();
-$skill_rel_user  = new SkillRelUser();
+$skill = new Skill();
+$skill_profile = new SkillProfile();
+$skill_rel_user = new SkillRelUser();
 
 $url = api_get_path(WEB_AJAX_PATH).'skill.ajax.php';
-
 $tpl = new Template(get_lang('Skills'));
-
 $form = new FormValidator('profile_search');
 
 $form->addElement('header', get_lang('SearchSkills'));

+ 6 - 5
main/admin/skills_wheel.php

@@ -11,10 +11,7 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script(false, true);
-
-if (api_get_setting('allow_skills_tool') != 'true') {
-    api_not_allowed();
-}
+Skill::isAllow();
 
 //Adds the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_js('d3/d3.v3.5.4.min.js');
@@ -60,7 +57,11 @@ $dialogForm->addLabel(
 );
 $dialogForm->addLabel(
     get_lang('Description'),
-    Display::tag('p', null, ['id' => 'description', 'class' => 'form-control-static'])
+    Display::tag(
+        'p',
+        null,
+        ['id' => 'description', 'class' => 'form-control-static']
+    )
 );
 
 $tpl->assign('dialogForm', $dialogForm->returnForm());

+ 1 - 1
main/admin/user_export.php

@@ -101,7 +101,7 @@ if ($form->validate()) {
                         cu.relation_type<>".COURSE_RELATION_TYPE_RRHH."
                     ORDER BY lastname,firstname";
         $filename = 'export_users_'.$course_code.'_'.api_get_local_time();
-    } else if (strlen($courseSessionCode) > 0) {
+    } elseif (strlen($courseSessionCode) > 0) {
         $sql .= " FROM $user_table u, $session_course_user_table scu
                     WHERE
                         u.user_id = scu.user_id AND

+ 31 - 10
main/admin/user_information.php

@@ -1,7 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
-use Chamilo\UserBundle\Entity\User,
-    Chamilo\CoreBundle\Entity\UserRelUser;
+
+use Chamilo\UserBundle\Entity\User;
+use Chamilo\CoreBundle\Entity\UserRelUser;
 
 /**
  * Script showing information about a user (name, e-mail, courses and sessions)
@@ -41,7 +42,7 @@ $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdm
 $interbreadcrumb[] = array("url" => 'user_list.php', "name" => get_lang('UserList'));
 
 $userId = $user['user_id'];
-$tool_name = $user['complete_name'].(empty($user['official_code']) ? '' : ' ('.$user['official_code'].')');
+$tool_name = $userEntity->getCompleteName();
 $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
 $csvContent = [];
@@ -49,7 +50,12 @@ $csvContent = [];
 // only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
 $actions = [
     Display::url(
-        Display::return_icon('statistics.png', get_lang('Reporting'), [], ICON_SIZE_MEDIUM),
+        Display::return_icon(
+            'statistics.png',
+            get_lang('Reporting'),
+            [],
+            ICON_SIZE_MEDIUM
+        ),
         api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?'.http_build_query([
             'student' => intval($_GET['user_id'])
         ]),
@@ -65,8 +71,7 @@ if (api_is_platform_admin()) {
             [],
             ICON_SIZE_MEDIUM
         ),
-        api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&user_id='.$userId.'&'
-            .'sec_token='.$_SESSION['sec_token']
+        api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&user_id='.$userId.'&sec_token='.$_SESSION['sec_token']
     );
 
     $actions[] = Display::url(
@@ -99,8 +104,21 @@ if (api_is_platform_admin()) {
     );
     $actions[] = Display::url(
         Display::return_icon('new_group.png', get_lang('AddHrmToUser'), [], ICON_SIZE_MEDIUM),
-        api_get_path(WEB_PATH).'main/admin/add_drh_to_user.php?u='.$userId
+        api_get_path(WEB_CODE_PATH).'admin/add_drh_to_user.php?u='.$userId
     );
+
+    if (Skill::isAllow($userId, false)) {
+        $actions[] = Display::url(
+            Display::return_icon(
+                'skill-badges.png',
+                get_lang('AddSkill'),
+                array(),
+                ICON_SIZE_MEDIUM,
+                false
+            ),
+            api_get_path(WEB_CODE_PATH).'badge/assign.php?user='.$userId
+        );
+    }
 }
 
 $studentBossList = UserManager::getStudentBossList($userId);
@@ -165,8 +183,8 @@ $table = new HTML_Table(array('class' => 'data_table'));
 $table->setHeaderContents(0, 0, get_lang('Tracking'));
 $csvContent[] = [get_lang('Tracking')];
 $data = array(
-    get_lang('FirstLogin') => Tracking :: get_first_connection_date($userId),
-    get_lang('LatestLogin') => Tracking :: get_last_connection_date($userId, true)
+    get_lang('FirstLogin') => Tracking::get_first_connection_date($userId),
+    get_lang('LatestLogin') => Tracking::get_last_connection_date($userId, true)
 );
 
 if (api_get_setting('allow_terms_conditions') === 'true') {
@@ -503,7 +521,10 @@ if (isset($_GET['action'])) {
             break;
         case 'delete_legal':
             $extraFieldValue = new ExtraFieldValue('user');
-            $value = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'legal_accept');
+            $value = $extraFieldValue->get_values_by_handler_and_field_variable(
+                $userId,
+                'legal_accept'
+            );
             $result = $extraFieldValue->delete($value['id']);
             if ($result) {
                 Display::addFlash(Display::return_message(get_lang('Deleted')));

+ 47 - 25
main/attendance/attendance_controller.php

@@ -30,10 +30,8 @@ class AttendanceController
      */
     public function attendance_list()
     {
-        $data = array();
-
         // render to the view
-        $this->view->set_data($data);
+        $this->view->set_data([]);
         $this->view->set_layout('layout');
         $this->view->set_template('attendance_list');
         $this->view->render();
@@ -87,7 +85,7 @@ class AttendanceController
     /**
      * It's used for editing attendance,
      * render to attendance_edit or attendance_list view
-     * @param int	$attendance_id
+     * @param int $attendance_id
      */
     public function attendance_edit($attendance_id)
     {
@@ -154,7 +152,7 @@ class AttendanceController
     /**
      * It's used for delete attendaces
      * render to attendance_list view
-     * @param int	$attendance_id
+     * @param int $attendance_id
      */
     public function attendance_delete($attendance_id)
     {
@@ -264,8 +262,12 @@ class AttendanceController
      * @param int    $student_id
      * @param bool   $edit
      */
-    public function attendance_sheet($action, $attendance_id, $student_id = 0, $edit = true)
-    {
+    public function attendance_sheet(
+        $action,
+        $attendance_id,
+        $student_id = 0,
+        $edit = true
+    ) {
         $attendance = new Attendance();
         $data = array();
         $data['attendance_id'] = $attendance_id;
@@ -284,7 +286,11 @@ class AttendanceController
 
         if ($edit == true) {
             if (api_is_allowed_to_edit(null, true) || $isDrhOfCourse) {
-                $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id, 0, $groupId);
+                $data['users_presence'] = $attendance->get_users_attendance_sheet(
+                    $attendance_id,
+                    0,
+                    $groupId
+                );
             }
         } else {
             if (!empty($student_id)) {
@@ -297,17 +303,29 @@ class AttendanceController
                 api_is_coach(api_get_session_id(), api_get_course_int_id()) ||
                 $isDrhOfCourse
             ) {
-                $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id, 0, $groupId);
+                $data['users_presence'] = $attendance->get_users_attendance_sheet(
+                    $attendance_id,
+                    0,
+                    $groupId
+                );
             } else {
-                $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id, $user_id, $groupId);
+                $data['users_presence'] = $attendance->get_users_attendance_sheet(
+                    $attendance_id,
+                    $user_id,
+                    $groupId
+                );
             }
 
             $data['faults']  = $attendance->get_faults_of_user($user_id, $attendance_id, $groupId);
             $data['user_id'] = $user_id;
         }
 
-        $data['next_attendance_calendar_id'] = $attendance->get_next_attendance_calendar_id($attendance_id);
-        $data['next_attendance_calendar_datetime'] = $attendance->get_next_attendance_calendar_datetime($attendance_id);
+        $data['next_attendance_calendar_id'] = $attendance->get_next_attendance_calendar_id(
+            $attendance_id
+        );
+        $data['next_attendance_calendar_datetime'] = $attendance->get_next_attendance_calendar_datetime(
+            $attendance_id
+        );
 
         if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
             if (isset($_POST['hidden_input'])) {
@@ -357,8 +375,8 @@ class AttendanceController
      * It's used for controlling attendance calendar (list, add, edit, delete),
      * render to attendance_calendar view
      * @param string $action (optional, by default 'calendar_list')
-     * @param int	 $attendance_id (optional)
-     * @param int	 $calendar_id (optional)
+     * @param int $attendance_id (optional)
+     * @param int $calendar_id (optional)
      */
     public function attendance_calendar($action = 'calendar_list', $attendance_id = 0, $calendar_id = 0)
     {
@@ -375,7 +393,8 @@ class AttendanceController
                     if (isset($_POST['repeat'])) {
                         //@todo  check this error_logs
                         $start_datetime = api_strtotime(
-                            api_get_utc_datetime($_POST['date_time']), 'UTC'
+                            api_get_utc_datetime($_POST['date_time']),
+                            'UTC'
                         );
 
                         $end_datetime = api_strtotime(api_get_utc_datetime($_POST['end_date_time'].' 23:59:59'), 'UTC');
@@ -416,7 +435,7 @@ class AttendanceController
                     $action = 'calendar_list';
                 }
             }
-        } else if ($action === 'calendar_edit') {
+        } elseif ($action === 'calendar_edit') {
             $data['calendar_id'] = $calendar_id;
             if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {
                 if (!isset($_POST['cancel'])) {
@@ -430,10 +449,10 @@ class AttendanceController
                     $action = 'calendar_list';
                 }
             }
-        } else if ($action == 'calendar_delete') {
+        } elseif ($action == 'calendar_delete') {
             $attendance->attendance_calendar_delete($calendar_id, $attendance_id);
             $action = 'calendar_list';
-        } else if ($action == 'calendar_all_delete') {
+        } elseif ($action == 'calendar_all_delete') {
             $attendance->attendance_calendar_delete(0, $attendance_id, true);
             $action = 'calendar_list';
         }
@@ -459,10 +478,14 @@ class AttendanceController
      * @param string $action
      * @param int    $attendance_id
      */
-    public function attendance_sheet_export_to_pdf($action, $attendance_id, $student_id = 0, $course_id = '')
-    {
+    public function attendance_sheet_export_to_pdf(
+        $action,
+        $attendance_id,
+        $student_id = 0,
+        $course_id = ''
+    ) {
         $attendance = new Attendance();
-        $courseInfo = CourseManager::get_course_information($course_id);
+        $courseInfo = api_get_course_info($course_id);
         $attendance->set_course_id($courseInfo['code']);
         $groupId = isset($_REQUEST['group_id']) ? $_REQUEST['group_id'] : null;
         $data_array = array();
@@ -504,7 +527,7 @@ class AttendanceController
         $data_array['next_attendance_calendar_id'] = $attendance->get_next_attendance_calendar_id($attendance_id);
 
         // Set headers pdf.
-        $courseCategory = CourseManager::get_course_category($courseInfo['category_code']);
+        $courseCategory = CourseManager::get_course_category($courseInfo['categoryCode']);
         $teacherInfo = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
         $teacherName = null;
         foreach ($teacherInfo as $teacherData) {
@@ -615,6 +638,7 @@ class AttendanceController
      * Gets attendance base in the table:
      * TABLE_STATISTIC_TRACK_E_COURSE_ACCESS
      * @param bool $showForm
+     * @param bool $exportToPdf
      */
     public function getAttendanceBaseInLogin($showForm = false, $exportToPdf = true)
     {
@@ -628,8 +652,7 @@ class AttendanceController
             $form = new FormValidator(
                 'search',
                 'post',
-                api_get_self().'?'.api_get_cidreq(
-                ).'&action=calendar_logins'
+                api_get_self().'?'.api_get_cidreq().'&action=calendar_logins'
             );
             $form->addDateRangePicker('range', get_lang('DateRange'));
             $form->addButton('submit', get_lang('Submit'));
@@ -650,7 +673,6 @@ class AttendanceController
         }
 
         $attendance = new Attendance();
-
         if ($exportToPdf) {
             $result = $attendance->exportAttendanceLogin($startDate, $endDate);
             if (empty($result)) {

+ 63 - 31
main/attendance/index.php

@@ -179,9 +179,15 @@ if (api_is_drh() && isset($_GET['student_id'])) {
     );
 }
 if (api_is_in_gradebook()) {
-    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'gradebook/index.php?'.api_get_cidreq(), 'name' => get_lang('ToolGradebook'));
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'gradebook/index.php?'.api_get_cidreq(),
+        'name' => get_lang('ToolGradebook')
+    );
 }
-$interbreadcrumb[] = array('url' => 'index.php?'.api_get_cidreq().'&action=attendance_list&'.$student_param, 'name' => get_lang('ToolAttendance'));
+$interbreadcrumb[] = array(
+    'url' => 'index.php?'.api_get_cidreq().'&action=attendance_list&'.$student_param,
+    'name' => get_lang('ToolAttendance')
+);
 if ($action == 'attendance_add') {
     $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('CreateANewAttendance'));
 }
@@ -192,96 +198,118 @@ if ($action == 'attendance_sheet_list' || $action == 'attendance_sheet_add') {
     $interbreadcrumb[] = array('url' => '#', 'name' => $attendance_data['name']);
 }
 if ($action == 'calendar_list' || $action == 'calendar_edit' || $action == 'calendar_delete' || $action == 'calendar_all_delete') {
-    $interbreadcrumb[] = array('url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id, 'name' => $attendance_data['name']);
+    $interbreadcrumb[] = array(
+        'url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id,
+        'name' => $attendance_data['name']
+    );
     $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AttendanceCalendar'));
 }
 if ($action == 'calendar_add') {
-    $interbreadcrumb[] = array('url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id, 'name' => $attendance_data['name']);
+    $interbreadcrumb[] = array(
+        'url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id,
+        'name' => $attendance_data['name']
+    );
     $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddDateAndTime'));
 }
 
+$allowToEdit = api_is_allowed_to_edit(null, true);
+
 // Delete selected attendance
-if (isset($_POST['action']) && $_POST['action'] == 'attendance_delete_select') {
+if (isset($_POST['action']) && $_POST['action'] == 'attendance_delete_select' && $allowToEdit) {
     $attendanceController->attendance_delete($_POST['id']);
 }
 
-if (isset($_POST['action']) && $_POST['action'] == 'attendance_set_invisible_select') {
+if (isset($_POST['action']) && $_POST['action'] == 'attendance_set_invisible_select' && $allowToEdit) {
     $attendanceController->attendanceSetInvisible($_POST['id']);
 }
 
-if (isset($_POST['action']) && $_POST['action'] == 'attendance_set_visible_select') {
+if (isset($_POST['action']) && $_POST['action'] == 'attendance_set_visible_select' && $allowToEdit) {
     $attendanceController->attendanceSetVisible($_POST['id']);
 }
 
-// Distpacher actions to controller
 switch ($action) {
     case 'attendance_list':
         $attendanceController->attendance_list();
         break;
     case 'attendance_add':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendance_add();
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     case 'attendance_edit':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendance_edit($attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     case 'attendance_delete':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendance_delete($attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     case 'attendance_set_invisible':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendanceSetInvisible($attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     case 'attendance_set_visible':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendanceSetVisible($attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     /*case 'attendance_restore':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendance_restore($attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;*/
     case 'attendance_sheet_list':
-        $attendanceController->attendance_sheet($action, $attendance_id, $student_id, true);
+        $attendanceController->attendance_sheet(
+            $action,
+            $attendance_id,
+            $student_id,
+            true
+        );
         break;
     case 'attendance_sheet_list_no_edit':
-        $attendanceController->attendance_sheet($action, $attendance_id, $student_id, false);
+        $attendanceController->attendance_sheet(
+            $action,
+            $attendance_id,
+            $student_id,
+            false
+        );
         break;
     case 'attendance_sheet_export_to_pdf':
-        $attendanceController->attendance_sheet_export_to_pdf($action, $attendance_id, $student_id, $course_id);
+        $attendanceController->attendance_sheet_export_to_pdf(
+            $action,
+            $attendance_id,
+            $student_id,
+            $course_id
+        );
         break;
     case 'attendance_sheet_add':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->attendance_sheet($action, $attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     case 'lock_attendance':
     case 'unlock_attendance':
-        if (api_is_allowed_to_edit(null, true)) {
+        if ($allowToEdit) {
             $attendanceController->lock_attendance($action, $attendance_id);
         } else {
-            api_not_allowed();
+            api_not_allowed(true);
         }
         break;
     case 'calendar_add':
@@ -291,15 +319,19 @@ switch ($action) {
     case 'calendar_all_delete':
         //no break
     case 'calendar_delete':
-        if (!api_is_allowed_to_edit(null, true)) {
-            api_not_allowed();
+        if (!$allowToEdit) {
+            api_not_allowed(true);
         }
         //no break
     case 'calendar_list':
-        $attendanceController->attendance_calendar($action, $attendance_id, $calendar_id);
+        $attendanceController->attendance_calendar(
+            $action,
+            $attendance_id,
+            $calendar_id
+        );
         break;
     case 'calendar_logins':
-        if (api_is_allowed_to_edit(null, true) || api_is_drh()) {
+        if (api_is_course_admin() || api_is_drh()) {
             $attendanceController->getAttendanceBaseInLogin(false, true);
         }
         break;

+ 61 - 13
main/badge/assign.php

@@ -1,8 +1,10 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+use \Skill as SkillManager;
 use Chamilo\CoreBundle\Entity\Skill;
 use Chamilo\CoreBundle\Entity\SkillRelUser;
+use Chamilo\UserBundle\Entity\User;
 
 /**
  * Page for assign skills to a user
@@ -13,20 +15,21 @@ use Chamilo\CoreBundle\Entity\SkillRelUser;
 
 require_once __DIR__.'/../inc/global.inc.php';
 
-if (!api_is_platform_admin(false, true) && !api_is_student_boss()) {
-    api_not_allowed(true);
-}
+$userId = isset($_REQUEST['user']) ? (int) $_REQUEST['user'] : 0;
 
-if (!isset($_REQUEST['user'])) {
+if (empty($userId)) {
     api_not_allowed(true);
 }
 
+SkillManager::isAllow($userId);
+
 $entityManager = Database::getManager();
 $skillRepo = $entityManager->getRepository('ChamiloCoreBundle:Skill');
 $skillRelSkill = $entityManager->getRepository('ChamiloCoreBundle:SkillRelSkill');
 $skillLevelRepo = $entityManager->getRepository('ChamiloSkillBundle:Level');
 $skillUserRepo = $entityManager->getRepository('ChamiloCoreBundle:SkillRelUser');
-$user = $entityManager->find('ChamiloUserBundle:User', $_REQUEST['user']);
+/** @var User $user */
+$user = $entityManager->find('ChamiloUserBundle:User', $userId);
 
 if (!$user) {
     Display::addFlash(
@@ -41,7 +44,7 @@ $skills = $skillRepo->findBy([
     'status' => Skill::STATUS_ENABLED
 ]);
 
-$url = api_get_path(WEB_CODE_PATH)."badge/assign.php?user=".$_REQUEST['user']."&id=";
+$url = api_get_path(WEB_CODE_PATH).'badge/assign.php?user='.$userId.'&id=';
 
 $htmlHeadXtra[] = '<script>
 $( document ).ready(function() {
@@ -60,11 +63,9 @@ foreach ($skills as $skill) {
 }
 
 $skillId = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : key($skillsOptions);
-
 $profile = $skillRepo->find($skillId)->getProfile();
 
 if (!$profile) {
-
     $skillRelSkill = new SkillRelSkill();
     $parents = $skillRelSkill->get_skill_parents($skillId);
 
@@ -116,14 +117,18 @@ $form->addSelect('acquired_level', get_lang('AcquiredLevel'), $acquiredLevel);
 $form->addRule('acquired_level', get_lang('ThisFieldIsRequired'), 'required');
 $form->addTextarea('argumentation', get_lang('Argumentation'), ['rows' => 6]);
 $form->addRule('argumentation', get_lang('ThisFieldIsRequired'), 'required');
-$form->addRule('argumentation', sprintf(get_lang('ThisTextShouldBeAtLeastXCharsLong'), 10), 'mintext', 10);
+$form->addRule(
+    'argumentation',
+    sprintf(get_lang('ThisTextShouldBeAtLeastXCharsLong'), 10),
+    'mintext',
+    10
+);
 $form->applyFilter('argumentation', 'trim');
 $form->addButtonSave(get_lang('Save'));
 $form->setDefaults($formDefaultValues);
 
 if ($form->validate()) {
     $values = $form->exportValues();
-
     $skill = $skillRepo->find($values['skill']);
 
     if (!$skill) {
@@ -138,7 +143,11 @@ if ($form->validate()) {
     if ($user->hasSkill($skill)) {
         Display::addFlash(
             Display::return_message(
-                sprintf(get_lang('TheUserXHasAlreadyAchievedTheSkillY'), $user->getCompleteName(), $skill->getName()),
+                sprintf(
+                    get_lang('TheUserXHasAlreadyAchievedTheSkillY'),
+                    $user->getCompleteName(),
+                    $skill->getName()
+                ),
                 'warning'
             )
         );
@@ -162,7 +171,11 @@ if ($form->validate()) {
 
     Display::addFlash(
         Display::return_message(
-            sprintf(get_lang('SkillXAssignedToUserY'), $skill->getName(), $user->getCompleteName()),
+            sprintf(
+                get_lang('SkillXAssignedToUserY'),
+                $skill->getName(),
+                $user->getCompleteName()
+            ),
             'success'
         )
     );
@@ -174,7 +187,42 @@ if ($form->validate()) {
 $form->setDefaults(['user_name' => $user->getCompleteName()]);
 $form->freeze(['user_name']);
 
-$template = new Template('');
+if (api_is_drh()) {
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'mySpace/index.php',
+        "name" => get_lang('MySpace')
+    );
+    if ($user->getStatus() == COURSEMANAGER) {
+        $interbreadcrumb[] = array(
+            "url" => api_get_path(WEB_CODE_PATH).'mySpace/teachers.php',
+            'name' => get_lang('Teachers')
+        );
+    } else {
+        $interbreadcrumb[] = array(
+            "url" => api_get_path(WEB_CODE_PATH).'mySpace/student.php',
+            'name' => get_lang('MyStudents')
+        );
+    }
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$userId,
+        'name' => $user->getCompleteName()
+    );
+} else {
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'admin/index.php',
+        'name' => get_lang('PlatformAdmin')
+    );
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'admin/user_list.php',
+        'name' => get_lang('UserList')
+    );
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'admin/user_information.php?user_id='.$userId,
+        'name' => $user->getCompleteName()
+    );
+}
+
+$template = new Template(get_lang('AddSkill'));
 $template->assign('header', get_lang('AssignSkill'));
 $template->assign('content', $form->returnForm());
 $template->display_one_col_template();

+ 9 - 9
main/badge/issued.php

@@ -1,6 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+use Chamilo\CoreBundle\Entity\SkillRelUserComment;
+
 /**
  * Show information about the issued badge
  * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
@@ -11,9 +13,8 @@ require_once __DIR__.'/../inc/global.inc.php';
 
 $issue = isset($_REQUEST['issue']) ? intval($_REQUEST['issue']) : 0;
 
-if (!$issue) {
-    header('Location: '.api_get_path(WEB_PATH));
-    exit;
+if (empty($issue)) {
+    api_not_allowed(true);
 }
 
 $entityManager = Database::getManager();
@@ -42,6 +43,8 @@ if (!$user || !$skill) {
     exit;
 }
 
+Skill::isAllow($user->getId());
+
 $userInfo = [
     'id' => $user->getId(),
     'complete_name' => $user->getCompleteName()
@@ -120,7 +123,6 @@ $acquiredLevel = [];
 $profile = $skillRepo->find($skillId)->getProfile();
 
 if (!$profile) {
-
     $skillRelSkill = new SkillRelSkill();
     $parents = $skillRelSkill->get_skill_parents($skillId);
 
@@ -142,7 +144,6 @@ if (!$profile) {
 }
 
 if ($profile) {
-
     $profileId = $profile->getId();
 
     $levels = $skillLevelRepo->findBy([
@@ -159,7 +160,6 @@ if ($profile) {
         $profileId = key($profileLevel);
         $acquiredLevel[$profileId] = $profileLevel[$profileId];
     }
-
 }
 
 $formAcquiredLevel = new FormValidator('acquired_level');
@@ -196,14 +196,14 @@ $form->addButtonSend(get_lang('Send'));
 
 if ($form->validate() && $allowComment) {
     $values = $form->exportValues();
-
-    $skillUserComment = new Chamilo\CoreBundle\Entity\SkillRelUserComment();
+    $skillUserComment = new SkillRelUserComment();
     $skillUserComment
         ->setFeedbackDateTime(new DateTime)
         ->setFeedbackGiver($currentUser)
         ->setFeedbackText($values['comment'])
         ->setFeedbackValue($values['value'] ? $values['value'] : null)
-        ->setSkillRelUser($skillIssue);
+        ->setSkillRelUser($skillIssue)
+    ;
 
     $entityManager->persist($skillUserComment);
     $entityManager->flush();

+ 16 - 13
main/badge/issued_all.php

@@ -12,16 +12,14 @@ $userId = isset($_GET['user']) ? intval($_GET['user']) : 0;
 $skillId = isset($_GET['skill']) ? intval($_GET['skill']) : 0;
 
 if (!$userId || !$skillId) {
-    header('Location: '.api_get_path(WEB_PATH));
-    exit;
+    api_not_allowed(true);
 }
 
-$entityManager = Database::getManager();
-$user = $entityManager->find('ChamiloUserBundle:User', $userId);
-$skill = $entityManager->find('ChamiloCoreBundle:Skill', $skillId);
-$skillRepo = $entityManager->getRepository('ChamiloCoreBundle:Skill');
-$skillUserRepo = $entityManager->getRepository('ChamiloCoreBundle:SkillRelUser');
-$skillLevelRepo = $entityManager->getRepository('ChamiloSkillBundle:Level');
+Skill::isAllow($userId);
+
+$em = Database::getManager();
+$user = $em->find('ChamiloUserBundle:User', $userId);
+$skill = $em->find('ChamiloCoreBundle:Skill', $skillId);
 
 $currentUserId = api_get_user_id();
 
@@ -34,6 +32,11 @@ if (!$user || !$skill) {
     exit;
 }
 
+
+$skillRepo = $em->getRepository('ChamiloCoreBundle:Skill');
+$skillUserRepo = $em->getRepository('ChamiloCoreBundle:SkillRelUser');
+$skillLevelRepo = $em->getRepository('ChamiloSkillBundle:Level');
+
 $userSkills = $skillUserRepo->findBy([
     'user' => $user,
     'skill' => $skill
@@ -57,7 +60,7 @@ $skillInfo = [
 $allUserBadges = [];
 
 foreach ($userSkills as $index => $skillIssue) {
-    $currentUser = $entityManager->find('ChamiloUserBundle:User', $currentUserId);
+    $currentUser = $em->find('ChamiloUserBundle:User', $currentUserId);
     $allowDownloadExport = $currentUser ? $currentUser->getId() === $user->getId() : false;
     $allowComment = $currentUser ? Skill::userCanAddFeedbackToUser($currentUser, $user) : false;
     $skillIssueDate = api_get_local_time($skillIssue->getAcquiredSkillAt());
@@ -164,8 +167,8 @@ foreach ($userSkills as $index => $skillIssue) {
         $level = $skillLevelRepo->find($values['acquired_level']);
         $skillIssue->setAcquiredLevel($level);
 
-        $entityManager->persist($skillIssue);
-        $entityManager->flush();
+        $em->persist($skillIssue);
+        $em->flush();
 
         header("Location: ".$skillIssue->getIssueUrlAll());
         exit;
@@ -195,8 +198,8 @@ foreach ($userSkills as $index => $skillIssue) {
             ->setFeedbackValue($values['value'] ? $values['value'] : null)
             ->setSkillRelUser($skillIssue);
 
-        $entityManager->persist($skillUserComment);
-        $entityManager->flush();
+        $em->persist($skillUserComment);
+        $em->flush();
 
         header("Location: ".$skillIssue->getIssueUrlAll());
         exit;

+ 2 - 1
main/badge/issuer.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Show information about the OpenBadge issuer
  * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
@@ -14,4 +15,4 @@ $json = array(
     'url' => api_get_path(WEB_PATH)
 );
 
-echo json_encode($json);
+echo json_encode($json);

+ 2 - 6
main/course_progress/thematic_advance.php

@@ -12,7 +12,6 @@
 api_protect_course_script(true);
 
 if ($action === 'thematic_advance_add' || $action === 'thematic_advance_edit') {
-
     $header_form = get_lang('NewThematicAdvance');
     if ($action === 'thematic_advance_edit') {
         $header_form = get_lang('EditThematicAdvance');
@@ -34,7 +33,7 @@ if ($action === 'thematic_advance_add' || $action === 'thematic_advance_edit') {
     if (!empty($thematic_id)) {
         $form->addElement('hidden', 'thematic_id', $thematic_id);
     }
-    
+
     $radios = array();
     $radios[] = $form->createElement(
         'radio',
@@ -137,7 +136,6 @@ if ($action === 'thematic_advance_add' || $action === 'thematic_advance_edit') {
     }
 
     $attendance_select_item_id = null;
-
     if (count($attendance_select) > 1) {
         $i = 1;
         foreach ($attendance_select as $key => $attendance_select_item) {
@@ -162,7 +160,6 @@ if ($action === 'thematic_advance_add' || $action === 'thematic_advance_edit') {
     $default['duration_in_hours'] = 1;
 
     if (!empty($thematic_advance_data)) {
-
         // set default values
         $default['content'] = isset($thematic_advance_data['content']) ? $thematic_advance_data['content'] : null;
         $default['duration_in_hours'] = isset($thematic_advance_data['duration']) ? $thematic_advance_data['duration'] : 1;
@@ -225,8 +222,7 @@ if ($action === 'thematic_advance_add' || $action === 'thematic_advance_edit') {
     }
 
     $form->display();
-
-} else if ($action == 'thematic_advance_list') {
+} elseif ($action == 'thematic_advance_list') {
     // thematic advance list
     echo '<div class="actions">';
     echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=thematic_details">'.

+ 5 - 7
main/course_progress/thematic_controller.php

@@ -202,7 +202,7 @@ class ThematicController
                 case 'export_documents':
                     //no break
                 case 'thematic_export_pdf':
-                    
+
                     $pdfOrientation = api_get_configuration_value('thematic_pdf_orientation');
 
                     $list = $thematic->get_thematic_list();
@@ -221,7 +221,7 @@ class ThematicController
                                 );
                             }
                             $theme['thematic_plan'] = $item;
-                            
+
                         }
                         $dataAdvance = $thematic->get_thematic_advance_by_thematic_id($theme['id']);
                         if (!empty($dataAdvance)) {
@@ -447,7 +447,7 @@ class ThematicController
                     $data['next_description_type'] = $thematic->get_next_description_type($_POST['thematic_id']);
 
                     // render to the view
-                    
+
                     $this->view->set_data($data);
                     $this->view->set_layout('layout');
                     $this->view->set_template('thematic_plan');
@@ -476,7 +476,7 @@ class ThematicController
             }
             $data['thematic_id'] = $thematic_id;
             $data['description_type'] = $description_type;
-        } else if (!empty($thematic_id) && $action === 'thematic_plan_list') {
+        } elseif (!empty($thematic_id) && $action === 'thematic_plan_list') {
             $data['thematic_plan_data'] = $thematic->get_thematic_plan_data($thematic_id);
             $data['thematic_id'] = $thematic_id;
         }
@@ -490,7 +490,7 @@ class ThematicController
         $data['thematic_data'] = $thematic->get_thematic_list($thematic_id);
 
         //render to the view
-        
+
         $this->view->set_data($data);
         $this->view->set_layout('layout');
         $this->view->set_template('thematic_plan');
@@ -509,7 +509,6 @@ class ThematicController
         $thematic = new Thematic();
         $attendance = new Attendance();
         $data = array();
-
         $displayHeader = (!empty($_REQUEST['display']) && $_REQUEST['display'] === 'no_header') ? false : true;
 
         // get data for attendance input select
@@ -576,7 +575,6 @@ class ThematicController
         $layoutName = $displayHeader ? 'layout' : 'layout_no_header';
 
         // render to the view
-        
         $this->view->set_data($data);
         $this->view->set_layout($layoutName);
         $this->view->set_template('thematic_advance');

+ 1 - 1
main/coursecopy/recycle_course.php

@@ -58,7 +58,7 @@ if (Security::check_token('post') && (
     $recycle_type = '';
     if (isset($_POST['recycle_option']) && $_POST['recycle_option'] == 'full_backup') {
         $recycle_type = 'full_backup';
-    } else if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
+    } elseif (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
         $recycle_type = 'select_items';
     }
     $cr = new CourseRecycler($course);

+ 3 - 1
main/cron/scheduled_announcement.php

@@ -5,7 +5,9 @@ require_once __DIR__.'/../inc/global.inc.php';
 
 $urlList = UrlManager::get_url_data();
 foreach ($urlList as $url) {
-    echo "Portal: # ".$url['id']." - ".$url['url'].PHP_EOL;
+    // Set access_url to set correct paths.
+    $_configuration['access_url'] = $url['id'];
+    echo "Portal: # ".$url['id']." - ".$url['url'].'-'.api_get_path(WEB_CODE_PATH).PHP_EOL;
     $object = new ScheduledAnnouncement();
     $messagesSent = $object->sendPendingMessages($url['id']);
     echo "Messages sent $messagesSent".PHP_EOL;

+ 14 - 11
main/dropbox/dropbox_class.inc.php

@@ -69,9 +69,9 @@ class Dropbox_Work
     public function __construct($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null, $arg6 = null)
     {
         if (func_num_args() > 1) {
-            $this->_createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
+            $this->createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
         } else {
-            $this->_createExistingWork($arg1);
+            $this->createExistingWork($arg1);
         }
     }
 
@@ -88,7 +88,7 @@ class Dropbox_Work
      * @todo    $author was originally a field but this has now been replaced by the first and lastname of the uploader (to prevent anonymous uploads)
      *            As a consequence this parameter can be removed
      */
-    public function _createNewWork($uploader_id, $title, $description, $author, $filename, $filesize)
+    public function createNewWork($uploader_id, $title, $description, $author, $filename, $filesize)
     {
         // Fill in the properties
         $this->uploader_id = intval($uploader_id);
@@ -173,7 +173,7 @@ class Dropbox_Work
      *
      * @param int $id
      */
-    public function _createExistingWork($id)
+    public function createExistingWork($id)
     {
         $course_id = api_get_course_int_id();
         $action = isset($_GET['action']) ? $_GET['action'] : null;
@@ -274,9 +274,9 @@ class Dropbox_SentWork extends Dropbox_Work
     public function __construct($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null, $arg6 = null, $arg7 = null)
     {
         if (func_num_args() > 1) {
-            $this->_createNewSentWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7);
+            $this->createNewSentWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7);
         } else {
-            $this->_createExistingSentWork($arg1);
+            $this->createExistingSentWork($arg1);
         }
     }
 
@@ -291,7 +291,7 @@ class Dropbox_SentWork extends Dropbox_Work
      * @param int $filesize
      * @param array $recipient_ids
      */
-    public function _createNewSentWork($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids)
+    public function createNewSentWork($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids)
     {
         $_course = api_get_course_info();
 
@@ -387,7 +387,7 @@ class Dropbox_SentWork extends Dropbox_Work
      *
      * @param int $id
      */
-    public function _createExistingSentWork($id)
+    public function createExistingSentWork($id)
     {
         $id = intval($id);
         $course_id = api_get_course_int_id();
@@ -517,13 +517,16 @@ class Dropbox_Person
         $id = intval($id);
         $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)."
                 WHERE c_id = $course_id AND cat_id = '".$id."' ";
-        if (!Database::query($sql)) return false;
+        Database::query($sql);
+
         $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)."
                 WHERE c_id = $course_id AND cat_id = '".$id."' ";
-        if (!Database::query($sql)) return false;
+        Database::query($sql);
+
         $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
                 WHERE c_id = $course_id AND cat_id = '".$id."' ";
-        if (!Database::query($sql)) return false;
+        Database::query($sql);
+
         return true;
     }
 

+ 1 - 1
main/exercise/Draggable.php

@@ -49,7 +49,7 @@ class Draggable extends Question
             if (isset($_POST['moreOptions'])) {
                 $nb_options++;
             }
-        } else if (!empty($this->id)) {
+        } elseif (!empty($this->id)) {
             $defaults['orientation'] = in_array($this->extra, ['h', 'v']) ? $this->extra : 'h';
 
             $answer = new Answer($this->id);

+ 4 - 4
main/exercise/question_pool.php

@@ -1,6 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+use ChamiloSession as Session;
+
 /**
  * Question Pool
  * This script allows administrators to manage questions and add them into their exercises.
@@ -11,8 +13,6 @@
  * @author Modify by hubert borderiou 2011-10-21 Question's category
  */
 
-use ChamiloSession as Session;
-
 require_once __DIR__.'/../inc/global.inc.php';
 
 $this_section = SECTION_COURSES;
@@ -58,7 +58,7 @@ if (!empty($objExercise)) {
 }
 
 // message to be displayed if actions successful
-$displayMessage = "";
+$displayMessage = '';
 if ($is_allowedToEdit) {
     // Duplicating a Question
     if (!isset($_POST['recup']) && $question_copy != 0 && isset($fromExercise)) {
@@ -126,7 +126,7 @@ if ($is_allowedToEdit) {
         // Adds the question ID represented by $recup into the list of questions for the current exercise
         $objExercise->addToList($recup);
         Session::write('objExercise', $objExercise);
-    } else if (isset($_POST['recup']) && is_array($_POST['recup']) && $fromExercise) {
+    } elseif (isset($_POST['recup']) && is_array($_POST['recup']) && $fromExercise) {
         $list_recup = $_POST['recup'];
 
         foreach ($list_recup as $course_id => $question_data) {

+ 2 - 3
main/forum/viewforumcategory.php

@@ -114,12 +114,11 @@ if (!api_is_allowed_to_edit(false, true) &&
 }
 
 /* Action Links */
-$html  = '';
-$html .= '<div class="actions">';
+$html = '<div class="actions">';
 $html .= '<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)) {
-    $html .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&forumcategory='
+    $html .= '<a href="'.api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&forumcategory='
         . $current_forum_category['cat_id'].'&action=add&content=forum"> '
         . Display::return_icon('new_forum.png', get_lang('AddForum'), '', ICON_SIZE_MEDIUM).'</a>';
 }

+ 3 - 0
main/glossary/index.php

@@ -379,6 +379,9 @@ switch ($action) {
         header('Location: '.$currentUrl);
         exit;
         break;
+    case 'export_documents':
+        GlossaryManager::movePdfToDocuments();
+        break;
     default:
         $tool_name = get_lang('List');
         $content = GlossaryManager::display_glossary();

+ 7 - 10
main/gradebook/get_badges.php

@@ -9,31 +9,28 @@
 
 require_once __DIR__.'/../inc/global.inc.php';
 
-if (api_get_setting('allow_skills_tool') !== 'true') {
+$userId = isset($_GET['user']) ? (int) $_GET['user'] : 0;
+
+if (empty($userId)) {
     api_not_allowed(true);
 }
 
-$userId = isset($_GET['user']) ? intval($_GET['user']) : 0;
+Skill::isAllow($userId);
+
 $courseId = api_get_course_int_id();
 $sessionId = api_get_session_id();
 
-if ($userId === 0) {
-    exit;
-}
-
 $objSkillRelUser = new SkillRelUser();
 $userSkills = $objSkillRelUser->get_user_skills($userId, $courseId, $sessionId);
 
 if (empty($userSkills)) {
-    exit;
+    api_not_allowed(true);
 }
 
 $assertions = array();
-
 foreach ($userSkills as $skill) {
     $skillId = current($skill);
-
-    $assertionUrl = api_get_path(WEB_CODE_PATH)."badge/assertion.php?";
+    $assertionUrl = api_get_path(WEB_CODE_PATH).'badge/assertion.php?';
     $assertionUrl .= http_build_query(array(
         'user' => $userId,
         'skill' => $skillId,

+ 171 - 55
main/gradebook/gradebook_display_certificate.php

@@ -25,6 +25,7 @@ function confirmation() {
 	}
 }
 </script>";
+
 api_block_anonymous_users();
 
 if (!api_is_allowed_to_edit() && !api_is_student_boss()) {
@@ -36,7 +37,130 @@ $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;
 
+$url = api_get_self().'?'.api_get_cidreq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
+$courseInfo = api_get_course_info();
+
+$filter = api_get_setting('certificate_filter_by_official_code');
+$userList = array();
+$filterForm = null;
+$certificate_list = array();
+if ($filter === 'true') {
+    $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->addButton('submit', get_lang('Submit'));
+    $filterForm = '<br />'.$form->returnForm();
+
+    if ($form->validate()) {
+        $officialCode = $form->getSubmitValue('filter');
+        if ($officialCode == 'all') {
+            $certificate_list = GradebookUtils::get_list_users_certificates($cat_id);
+        } else {
+            $userList = UserManager::getUsersByOfficialCode($officialCode);
+            if (!empty($userList)) {
+                $certificate_list = GradebookUtils::get_list_users_certificates(
+                    $cat_id,
+                    $userList
+                );
+            }
+        }
+    } else {
+        $certificate_list = GradebookUtils::get_list_users_certificates($cat_id);
+    }
+} else {
+    $certificate_list = GradebookUtils::get_list_users_certificates($cat_id);
+}
+
+$content = '';
+
+$tags = [
+    '((course_title))',
+    '((user_first_name))',
+    '((user_last_name))',
+    '((author_first_name))',
+    '((author_last_name))',
+    '((score))',
+    '((portal_name))'
+];
+
 switch ($action) {
+    case 'send_notifications':
+        $currentUserInfo = api_get_user_info();
+        $originalMessage = isset($_POST['message']) ? $_POST['message'] : '';
+        if (!empty($originalMessage)) {
+            foreach ($certificate_list as $index => $value) {
+                $userInfo = api_get_user_info($value['user_id']);
+                if (empty($userInfo)) {
+                    continue;
+                }
+                $list = GradebookUtils::get_list_gradebook_certificates_by_user_id(
+                    $value['user_id'],
+                    $cat_id
+                );
+
+                $subject = get_lang('NotificationCertificateSubject');
+                foreach ($list as $valueCertificate) {
+                    $replace = [
+                        $courseInfo['title'],
+                        $userInfo['firstname'],
+                        $userInfo['lastname'],
+                        $currentUserInfo['firstname'],
+                        $currentUserInfo['lastname'],
+                        $valueCertificate['score_certificate'],
+                        api_get_setting('Institution')
+                    ];
+                    $message = str_replace($tags, $replace, $originalMessage);
+
+                    MessageManager::send_message(
+                        $userInfo['id'],
+                        $subject,
+                        $message,
+                        [],
+                        [],
+                        0,
+                        0,
+                        0,
+                        0,
+                        $currentUserInfo['id']
+                    );
+
+                    $plugin = new AppPlugin();
+                    $smsPlugin = $plugin->getSMSPluginLibrary();
+                    if ($smsPlugin) {
+                        $additionalParameters = array(
+                            'smsType' => SmsPlugin::CERTIFICATE_NOTIFICATION,
+                            'userId' => $userInfo['id'],
+                            'direct_message' => $message
+                        );
+                        $smsPlugin->send($additionalParameters);
+                    }
+                }
+            }
+            Display::addFlash(Display::return_message(get_lang('Sent')));
+        }
+
+        header('Location: '.$url);
+        exit;
+        break;
+    case 'show_notification_form':
+        $form = new FormValidator('notification', 'post', $url.'&action=send_notifications');
+        $form->addHeader(get_lang('SendNotification'));
+        $form->addHtmlEditor('message', get_lang('Message'));
+        $form->addLabel(
+            get_lang('Tags'),
+            Display::return_message(implode('<br />', $tags), 'normal', false)
+        );
+        $form->addButtonSend(get_lang('Send'));
+        $form->setDefaults(
+            ['message' => nl2br(get_lang('NotificationCertificateTemplate'))]
+        );
+        $content = $form->returnForm();
+        break;
     case 'export_all_certificates':
         if (api_is_student_boss()) {
             $userGroup = new UserGroup();
@@ -70,8 +194,6 @@ switch ($action) {
         break;
 }
 
-$course_code = api_get_course_id();
-
 $interbreadcrumb[] = array(
     'url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?',
     'name' => get_lang('Gradebook'),
@@ -98,8 +220,12 @@ if (isset($_GET['action']) && $_GET['action'] == 'delete') {
 $token = Security::get_token();
 echo Display::page_header(get_lang('GradebookListOfStudentsCertificates'));
 
+if (!empty($content)) {
+    echo $content;
+}
+
 //@todo replace all this code with something like get_total_weight()
-$cats = Category:: load($cat_id, null, null, null, null, null, false);
+$cats = Category::load($cat_id, null, null, null, null, null, false);
 
 if (!empty($cats)) {
     //with this fix the teacher only can view 1 gradebook
@@ -123,7 +249,7 @@ if (!empty($cats)) {
     $total_resource_weight = 0;
     if (!empty($datagen)) {
         $data_array = $datagen->get_data(
-            GradebookDataGenerator :: GDG_SORT_NAME,
+            0,
             0,
             null,
             true
@@ -142,59 +268,42 @@ if (!empty($cats)) {
     }
 
     if ($total_resource_weight != $total_weight) {
-        echo Display::return_message(get_lang('SumOfActivitiesWeightMustBeEqualToTotalWeight'), 'warning');
-    }
-}
-
-$filter = api_get_setting('certificate_filter_by_official_code');
-$userList = array();
-$filterForm = null;
-$certificate_list = array();
-if ($filter === 'true') {
-    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->addButton('submit', get_lang('Submit'));
-    $filterForm = '<br />'.$form->returnForm();
-
-    if ($form->validate()) {
-        $officialCode = $form->getSubmitValue('filter');
-        if ($officialCode == 'all') {
-            $certificate_list = GradebookUtils::get_list_users_certificates($cat_id);
-        } else {
-            $userList = UserManager::getUsersByOfficialCode($officialCode);
-            if (!empty($userList)) {
-                $certificate_list = GradebookUtils::get_list_users_certificates(
-                    $cat_id,
-                    $userList
-                );
-            }
-        }
-    } else {
-        $certificate_list = GradebookUtils::get_list_users_certificates($cat_id);
+        echo Display::return_message(
+            get_lang('SumOfActivitiesWeightMustBeEqualToTotalWeight'),
+            'warning'
+        );
     }
-} else {
-    $certificate_list = GradebookUtils::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.'&filter='.$filterOfficialCode;
-echo Display::url(get_lang('GenerateCertificates'), $url, array('class' => 'btn btn-default'));
 
-$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 btn-default'));
+echo Display::url(
+    get_lang('GenerateCertificates'),
+    $url.'&action=generate_all_certificates',
+    array('class' => 'btn btn-default')
+);
+
+echo Display::url(
+    get_lang('DeleteAllCertificates'),
+    $url.'&action=delete_all_certificates',
+    array('class' => 'btn btn-default')
+);
 
 $hideCertificateExport = api_get_setting('hide_certificate_export_link');
 if (count($certificate_list) > 0 && $hideCertificateExport !== 'true') {
-    $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 btn-default'));
+    echo Display::url(
+        get_lang('ExportAllCertificatesToPDF'),
+        $url.'&action=export_all_certificates',
+        array('class' => 'btn btn-default')
+    );
+
+    echo Display::url(
+        get_lang('SendCertificateNotifications'),
+        $url.'&action=show_notification_form',
+        array('class' => 'btn btn-default')
+    );
 }
+
 echo '</div>';
 
 echo $filterForm;
@@ -210,16 +319,23 @@ if (count($certificate_list) == 0) {
         echo '<tr><td>
             <table class="data_table">';
 
-        $list_certificate = GradebookUtils::get_list_gradebook_certificates_by_user_id($value['user_id'], $cat_id);
-        foreach ($list_certificate as $value_certificate) {
+        $list = GradebookUtils::get_list_gradebook_certificates_by_user_id(
+            $value['user_id'],
+            $cat_id
+        );
+        foreach ($list as $valueCertificate) {
             echo '<tr>';
-            echo '<td width="50%">'.get_lang('Score').' : '.$value_certificate['score_certificate'].'</td>';
-            echo '<td width="30%">'.get_lang('Date').' : '.api_convert_and_format_date($value_certificate['created_at']).'</td>';
+            echo '<td width="50%">'.get_lang('Score').' : '.$valueCertificate['score_certificate'].'</td>';
+            echo '<td width="30%">'.get_lang('Date').' : '.api_convert_and_format_date($valueCertificate['created_at']).'</td>';
             echo '<td width="20%">';
-            $url = api_get_path(WEB_PATH).'certificates/index.php?id='.$value_certificate['id'];
-            $certificates = Display::url(get_lang('Certificate'), $url, array('target'=>'_blank', 'class' => 'btn btn-default'));
+            $url = api_get_path(WEB_PATH).'certificates/index.php?id='.$valueCertificate['id'];
+            $certificates = Display::url(
+                get_lang('Certificate'),
+                $url,
+                array('target' => '_blank', 'class' => 'btn btn-default')
+            );
             echo $certificates;
-            echo '<a onclick="return confirmation();" href="gradebook_display_certificate.php?sec_token='.$token.'&'.api_get_cidreq().'&action=delete&cat_id='.$cat_id.'&certificate_id='.$value_certificate['id'].'">
+            echo '<a onclick="return confirmation();" href="gradebook_display_certificate.php?sec_token='.$token.'&'.api_get_cidreq().'&action=delete&cat_id='.$cat_id.'&certificate_id='.$valueCertificate['id'].'">
                     '.Display::return_icon('delete.png', get_lang('Delete')).'
                   </a>';
             echo '</td></tr>';

+ 1 - 2
main/gradebook/lib/be/category.class.php

@@ -2118,7 +2118,6 @@ class Category implements GradebookItem
 
         // A student always sees only the teacher's repartition
         $scoretotal_display = $scoredisplay->display_score($scoretotal, SCORE_DIV_PERCENT);
-
         $userFinishedCourse = self::userFinishedCourse(
             $user_id,
             $cats_course[0],
@@ -2132,7 +2131,7 @@ class Category implements GradebookItem
             return false;
         }
 
-        $skillToolEnabled = api_get_setting('allow_skills_tool') == 'true';
+        $skillToolEnabled = Skill::hasAccessToUserSkill(api_get_user_id(), $user_id);
         $userHasSkills = false;
 
         if ($skillToolEnabled) {

+ 1 - 2
main/gradebook/lib/fe/catform.class.php

@@ -232,7 +232,7 @@ class CatForm extends FormValidator
         $skillsDefaults = [];
 
         if (api_is_platform_admin() || api_is_drh()) {
-            if (api_get_setting('allow_skills_tool') == 'true') {
+            if (Skill::isToolAvailable()) {
                 $skillSelect = $this->addElement(
                     'select_ajax',
                     'skills',
@@ -250,7 +250,6 @@ class CatForm extends FormValidator
 
                 // The magic should be here
                 $skills = $this->category_object->get_skills();
-
                 foreach ($skills as $skill) {
                     $skillsDefaults[] = $skill['id'];
 

+ 2 - 4
main/inc/ajax/skill.ajax.php

@@ -8,12 +8,10 @@ require_once __DIR__.'/../global.inc.php';
 
 $action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
 
-if (api_get_setting('allow_skills_tool') != 'true') {
-    exit;
-}
-
 api_block_anonymous_users();
 
+Skill::isAllow();
+
 $skill = new Skill();
 $gradebook = new Gradebook();
 $skill_gradebook = new SkillRelGradebook();

+ 2 - 2
main/inc/introductionSection.inc.php

@@ -185,7 +185,7 @@ if ($tool == TOOL_COURSE_HOMEPAGE && !isset($_GET['intro_cmdEdit'])) {
         $thematic_advance_info = $thematic->get_thematic_advance_list($last_done_advance);
         $subTitle1 = get_lang('CurrentTopic');
         $class1 = ' current';
-    } else if ($displayMode == '2') {
+    } elseif ($displayMode == '2') {
         // Show only the two next course progress steps
         // $information_title = get_lang('InfoAboutNextAdvanceNotDone');
         $last_done_advance = $thematic->get_next_thematic_advance_not_done();
@@ -193,7 +193,7 @@ if ($tool == TOOL_COURSE_HOMEPAGE && !isset($_GET['intro_cmdEdit'])) {
         $thematic_advance_info = $thematic->get_thematic_advance_list($last_done_advance);
         $thematic_advance_info2 = $thematic->get_thematic_advance_list($next_advance_not_done);
         $subTitle1 = $subTitle2 = get_lang('NextTopic');
-    } else if ($displayMode == '3') {
+    } elseif ($displayMode == '3') {
         // Show the current and next course progress steps
         // $information_title = get_lang('InfoAboutLastDoneAdvanceAndNextAdvanceNotDone');
         $last_done_advance = $thematic->get_last_done_thematic_advance();

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

@@ -1548,7 +1548,7 @@ class CourseChatUtils
 
         if ($this->groupId && !$friendId) {
             $filename_chat = 'messages-'.$date_now.'_gid-'.$this->groupId.'.log.html';
-        } else if ($this->sessionId && !$friendId) {
+        } elseif ($this->sessionId && !$friendId) {
             $filename_chat = 'messages-'.$date_now.'_sid-'.$this->sessionId.'.log.html';
         } elseif ($friendId) {
             if ($this->userId < $friendId) {
@@ -1593,7 +1593,7 @@ class CourseChatUtils
         $basename_chat = 'messages-'.$date_now;
         if ($this->groupId && !$friendId) {
             $basename_chat = 'messages-'.$date_now.'_gid-'.$this->groupId;
-        } else if ($this->sessionId && !$friendId) {
+        } elseif ($this->sessionId && !$friendId) {
             $basename_chat = 'messages-'.$date_now.'_sid-'.$this->sessionId;
         } elseif ($friendId) {
             if ($this->userId < $friendId) {

+ 3 - 1
main/inc/lib/ScheduledAnnouncement.php

@@ -287,10 +287,12 @@ class ScheduledAnnouncement extends Model
                     self::update(['id' => $result['id'], 'sent' => 1]);
 
                     $subject = $result['subject'];
-                    $message = $result['message'];
 
                     if ($users) {
                         foreach ($users as $user) {
+                            // Take original message
+                            $message = $result['message'];
+
                             $userInfo = api_get_user_info($user['user_id']);
                             $courseList = SessionManager::getCoursesInSession($sessionId);
                             $courseInfo = [];

+ 1 - 0
main/inc/lib/SmsPlugin.php

@@ -52,6 +52,7 @@ class SmsPlugin extends Plugin
     const BEEN_INVITED_COMPLETE_SURVEY_COURSE = 40;
     const REMINDER_ASSIGNMENT_COURSE_DUE = 41;
     const USER_DETAILS_MODIFIED = 42;
+    const CERTIFICATE_NOTIFICATION = 43;
 
     public $isCoursePlugin = true;
     public $isMailPlugin = true;

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

@@ -1051,7 +1051,7 @@ class Attendance
 
         if ($faults_porcent > 25) {
             $color_bar = '#f28989';
-        } else if ($faults_porcent > 10) {
+        } elseif ($faults_porcent > 10) {
             $color_bar = '#F90';
         }
         $results['color_bar'] = $color_bar;

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

@@ -620,7 +620,7 @@ class Auth
                         $all_course_information['real_id'],
                         $send_to_tutor_also = false
                     );
-                } else if ($send == 2) {
+                } elseif ($send == 2) {
                     CourseManager::email_to_tutor(
                         $user_id,
                         $all_course_information['real_id'],

+ 6 - 9
main/inc/lib/course.lib.php

@@ -4287,18 +4287,15 @@ class CourseManager
                 'session_category_id' => $session_category_id
             );
 
-            if (api_get_setting('allow_skills_tool') === 'true') {
-                $entityManager = Database::getManager();
-                $objUser = $entityManager->find('ChamiloUserBundle:User', $user_id);
-                $objCourse = $entityManager->find('ChamiloCoreBundle:Course', $course['real_id']);
-                $objSession = $entityManager->find('ChamiloCoreBundle:Session', $session_id);
+            if (Skill::isAllow($user_id, false)) {
+                $em = Database::getManager();
+                $objUser = $em->find('ChamiloUserBundle:User', $user_id);
+                $objCourse = $em->find('ChamiloCoreBundle:Course', $course['real_id']);
+                $objSession = $em->find('ChamiloCoreBundle:Session', $session_id);
 
-                $skill = $entityManager
-                    ->getRepository('ChamiloCoreBundle:Skill')
-                    ->getLastByUser($objUser, $objCourse, $objSession);
+                $skill = $em->getRepository('ChamiloCoreBundle:Skill')->getLastByUser($objUser, $objCourse, $objSession);
 
                 $output['skill'] = null;
-
                 if ($skill) {
                     $output['skill']['name'] = $skill->getName();
                     $output['skill']['icon'] = $skill->getIcon();

+ 8 - 2
main/inc/lib/course_home.lib.php

@@ -1295,7 +1295,7 @@ class CourseHome
                 $class = 'text';
                 $marginLeft = 170;
                 $item = $navigation_item['name'];
-            } else if (api_get_setting('show_navigation_menu') == 'icons') {
+            } elseif (api_get_setting('show_navigation_menu') == 'icons') {
                 $class = 'icons';
                 $marginLeft = 25;
                 $item = Display::return_icon(
@@ -1306,7 +1306,13 @@ class CourseHome
                 );
             } else {
                 $class = 'icons-text';
-                $item = $navigation_item['name'].Display::return_icon(substr($navigation_item['image'], 0, -3)."png", $navigation_item['name'], array('class'=>'tool-img'), ICON_SIZE_SMALL);
+                $item = $navigation_item['name'].
+                    Display::return_icon(
+                        substr($navigation_item['image'], 0, -3)."png",
+                        $navigation_item['name'],
+                        array('class' => 'tool-img'),
+                        ICON_SIZE_SMALL
+                    );
             }
 
             if (stristr($url_item['path'], $url_current['path'])) {

+ 47 - 21
main/inc/lib/document.lib.php

@@ -3448,7 +3448,6 @@ class DocumentManager
         $userInfo = api_get_user_info();
 
         $user_in_course = false;
-
         if (api_is_platform_admin()) {
             $user_in_course = true;
         }
@@ -3518,7 +3517,12 @@ class DocumentManager
 
         $parentData = [];
         if ($folderId !== false) {
-            $parentData = self::get_document_data_by_id($folderId, $course_info['code'], false, $session_id);
+            $parentData = self::get_document_data_by_id(
+                $folderId,
+                $course_info['code'],
+                false,
+                $session_id
+            );
             if (!empty($parentData)) {
                 $cleanedPath = $parentData['path'];
                 $num = substr_count($cleanedPath, '/');
@@ -3535,8 +3539,7 @@ class DocumentManager
                     $notLikeCondition
                 ";
             } else {
-                $folderCondition = " AND
-                docs.filetype = 'file' ";
+                $folderCondition = " AND docs.filetype = 'file' ";
             }
         }
 
@@ -3546,7 +3549,8 @@ class DocumentManager
         }
 
         $sql = "SELECT DISTINCT last.visibility, docs.*
-                FROM $tbl_item_prop AS last INNER JOIN $tbl_doc AS docs
+                FROM $tbl_item_prop AS last 
+                INNER JOIN $tbl_doc AS docs
                 ON (docs.id = last.ref AND docs.c_id = last.c_id)
                 WHERE
                     docs.path NOT LIKE '%_DELETED_%' AND
@@ -3588,7 +3592,6 @@ class DocumentManager
 
         // If you want to debug it, I advise you to do "echo" on the eval statements.
         $newResources = array();
-
         if (!empty($resources) && $user_in_course) {
             foreach ($resources as $resource) {
                 $is_visible = self::is_visible_by_id(
@@ -3996,9 +3999,19 @@ class DocumentManager
         $user_id,
         $groupId = 0
     ) {
-        $document_data = self::get_document_data_by_id($doc_id, $course_code, null, $session_id);
+        $document_data = self::get_document_data_by_id(
+            $doc_id,
+            $course_code,
+            null,
+            $session_id
+        );
         if ($session_id != 0 && !$document_data) {
-            $document_data = self::get_document_data_by_id($doc_id, $course_code, null, 0);
+            $document_data = self::get_document_data_by_id(
+                $doc_id,
+                $course_code,
+                null,
+                0
+            );
         }
 
         if (!empty($document_data)) {
@@ -4080,7 +4093,8 @@ class DocumentManager
             $doc_mime = mime_content_type($doc_path);
             $allowed_mime_types = self::file_get_mime_type(true);
 
-            // mime_content_type does not detect correctly some formats that are going to be supported for index, so an extensions array is used for the moment
+            // mime_content_type does not detect correctly some formats that
+            // are going to be supported for index, so an extensions array is used for the moment
             if (empty($doc_mime)) {
                 $allowed_extensions = array(
                     'doc',
@@ -4187,7 +4201,13 @@ class DocumentManager
                                     $ic_slide->addTerm($sterm, $specific_field['code']);
                                     // updated the last param here from $value to $sterm without being sure - see commit15464
                                     if (!$simulation) {
-                                        add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm);
+                                        add_specific_field_value(
+                                            $specific_field['id'],
+                                            $course_code,
+                                            TOOL_DOCUMENT,
+                                            $docid,
+                                            $sterm
+                                        );
                                     }
                                 }
                             }
@@ -4225,7 +4245,13 @@ class DocumentManager
                             foreach ($sterms as $sterm) {
                                 if (!$simulation) {
                                     $ic_slide->addTerm(trim($sterm), $specific_field['code']);
-                                    add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm);
+                                    add_specific_field_value(
+                                        $specific_field['id'],
+                                        $course_code,
+                                        TOOL_DOCUMENT,
+                                        $docid,
+                                        $sterm
+                                    );
                                 }
                             }
                         }
@@ -4716,7 +4742,6 @@ class DocumentManager
                 );
 
                 if (!empty($documentId)) {
-
                     if ($deleteWavFile) {
                         $coursePath = $courseInfo['directory'].'/document';
                         $documentPath = api_get_path(SYS_COURSE_PATH).$coursePath;
@@ -4859,8 +4884,11 @@ class DocumentManager
      * @param bool $fromBaseCourse
      * @param int $sessionId
      */
-    public static function generateDefaultCertificate($courseData, $fromBaseCourse = false, $sessionId = 0)
-    {
+    public static function generateDefaultCertificate(
+        $courseData,
+        $fromBaseCourse = false,
+        $sessionId = 0
+    ) {
         if (empty($courseData)) {
             return false;
         }
@@ -4963,7 +4991,6 @@ class DocumentManager
     {
         $documentId = intval($documentId);
         $newName = Database::escape_string($newName);
-
         $docuentTable = Database::get_course_table(TABLE_DOCUMENT);
 
         $values = array(
@@ -5223,11 +5250,10 @@ class DocumentManager
      * Builds the form that enables the user to
      * select a directory to browse/upload in
      *
-     * @param array 	An array containing the folders we want to be able to select
-     * @param string	The current folder (path inside of the "document" directory, including the prefix "/")
-     * @param string	Group directory, if empty, prevents documents to be uploaded (because group documents cannot be uploaded in root)
-     * @param	boolean	Whether to change the renderer (this will add a template <span> to the QuickForm object displaying the form)
-
+     * @param array    An array containing the folders we want to be able to select
+     * @param string    The current folder (path inside of the "document" directory, including the prefix "/")
+     * @param string    Group directory, if empty, prevents documents to be uploaded (because group documents cannot be uploaded in root)
+     * @param boolean    Whether to change the renderer (this will add a template <span> to the QuickForm object displaying the form)
      * @return string html form
      */
     public static function build_directory_selector(
@@ -5441,7 +5467,7 @@ class DocumentManager
                     api_is_platform_admin() ||
                     api_get_setting('students_download_folders') == 'true'
                 ) {
-                    //filter: when I am into a shared folder, I can only show "my shared folder" for donwload
+                    // filter: when I am into a shared folder, I can only show "my shared folder" for donwload
                     if (self::is_shared_folder($curdirpath, $current_session_id)) {
                         if (preg_match('/shared_folder\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) ||
                             preg_match('/shared_folder_session_'.$current_session_id.'\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) ||

+ 36 - 0
main/inc/lib/glossary.lib.php

@@ -396,6 +396,11 @@ class GlossaryManager
                 Display::return_icon('view_text.png', get_lang('TableView'), '', ICON_SIZE_MEDIUM).'</a>';
         }
 
+        $actionsLeft .= Display::url(
+            Display::return_icon('export_to_documents.png', get_lang('ExportToDocArea'), [], ICON_SIZE_MEDIUM),
+            api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['action' => 'export_documents'])
+        );
+
         /* BUILD SEARCH FORM */
         $form = new FormValidator(
             'search',
@@ -711,4 +716,35 @@ class GlossaryManager
         $pdf = new PDF();
         $pdf->content_to_pdf($html, '', get_lang('Glossary').'_'.$courseCode, $courseCode);
     }
+
+    /**
+     * Generate a PDF with all glossary terms and move file to documents
+     */
+    public static function movePdfToDocuments()
+    {
+        $sessionId = api_get_session_id();
+        $courseId = api_get_course_int_id();
+        $data = self::get_glossary_data(
+            0,
+            self::get_number_glossary_terms($sessionId),
+            0,
+            'ASC'
+        );
+        $template = new Template('', false, false, false, true, false, false);
+        $layout = $template->get_template('glossary/export_pdf.tpl');
+        $template->assign('items', $data);
+        $fileName = get_lang('Glossary').'-'.api_get_local_time();
+        $signatures = ['Drh', 'Teacher', 'Date'];
+
+        $pdf = new PDF(
+            'A4-P',
+            'P',
+            [
+                'filename' => $fileName,
+                'pdf_title' => $fileName,
+                'add_signatures' => $signatures
+            ]
+        );
+        $pdf->exportFromHtmlToDocumentsArea($template->fetch($layout), $fileName, $courseId);
+    }
 }

+ 13 - 3
main/inc/lib/message.lib.php

@@ -311,7 +311,12 @@ class MessageManager
 
         // Validating fields
         if (empty($subject) && empty($group_id)) {
-            Display::addFlash(Display::return_message(get_lang('YouShouldWriteASubject'), 'warning'));
+            Display::addFlash(
+                Display::return_message(
+                    get_lang('YouShouldWriteASubject'),
+                    'warning'
+                )
+            );
             return false;
         } elseif ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) {
             $warning = sprintf(
@@ -328,7 +333,6 @@ class MessageManager
 
         //Just in case we replace the and \n and \n\r while saving in the DB
         //$content = str_replace(array("\n", "\n\r"), '<br />', $content);
-
         $now = api_get_utc_datetime();
         if (!empty($receiver_user_id) || !empty($group_id)) {
             // message for user friend
@@ -435,7 +439,13 @@ class MessageManager
                 $group_info['topic_id'] = $topic_id;
                 $group_info['msg_id'] = $inbox_last_id;
 
-                $user_list = $usergroup->get_users_by_group($group_id, false, array(), 0, 1000);
+                $user_list = $usergroup->get_users_by_group(
+                    $group_id,
+                    false,
+                    array(),
+                    0,
+                    1000
+                );
 
                 // Adding more sense to the message group
                 $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);

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

@@ -1035,7 +1035,7 @@ class MySpace
             );
             if ($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned
                 $last_login_date = $last_login_date_tmp;
-            } else if ($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition. To be cleaned.
+            } elseif ($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition. To be cleaned.
                 // Find the max and assign it to first_login_date
                 if (strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
                     $last_login_date = $last_login_date_tmp;

+ 6 - 7
main/inc/lib/notification.lib.php

@@ -212,15 +212,15 @@ class Notification extends Model
 
     /**
      * Save message notification
-     * @param int	    $type message type
+     * @param int $type message type
      * NOTIFICATION_TYPE_MESSAGE,
      * NOTIFICATION_TYPE_INVITATION,
      * NOTIFICATION_TYPE_GROUP
-     * @param array	    $userList recipients: user list of ids
-     * @param string	$title
-     * @param string	$content
-     * @param array	    $senderInfo result of api_get_user_info() or GroupPortalManager:get_group_data()
-     * @param array	    $attachments
+     * @param array $userList recipients: user list of ids
+     * @param string $title
+     * @param string $content
+     * @param array $senderInfo result of api_get_user_info() or GroupPortalManager:get_group_data()
+     * @param array $attachments
      *
      */
     public function save_notification(
@@ -234,7 +234,6 @@ class Notification extends Model
         $this->type = intval($type);
         $content = $this->formatContent($content, $senderInfo);
         $titleToNotification = $this->formatTitle($title, $senderInfo);
-
         $settingToCheck = '';
         $avoid_my_self = false;
 

+ 74 - 26
main/inc/lib/sessionmanager.lib.php

@@ -574,6 +574,13 @@ class SessionManager
 
             foreach ($sessions as $session) {
                 $session_id = $session['id'];
+                if ($showCountUsers) {
+                    $session['users'] = SessionManager::get_users_by_session(
+                        $session['id'],
+                        null,
+                        true
+                    );
+                }
                  $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
                 if (api_is_drh()) {
                     $url = api_get_path(WEB_CODE_PATH)."session/about.php?session_id=".$session['id'];
@@ -3865,8 +3872,12 @@ class SessionManager
      * @param int $urlId
      * @return array|int A list with an user list. If $getCount is true then return a the count of registers
      */
-    public static function get_users_by_session($id, $status = null, $getCount = false, $urlId = 0)
-    {
+    public static function get_users_by_session(
+        $id,
+        $status = null,
+        $getCount = false,
+        $urlId = 0
+    ) {
         if (empty($id)) {
             return array();
         }
@@ -3969,7 +3980,12 @@ class SessionManager
     public static function get_sessions_by_coach($user_id)
     {
         $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
-        return Database::select('*', $session_table, array('where' => array('id_coach = ?' => $user_id)));
+
+        return Database::select(
+            '*',
+            $session_table,
+            array('where' => array('id_coach = ?' => $user_id))
+        );
     }
 
     /**
@@ -3980,10 +3996,10 @@ class SessionManager
      */
     public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
     {
-        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
         $sql = "SELECT session_rcru.status
-                FROM $tbl_session_rel_course_rel_user session_rcru 
+                FROM $table session_rcru 
                 INNER JOIN $tbl_user user
                 ON (session_rcru.user_id = user.user_id)
                 WHERE                    
@@ -4028,8 +4044,13 @@ class SessionManager
      */
     public static function get_all_sessions_by_promotion($id)
     {
-        $t = Database::get_main_table(TABLE_MAIN_SESSION);
-        return Database::select('*', $t, array('where' => array('promotion_id = ?' => $id)));
+        $table = Database::get_main_table(TABLE_MAIN_SESSION);
+
+        return Database::select(
+            '*',
+            $table,
+            array('where' => array('promotion_id = ?' => $id))
+        );
     }
 
     /**
@@ -4038,16 +4059,20 @@ class SessionManager
      */
     public static function subscribe_sessions_to_promotion($promotion_id, $list)
     {
-        $t = Database::get_main_table(TABLE_MAIN_SESSION);
+        $table = Database::get_main_table(TABLE_MAIN_SESSION);
         $params = array();
         $params['promotion_id'] = 0;
-        Database::update($t, $params, array('promotion_id = ?' => $promotion_id));
+        Database::update(
+            $table,
+            $params,
+            array('promotion_id = ?' => $promotion_id)
+        );
 
         $params['promotion_id'] = $promotion_id;
         if (!empty($list)) {
             foreach ($list as $session_id) {
                 $session_id = intval($session_id);
-                Database::update($t, $params, array('id = ?' => $session_id));
+                Database::update($table, $params, ['id = ?' => $session_id]);
             }
         }
     }
@@ -4272,9 +4297,7 @@ class SessionManager
      */
     public static function protectSession($id, $checkSession = true)
     {
-        // api_protect_admin_script(true);
         if (self::allowToManageSessions()) {
-
             if (api_is_platform_admin() && self::allowed($id)) {
                 return true;
             }
@@ -4424,8 +4447,11 @@ class SessionManager
      *
      * @return array
      */
-    public static function get_sessions_by_user($user_id, $ignoreVisibilityForAdmins = false, $ignoreTimeLimit = false)
-    {
+    public static function get_sessions_by_user(
+        $user_id,
+        $ignoreVisibilityForAdmins = false,
+        $ignoreTimeLimit = false
+    ) {
         $sessionCategories = UserManager::get_sessions_by_category(
             $user_id,
             false,
@@ -4464,6 +4490,8 @@ class SessionManager
      * @param bool $deleteUsersNotInList
      * @param bool $updateCourseCoaches
      * @param bool $sessionWithCoursesModifier
+     * @param bool $addOriginalCourseTeachersAsCourseSessionCoaches
+     * @param bool $removeAllTeachersFromCourse
      * @param int $showDescription
      * @param array $teacherBackupList
      * @param array $groupBackup
@@ -4944,11 +4972,9 @@ class SessionManager
                         }
 
                         $course_counter++;
-
                         $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
-                        $course_users   = isset($courseArray[2]) ? $courseArray[2] : null;
-
-                        $course_users   = explode(',', $course_users);
+                        $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
+                        $course_users = explode(',', $course_users);
                         $course_coaches = explode(',', $course_coaches);
 
                         // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
@@ -5740,10 +5766,25 @@ class SessionManager
                         foreach ($sessionsDestination as $sessionDestinationId) {
                             $sessionDestinationInfo = self::fetch($sessionDestinationId);
                             $messages[] = Display::return_message(
-                                sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
+                                sprintf(
+                                    get_lang(
+                                        'AddingStudentsFromSessionXToSessionY'
+                                    ),
+                                    $sessionInfo['name'],
+                                    $sessionDestinationInfo['name']
+                                ),
+                                'info',
+                                false
                             );
                             if ($sessionId == $sessionDestinationId) {
-                                $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
+                                $messages[] = Display::return_message(
+                                    sprintf(
+                                        get_lang('SessionXSkipped'),
+                                        $sessionDestinationId
+                                    ),
+                                    'warning',
+                                    false
+                                );
                                 continue;
                             }
                             $messages[] = Display::return_message(get_lang('StudentList').'<br />'.$userToString, 'info', false);
@@ -5934,9 +5975,12 @@ class SessionManager
                 $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
                 // Select the teachers.
-                $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
-                        INNER JOIN $sessionCourse src ON c.id = src.c_id
-                        INNER JOIN $courseUser cu ON (cu.c_id = c.id)
+                $sql = "SELECT DISTINCT(cu.user_id) 
+                        FROM $course c
+                        INNER JOIN $sessionCourse src 
+                        ON c.id = src.c_id
+                        INNER JOIN $courseUser cu 
+                        ON (cu.c_id = c.id)
 		                WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
                 $result = Database::query($sql);
                 while ($row = Database::fetch_array($result, 'ASSOC')) {
@@ -6096,7 +6140,6 @@ class SessionManager
      */
     public static function removeCourseDescription($sessionId, $courseId)
     {
-
     }
 
     /**
@@ -6105,8 +6148,11 @@ class SessionManager
      * @param bool $removeOldRelationShips
      * @return string
      */
-    public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
-    {
+    public static function subscribeDrhToSessionList(
+        $userSessionList,
+        $sendEmail,
+        $removeOldRelationShips
+    ) {
         if (!empty($userSessionList)) {
             foreach ($userSessionList as $userId => $data) {
                 $sessionList = array();
@@ -7229,6 +7275,8 @@ class SessionManager
     /**
      * Returns a human readable string
      * @params array $sessionInfo An array with all the session dates
+     * @param bool $showTime
+     *
      * @return string
      */
     public static function parseSessionDates($sessionInfo, $showTime = false)

+ 125 - 16
main/inc/lib/skill.lib.php

@@ -2,6 +2,7 @@
 /* For licensing terms, see /license.txt */
 
 use Chamilo\UserBundle\Entity\User;
+use Chamilo\UserBundle\Entity\Repository\UserRepository;
 
 /**
  * Class SkillProfile
@@ -135,8 +136,8 @@ class SkillRelProfile extends Model
     /**
      * This function is for getting profile info from profile_id.
      * @param int $profileId
+     * @return array
      */
-
     public function getProfileInfo($profileId)
     {
         $sql = "SELECT * FROM $this->table p
@@ -338,7 +339,14 @@ class SkillRelGradebook extends Model
     {
         $result = $this->find(
             'all',
-            array('where' => array('gradebook_id = ? AND skill_id = ?' => array($gradebook_id, $skill_id)))
+            array(
+                'where' => array(
+                    'gradebook_id = ? AND skill_id = ?' => array(
+                        $gradebook_id,
+                        $skill_id
+                    )
+                )
+            )
         );
         if (!empty($result)) {
             return true;
@@ -357,7 +365,14 @@ class SkillRelGradebook extends Model
         $result = Database::select(
             '*',
             $this->table,
-            array('where' => array('skill_id = ? AND gradebook_id = ? ' => array($skill_id, $gradebook_id))),
+            array(
+                'where' => array(
+                    'skill_id = ? AND gradebook_id = ? ' => array(
+                        $skill_id,
+                        $gradebook_id
+                    )
+                )
+            ),
             'first'
         );
         return $result;
@@ -933,6 +948,8 @@ class Skill extends Model
      *
      * @param int $userId User's id
      * @param bool $get_skill_data
+     *
+     * @return array
      */
     public function get_user_skills($user_id, $get_skill_data = false)
     {
@@ -1043,8 +1060,7 @@ class Skill extends Model
 
                 // If a short code was defined, send the short code to replace
                 // skill name (to shorten the text in the wheel)
-                if (
-                    !empty($skill['short_code']) &&
+                if (!empty($skill['short_code']) &&
                     api_get_setting('show_full_skill_name_on_skill_wheel') === 'false'
                 ) {
                     $skill['data']['short_code'] = $skill['short_code'];
@@ -1243,8 +1259,13 @@ class Skill extends Model
      * @param $where_condition
      * @return array
      */
-    public function get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition)
-    {
+    public function get_user_list_skill_ranking(
+        $start,
+        $limit,
+        $sidx,
+        $sord,
+        $where_condition
+    ) {
         $start = intval($start);
         $limit = intval($limit);
         /*  ORDER BY $sidx $sord */
@@ -1270,14 +1291,14 @@ class Skill extends Model
     public function get_user_list_skill_ranking_count()
     {
         $sql = "SELECT count(*) FROM (
-                        SELECT count(distinct 1)
-                        FROM {$this->table} s
-                        INNER JOIN {$this->table_skill_rel_user} su
-                        ON (s.id = su.skill_id)
-                        INNER JOIN {$this->table_user} u
-                        ON u.user_id = su.user_id
-                        GROUP BY username
-                     ) as T1";
+                    SELECT count(distinct 1)
+                    FROM {$this->table} s
+                    INNER JOIN {$this->table_skill_rel_user} su
+                    ON (s.id = su.skill_id)
+                    INNER JOIN {$this->table_user} u
+                    ON u.user_id = su.user_id
+                    GROUP BY username
+                 ) as T1";
         $result = Database::query($sql);
         if (Database::num_rows($result)) {
             $result = Database::fetch_row($result);
@@ -1531,6 +1552,7 @@ class Skill extends Model
         }
 
         $entityManager = Database::getManager();
+        /** @var UserRepository $userRepo */
         $userRepo = $entityManager->getRepository('ChamiloUserBundle:User');
         $fromUserStatus = $fromUser->getStatus();
 
@@ -1564,10 +1586,97 @@ class Skill extends Model
                 }
                 break;
             case DRH:
-                return UserManager::is_user_followed_by_drh($toUser->getId(), $fromUser->getId());
+                return UserManager::is_user_followed_by_drh(
+                    $toUser->getId(),
+                    $fromUser->getId()
+                );
         }
 
         return false;
     }
 
+    /**
+     * If $studentId is set then check if current user has the right to see
+     * the page.
+     * @param int $studentId check if current user has access to see $studentId
+     * @param bool $blockPage raise a api_not_allowed()
+     *
+     * @return bool
+     */
+    public static function isAllow($studentId = 0, $blockPage = true)
+    {
+        if (self::isToolAvailable()) {
+            if (api_is_platform_admin()) {
+                return true;
+            }
+
+            if (!empty($studentId)) {
+                $currentUserId = api_get_user_id();
+                if ((int) $currentUserId === (int) $studentId) {
+                    return true;
+                }
+
+                $haveAccess = self::hasAccessToUserSkill(
+                    $currentUserId,
+                    $studentId
+                );
+
+                if ($haveAccess) {
+                    return true;
+                }
+            }
+        }
+
+        if ($blockPage) {
+            api_not_allowed(true);
+        }
+
+        return false;
+    }
+
+    /**
+     * @return bool
+     */
+    public static function isToolAvailable()
+    {
+        $allowTool = api_get_setting('allow_skills_tool');
+
+        if ($allowTool == 'true') {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * @param $currentUserId
+     * @param $studentId
+     * @return bool
+     */
+    public static function hasAccessToUserSkill($currentUserId, $studentId)
+    {
+        if (self::isToolAvailable()) {
+            if (api_is_platform_admin()) {
+                return true;
+            }
+            $allow = api_get_configuration_value('allow_private_skills');
+            if ($allow === true) {
+                if (api_is_teacher()) {
+                    return UserManager::isTeacherOfStudent(
+                        $currentUserId,
+                        $studentId
+                    );
+                }
+
+                if (api_is_drh()) {
+                    return UserManager::is_user_followed_by_drh(
+                        $studentId,
+                        $currentUserId
+                    );
+                }
+            }
+        }
+
+        return false;
+    }
 }

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

@@ -2055,8 +2055,8 @@ class SocialManager extends UserManager
      */
     public static function getSkillBlock($userId)
     {
-        if (api_get_setting('allow_skills_tool') !== 'true') {
-            return null;
+        if (Skill::isAllow($userId, false) === false) {
+            return '';
         }
 
         $skill = new Skill();

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

@@ -6342,20 +6342,19 @@ class Tracking
      */
     public static function displayUserSkills($userId, $courseId = 0, $sessionId = 0)
     {
+        if (Skill::isAllow($userId, false) === false) {
+            return '';
+        }
+
         $userId = intval($userId);
         $courseId = intval($courseId);
         $sessionId = intval($sessionId);
 
-        if (api_get_setting('allow_skills_tool') !== 'true') {
-            return '';
-        }
-
         $filter = ['user' => $userId];
         $filter['course'] = $courseId ?: null;
         $filter['session'] = $sessionId ?: null;
 
         $em = Database::getManager();
-
         $skillsRelUser = $em->getRepository('ChamiloCoreBundle:SkillRelUser')->findBy($filter);
 
         $html = '
@@ -7093,7 +7092,7 @@ class TrackingCourseLog
         $direction,
         $includeInvitedUsers = false
     ) {
-        global $user_ids, $course_code, $export_csv, $is_western_name_order, $csv_content, $session_id;
+        global $user_ids, $course_code, $export_csv, $csv_content, $session_id;
 
         $course_code = Database::escape_string($course_code);
         $tbl_user = Database::get_main_table(TABLE_MAIN_USER);

+ 88 - 28
main/inc/lib/usermanager.lib.php

@@ -4571,8 +4571,7 @@ class UserManager
         $relationType,
         $deleteUsersBeforeInsert = false,
         $deleteOtherAssignedUsers = true
-    )
-    {
+    ) {
         $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
@@ -4583,26 +4582,30 @@ class UserManager
         if ($deleteOtherAssignedUsers) {
             if (api_get_multiple_access_url()) {
                 // Deleting assigned users to hrm_id
-                $sql = "SELECT s.user_id FROM $userRelUserTable s 
-                    INNER JOIN $userRelAccessUrlTable a ON (a.user_id = s.user_id) 
-                    WHERE 
-                        friend_user_id = $userId AND 
-                        relation_type = $relationType AND 
-                        access_url_id = ".api_get_current_access_url_id();
+                $sql = "SELECT s.user_id 
+                        FROM $userRelUserTable s 
+                        INNER JOIN $userRelAccessUrlTable a
+                        ON (a.user_id = s.user_id) 
+                        WHERE 
+                            friend_user_id = $userId AND 
+                            relation_type = $relationType AND 
+                            access_url_id = ".api_get_current_access_url_id();
             } else {
-                $sql = "SELECT user_id FROM $userRelUserTable 
-                    WHERE friend_user_id = $userId 
-                    AND relation_type = $relationType";
+                $sql = "SELECT user_id 
+                        FROM $userRelUserTable 
+                        WHERE 
+                            friend_user_id = $userId AND 
+                            relation_type = $relationType";
             }
             $result = Database::query($sql);
 
             if (Database::num_rows($result) > 0) {
                 while ($row = Database::fetch_array($result)) {
                     $sql = "DELETE FROM $userRelUserTable 
-                        WHERE 
-                          user_id = {$row['user_id']} AND 
-                          friend_user_id = $userId AND 
-                          relation_type = $relationType";
+                            WHERE
+                                user_id = {$row['user_id']} AND 
+                                friend_user_id = $userId AND 
+                                relation_type = $relationType";
                     Database::query($sql);
                 }
             }
@@ -4620,7 +4623,6 @@ class UserManager
         if (is_array($subscribedUsersId)) {
             foreach ($subscribedUsersId as $subscribedUserId) {
                 $subscribedUserId = intval($subscribedUserId);
-
                 $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
                         VALUES ($subscribedUserId, $userId, $relationType)";
 
@@ -4757,9 +4759,14 @@ class UserManager
             $cat = Category::load($category_id);
             $displayscore = ScoreDisplay::instance();
             if (isset($cat) && $displayscore->is_custom()) {
-                $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()), SCORE_DIV_PERCENT_WITH_CUSTOM);
+                $grade = $displayscore->display_score(
+                    array($score, $cat[0]->get_weight()),
+                    SCORE_DIV_PERCENT_WITH_CUSTOM
+                );
             } else {
-                $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()));
+                $grade = $displayscore->display_score(
+                    array($score, $cat[0]->get_weight())
+                );
             }
             $row['grade'] = $grade;
 
@@ -4860,13 +4867,17 @@ class UserManager
 
     /**
      *
-     * @param int   student id
-     * @param int   years
-     * @param bool  show warning_message
-     * @param bool  return_timestamp
+     * @param int $student_id
+     * @param int $years
+     * @param bool $warning_message  show warning_message
+     * @param bool $return_timestamp return_timestamp
      */
-    public static function delete_inactive_student($student_id, $years = 2, $warning_message = false, $return_timestamp = false)
-    {
+    public static function delete_inactive_student(
+        $student_id,
+        $years = 2,
+        $warning_message = false,
+        $return_timestamp = false
+    ) {
         $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
         $sql = 'SELECT login_date FROM '.$tbl_track_login.'
                 WHERE login_user_id = '.intval($student_id).'
@@ -5090,8 +5101,10 @@ class UserManager
     public static function getTeachersList()
     {
         $userTable = Database::get_main_table(TABLE_MAIN_USER);
-
-        $resultData = Database::select('user_id, lastname, firstname, username', $userTable, array(
+        $resultData = Database::select(
+            'user_id, lastname, firstname, username',
+            $userTable,
+            array(
             'where' => array(
                 'status = ?' => COURSEMANAGER
             )
@@ -5117,9 +5130,7 @@ class UserManager
                 FROM $user
                 GROUP BY official_code";
         $result = Database::query($sql);
-
         $values = Database::store_result($result, 'ASSOC');
-
         $result = array();
         foreach ($values as $value) {
             $result[$value['official_code']] = $value['official_code'];
@@ -5504,4 +5515,53 @@ SQL;
 
         return [];
     }
+
+    /**
+     * Check if user is teacher of a student based in their courses
+     * @param $teacherId
+     * @param $studentId
+     * @return array
+     */
+    public static function getCommonCoursesBetweenTeacherAndStudent($teacherId, $studentId)
+    {
+        $courses = CourseManager::getCoursesFollowedByUser($teacherId, COURSEMANAGER);
+        if (empty($courses)) {
+            return false;
+        }
+
+        $coursesFromUser = CourseManager::get_courses_list_by_user_id($studentId);
+        if (empty($coursesFromUser)) {
+            return false;
+        }
+
+        $coursesCodeList = array_column($courses, 'code');
+        $coursesCodeFromUserList = array_column($coursesFromUser, 'code');
+        $commonCourses = array_intersect($coursesCodeList, $coursesCodeFromUserList);
+        $commonCourses = array_filter($commonCourses);
+
+        if (!empty($commonCourses)) {
+            return $commonCourses;
+        }
+
+        return [];
+    }
+
+    /**
+     * @param $teacherId
+     * @param $studentId
+     * @return bool
+     */
+    public static function isTeacherOfStudent($teacherId, $studentId)
+    {
+        $courses = self::getCommonCoursesBetweenTeacherAndStudent(
+            $teacherId,
+            $studentId
+        );
+
+        if (!empty($courses)) {
+            return true;
+        }
+
+        return false;
+    }
 }

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

@@ -391,7 +391,14 @@ class IndexManager
             ];
         }
 
-        if (api_get_setting('allow_skills_tool') == 'true') {
+        if (empty($certificatesItem) && empty($searchItem)) {
+            return '';
+        } else {
+            $items[] = $certificatesItem;
+            $items[] = $searchItem;
+        }
+
+        if (Skill::isAllow(0, false)) {
             $items[] = [
                 'icon' => Display::return_icon('skill-badges.png', get_lang('MySkills')),
                 'link' => api_get_path(WEB_CODE_PATH).'social/my_skills_report.php',
@@ -406,7 +413,6 @@ class IndexManager
                 ];
             }
         }
-        return $items;
     }
 
     /**

+ 9 - 6
main/install/configuration.dist.php

@@ -461,7 +461,7 @@ VALUES (12, 13, 'is_mandatory', 'IsMandatory', 1, 1, NOW());
 */
 //$_configuration['allow_mandatory_survey'] = false;
 // ------
-//
+
 // Allow career diagram, requires a DB change:
 //UPDATE extra_field_values SET created_at = NULL WHERE CAST(created_at AS CHAR(20)) = '0000-00-00 00:00:00';
 //UPDATE extra_field_values SET updated_at = NULL WHERE CAST(updated_at AS CHAR(20)) = '0000-00-00 00:00:00';
@@ -548,12 +548,12 @@ $_configuration['score_grade_model'] = [
     ]
 ];
 */
-//Allow show link to request vinculation HRM-user
+
+// Allow show link to request relation between HRM and user
 //$_configuration['show_link_request_hrm_user'] = false;
-// Allow CKEditor start up with ShowBlocks plugin acive
+// Allow CKEditor start up with ShowBlocks plugin active
 //$_configuration['ckeditor_startup_outline_blocks'] = false;
-//
-// ------ SETTINGS FOT USER COURSE LIST
+// SETTINGS FOR USER COURSE LIST
 // Manage the links to Session Index page
 // 1 = Default. Works as it is now (default is to link to the special session page)
 // 0 = No link (not clickable)
@@ -574,4 +574,7 @@ $_configuration['score_grade_model'] = [
 //ALTER TABLE course_category ADD image varchar(255) NULL;
 //$_configuration['my_courses_list_as_category'] = false;
 // ------
-//
+
+// Skills can only visible for admins, teachers (related to a user via a course),
+// and HRM users (if related to a user).
+// $_configuration['allow_private_skills'] = false;

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

@@ -8031,4 +8031,14 @@ $HrmList = "Human Resource Managers list";
 $AssignHrmToUser = "Assign Human Resources Manager to user";
 $AddHrmToUser = "Add Human Resources Manager to user";
 $HrmAssignedUsersCourseList = "Human Resources Manager assigned users course list";
+$GoToSurvey = "Go to Survey";
+$NotificationCertificateSubject = "Certificate notification";
+$NotificationCertificateTemplate = "((user_first_name)),
+
+Congratulations on the completion of ((course_title)). Your final grade received for this class is ((score)). Please allow a few days for it to reflect in their system. We look forward to seeing you in future classes. If we can assist you further in any way, please feel free to contact us.
+
+Sincerely,
+((author_first_name)), ((author_last_name))
+((portal_name))";
+$SendCertificateNotifications = "Send certificate notification to all users";
 ?>

+ 2 - 3
main/mySpace/myStudents.php

@@ -405,9 +405,8 @@ if (api_can_login_as($student_id)) {
         Display::return_icon('login_as.png', get_lang('LoginAs'), null, ICON_SIZE_MEDIUM).'</a>&nbsp;&nbsp;';
 }
 
-if (api_is_platform_admin(false, true) ||
-    api_is_student_boss()
-) {
+
+if (Skill::isAllow($student_id, false)) {
     echo Display::url(
         Display::return_icon(
             'skill-badges.png',

+ 1 - 1
main/session/scheduled_announcement.php

@@ -5,7 +5,7 @@ $cidReset = true;
 
 require_once __DIR__.'/../inc/global.inc.php';
 
-api_protect_admin_script();
+api_protect_admin_script(true);
 
 $sessionId = isset($_GET['session_id']) ? (int) $_GET['session_id'] : 0;
 $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

+ 4 - 2
main/social/message_for_group_form.inc.php

@@ -106,8 +106,10 @@ if (api_get_setting('allow_message_tool') === 'true') {
     $form->addElement(
         'file',
         'attach_1',
-        sprintf(get_lang('MaximunFileSizeX'),
-        format_file_size(api_get_setting('message_max_upload_filesize')))
+        sprintf(
+            get_lang('MaximunFileSizeX'),
+            format_file_size(api_get_setting('message_max_upload_filesize'))
+        )
     );
     $form->addButtonSend(get_lang('SendMessage'));
 

+ 31 - 15
main/social/my_skills_report.php

@@ -9,6 +9,8 @@
 
 require_once __DIR__.'/../inc/global.inc.php';
 
+Skill::isAllow();
+
 $isStudent = api_is_student();
 $isStudentBoss = api_is_student_boss();
 $isDRH = api_is_drh();
@@ -19,18 +21,15 @@ if (!$isStudent && !$isStudentBoss && !$isDRH) {
 }
 
 $userId = api_get_user_id();
-
 $skillTable = Database::get_main_table(TABLE_MAIN_SKILL);
 $skillRelUserTable = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
 $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
-
 $tableRows = array();
-
 $tpl = new Template(get_lang('Skills'));
 $tplPath = null;
 
-$tpl->assign('allowSkillsTool', api_get_setting('allow_skills_tool') === 'true');
-$tpl->assign('allowDrhSkillsManagement', api_get_setting('allow_hr_skills_management') === 'true');
+$tpl->assign('allow_skill_tool', api_get_setting('allow_skills_tool') === 'true');
+$tpl->assign('allow_drh_skills_management', api_get_setting('allow_hr_skills_management') === 'true');
 
 if ($isStudent) {
     $sql = "SELECT s.name, sru.acquired_skill_at, c.title, c.directory
@@ -40,14 +39,19 @@ if ($isStudent) {
             LEFT JOIN $courseTable c
             ON sru.course_id = c.id
             WHERE sru.user_id = $userId";
-
     $result = Database::query($sql);
-
     while ($resultData = Database::fetch_assoc($result)) {
         $tableRow = array(
             'skillName' => $resultData['name'],
             'achievedAt' => api_format_date($resultData['acquired_skill_at'], DATE_FORMAT_NUMBER),
-            'courseImage' => Display::return_icon('course.png', null, null, ICON_SIZE_MEDIUM, null, true),
+            'courseImage' => Display::return_icon(
+                'course.png',
+                null,
+                null,
+                ICON_SIZE_MEDIUM,
+                null,
+                true
+            ),
             'courseName' => $resultData['title']
         );
 
@@ -68,7 +72,7 @@ if ($isStudent) {
     }
 
     $tplPath = 'skill/student_report.tpl';
-} else if ($isStudentBoss) {
+} elseif ($isStudentBoss) {
     $selectedStudent = isset($_REQUEST['student']) ? intval($_REQUEST['student']) : 0;
     $tableRows = array();
     $followedStudents = UserManager::getUsersFollowedByStudentBoss($userId);
@@ -94,7 +98,14 @@ if ($isStudent) {
                 'completeName' => $followedStudents[$selectedStudent]['completeName'],
                 'skillName' => $resultData['name'],
                 'achievedAt' => api_format_date($resultData['acquired_skill_at'], DATE_FORMAT_NUMBER),
-                'courseImage' => Display::return_icon('course.png', null, null, ICON_SIZE_MEDIUM, null, true),
+                'courseImage' => Display::return_icon(
+                    'course.png',
+                    null,
+                    null,
+                    ICON_SIZE_MEDIUM,
+                    null,
+                    true
+                ),
                 'courseName' => $resultData['title']
             );
 
@@ -118,15 +129,13 @@ if ($isStudent) {
     $tplPath = 'skill/student_boss_report.tpl';
     $tpl->assign('followedStudents', $followedStudents);
     $tpl->assign('selectedStudent', $selectedStudent);
-} else if ($isDRH) {
+} elseif ($isDRH) {
     $selectedCourse = isset($_REQUEST['course']) ? intval($_REQUEST['course']) : null;
     $selectedSkill = isset($_REQUEST['skill']) ? intval($_REQUEST['skill']) : 0;
-
     $action = null;
-
     if (!empty($selectedCourse)) {
         $action = 'filterByCourse';
-    } else if (!empty($selectedSkill)) {
+    } elseif (!empty($selectedSkill)) {
         $action = 'filterBySkill';
     }
 
@@ -174,7 +183,14 @@ if ($isStudent) {
     foreach ($tableRows as &$row) {
         $row['completeName'] = api_get_person_name($row['firstname'], $row['lastname']);
         $row['achievedAt'] = api_format_date($row['acquired_skill_at'], DATE_FORMAT_NUMBER);
-        $row['courseImage'] = Display::return_icon('course.png', null, null, ICON_SIZE_MEDIUM, null, true);
+        $row['courseImage'] = Display::return_icon(
+            'course.png',
+            null,
+            null,
+            ICON_SIZE_MEDIUM,
+            null,
+            true
+        );
 
         $imageSysPath = sprintf("%s%s/course-pic.png", api_get_path(SYS_COURSE_PATH), $row['c_directory']);
 

+ 15 - 14
main/social/profile.php

@@ -29,7 +29,7 @@ $show_full_profile = true;
 //social tab
 $this_section = SECTION_SOCIAL;
 
-//Initialize blocks
+// Initialize blocks
 $social_extra_info_block = null;
 $social_course_block = null;
 $social_group_info_block = null;
@@ -64,7 +64,6 @@ if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp
     $url .= empty($_SERVER['QUERY_STRING']) ? '' : '?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
     header('Location: '.$url);
     exit;
-
 } elseif (!empty($_POST['social_wall_new_msg']) && !empty($_POST['messageId'])) {
     $messageId = intval($_POST['messageId']);
     $messageContent = $_POST['social_wall_new_msg'];
@@ -81,7 +80,6 @@ if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp
     $url .= empty($_SERVER['QUERY_STRING']) ? '' : '?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
     header('Location: '.$url);
     exit;
-
 } elseif (isset($_GET['messageId'])) {
     $messageId = intval($_GET['messageId']);
     $messageInfo = MessageManager::get_message_by_id($messageId);
@@ -96,7 +94,8 @@ if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp
         }
     }
     api_not_allowed(true);
-} elseif (isset($_GET['u'])) { //I'm your friend? I can see your profile?
+} elseif (isset($_GET['u'])) {
+    //I'm your friend? I can see your profile?
     $user_id = intval($_GET['u']);
     if (api_is_anonymous($user_id, true)) {
         api_not_allowed(true);
@@ -118,7 +117,8 @@ if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp
                     USER_RELATION_TYPE_PARENT,
                     USER_RELATION_TYPE_FRIEND,
                     USER_RELATION_TYPE_GOODFRIEND
-                ))) {
+                ))
+            ) {
                 $show_full_profile = true;
             }
             //checking the relationship between my friend and me
@@ -130,7 +130,8 @@ if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp
                     USER_RELATION_TYPE_PARENT,
                     USER_RELATION_TYPE_FRIEND,
                     USER_RELATION_TYPE_GOODFRIEND
-                ))) {
+                ))
+            ) {
                 $show_full_profile = true;
             } else {
                 // im probably not a good friend
@@ -167,7 +168,7 @@ if (file_exists($timeAgoLocaleDir)) {
 }
 
 $htmlHeadXtra[] = '<script>
-$(document).ready(function (){
+$(document).ready(function(){
     var container = $("#wallMessages");
     container.jscroll({
         loadingHtml: "<div class=\"well_border\">' . get_lang('Loading').' </div>",
@@ -217,7 +218,10 @@ Session::write('social_user_id', (int) $user_id);
 
 // Setting some course info
 $my_user_id = isset($_GET['u']) ? intval($_GET['u']) : api_get_user_id();
-$personal_course_list = UserManager::get_personal_session_course_list($my_user_id, 50);
+$personal_course_list = UserManager::get_personal_session_course_list(
+    $my_user_id,
+    50
+);
 $course_list_code = array();
 $i = 1;
 $list = [];
@@ -262,7 +266,6 @@ $social_wall_block = $wallSocialAddPost;
 
 // Social Post Wall
 $posts = SocialManager::getWallMessagesByUser($my_user_id, $friendId);
-
 $social_post_wall_block = empty($posts) ? '<p>'.get_lang("NoPosts").'</p>' : $posts;
 
 $socialAutoExtendLink = Display::url(
@@ -276,7 +279,6 @@ $socialAutoExtendLink = Display::url(
 // Added a Jquery Function to return the Preview of OpenGraph URL Content
 $htmlHeadXtra[] = '<script>
 $(document).ready(function() {
-
     var getUrl = $("[name=\'social_wall_new_msg_main\']");
     var matchUrl = /https?:\/\/w{0,3}\w*?\.(\w*?\.)?\w{2,3}\S*|www\.(\w*?\.)?\w*?\.\w{2,3}\S*|(\w*?\.)?\w*?\.\w{2,3}[\/\?]\S*/ ;
 
@@ -371,7 +373,9 @@ if ($show_full_profile) {
                         $value_options = array();
                         // get option display text from user_field_options table
                         foreach ($id_options as $id_option) {
-                            $sql = "SELECT display_text FROM $t_ufo WHERE id = '$id_option'";
+                            $sql = "SELECT display_text 
+                                    FROM $t_ufo 
+                                    WHERE id = '$id_option'";
                             $res_options = Database::query($sql);
                             $row_options = Database::fetch_row($res_options);
                             $value_options[] = $row_options[0];
@@ -421,9 +425,7 @@ if ($show_full_profile) {
 
         // if there are information to show
         if (!empty($extra_information_value)) {
-
             $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
-
             $extra_information .= Display::panelCollapse(
                 get_lang('ExtraInformation'),
                 $extra_information_value,
@@ -647,7 +649,6 @@ if ($show_full_profile) {
 
     if (!empty($user_info['competences']) || !empty($user_info['diplomas'])
         || !empty($user_info['openarea']) || !empty($user_info['teach'])) {
-
         $more_info .= '<div><h3>'.get_lang('MoreInformation').'</h3></div>';
         if (!empty($user_info['competences'])) {
             $more_info .= '<br />';

+ 4 - 6
main/social/profile_friends_and_groups.inc.php

@@ -52,9 +52,7 @@ if (isset($_GET['view']) && in_array($_GET['view'], $views)) {
                     $friend['lastName']
                 );
                 $friend_html .= '<div id=div_'.$friend['friend_user_id'].' class="image_friend_network" ><span><center>';
-
                 $userPicture = UserManager::getUserPicture($friend['friend_user_id']);
-
                 $friend_html .= '<a href="profile.php?u='.$friend['friend_user_id'].'">';
                 $friend_html .= '<img src="'.$userPicture.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" />';
                 $friend_html .= '</center></span>';
@@ -95,12 +93,12 @@ if (isset($_GET['view']) && in_array($_GET['view'], $views)) {
                 );
                 if ($count_users_group == 1) {
                     $count_users_group = $count_users_group.' '.get_lang(
-                            'Member'
-                        );
+                        'Member'
+                    );
                 } else {
                     $count_users_group = $count_users_group.' '.get_lang(
-                            'Members'
-                        );
+                        'Members'
+                    );
                 }
                 $picture = $userGroup->get_picture_group(
                     $result['id'],

+ 3 - 2
main/social/skills_ranking.php

@@ -7,9 +7,11 @@
  */
 
 $cidReset = true;
-
 require_once __DIR__.'/../inc/global.inc.php';
 
+api_block_anonymous_users();
+Skill::isAllow();
+
 //Add the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
@@ -79,7 +81,6 @@ $extra_params['autowidth'] = 'true';
 //height auto
 $extra_params['height'] = 'auto';
 //$extra_params['excel'] = 'excel';
-
 //$extra_params['rowList'] = array(10, 20 ,30);
 
 $jqgrid = Display::grid_js(

+ 1 - 5
main/social/skills_tree.php

@@ -11,10 +11,7 @@ require_once __DIR__.'/../inc/global.inc.php';
 $this_section = SECTION_MYPROFILE;
 
 api_block_anonymous_users();
-
-if (api_get_setting('allow_skills_tool') !== 'true') {
-    api_not_allowed();
-}
+Skill::isAllow(api_get_user_id());
 
 //Adds the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
@@ -24,7 +21,6 @@ $htmlHeadXtra[] = api_get_js('skills.js');
 
 $skill = new Skill();
 $type = 'read'; //edit
-
 $tree = $skill->get_skills_tree(api_get_user_id(), null, true);
 $skill_visualizer = new SkillVisualizer($tree, $type);
 $url = api_get_path(WEB_AJAX_PATH).'skill.ajax.php?1=1';

+ 11 - 11
main/social/skills_wheel.php

@@ -7,14 +7,10 @@
 $cidReset = true;
 
 require_once __DIR__.'/../inc/global.inc.php';
-
 $this_section = SECTION_SOCIAL;
 
-if (api_get_setting('allow_skills_tool') !== 'true') {
-    api_not_allowed();
-}
-
 api_block_anonymous_users();
+Skill::isAllow(api_get_user_id());
 
 //Adds the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_js('d3/d3.v3.5.4.min.js');
@@ -47,21 +43,25 @@ $dialogForm->addLabel(
     Display::tag('p', null, ['id' => 'parent', 'class' => 'form-control-static'])
 );
 $dialogForm->addLabel(
-    [get_lang('Gradebook'), get_lang('WithCertificate')],
-    Display::tag('ul', null, ['id' => 'gradebook', 'class' => 'form-control-static list-unstyled'])
+    [
+        get_lang('Gradebook'),
+        get_lang('WithCertificate')
+    ],
+    Display::tag(
+        'ul',
+        null,
+        ['id' => 'gradebook', 'class' => 'form-control-static list-unstyled']
+    )
 );
 $dialogForm->addLabel(
     get_lang('Description'),
     Display::tag('p', null, ['id' => 'description', 'class' => 'form-control-static'])
 );
 
-$type = 'read'; //edit
+$type = 'read';
 $tree = $skill->get_skills_tree($userId, null, true);
 $skill_visualizer = new SkillVisualizer($tree, $type);
 $tpl->assign('skill_visualizer', $skill_visualizer);
-//$html = $skill_visualizer->return_html();
-//$tpl->assign('html', $html);
-
 $tpl->assign('dialogForm', $dialogForm->returnForm());
 
 $url = api_get_path(WEB_AJAX_PATH)."skill.ajax.php?a=get_skills_tree_json&load_user=$userId";

+ 2 - 2
main/template/default/skill/drh_report.tpl

@@ -1,7 +1,7 @@
-{% if allowSkillsTool %}
+{% if allow_skill_tool %}
     <div class="btn-group">
         <a class="btn btn-default" href="{{ _p.web_main }}social/skills_wheel.php">{{ 'SkillsWheel' | get_lang }}</a>
-        {% if allowDrhSkillsManagement %}
+        {% if allow_drh_skills_management %}
             <a class="btn btn-default" href="{{ _p.web_main }}admin/skills_wheel.php">{{ 'ManageSkills' | get_lang }}</a>
         {% endif %}
     </div>

+ 1 - 1
main/template/default/skill/student_boss_report.tpl

@@ -1,4 +1,4 @@
-{% if allowSkillsTool %}
+{% if allow_skill_tool %}
     <div class="btn-group">
         <a class="btn btn-default" href="{{ _p.web_main }}social/skills_wheel.php">
             {{ 'SkillsWheel' | get_lang }}

+ 1 - 1
main/template/default/skill/student_report.tpl

@@ -1,4 +1,4 @@
-{% if allowSkillsTool %}
+{% if allow_skill_tool %}
     <div class="btn-group">
         <a class="btn btn-default" href="{{ _p.web_main }}social/skills_wheel.php">{{ 'SkillsWheel' | get_lang }}</a>
     </div>

+ 69 - 30
main/tracking/courseLog.php

@@ -145,10 +145,7 @@ $htmlHeadXtra[] .= $js;
 
 // Database table definitions.
 //@todo remove this calls
-$TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
-$TABLETRACK_LINKS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
 $TABLETRACK_DOWNLOADS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
-$TABLETRACK_ACCESS_2 = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
 $TABLETRACK_EXERCISES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
 $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
@@ -159,9 +156,18 @@ $sessionId = api_get_session_id();
 
 // Breadcrumbs.
 if (isset($_GET['origin']) && $_GET['origin'] == 'resume_session') {
-    $interbreadcrumb[] = array('url' => '../admin/index.php', 'name' => get_lang('PlatformAdmin'));
-    $interbreadcrumb[] = array('url' => '../session/session_list.php', 'name' => get_lang('SessionList'));
-    $interbreadcrumb[] = array('url' => '../session/resume_session.php?id_session='.$sessionId, 'name' => get_lang('SessionOverview'));
+    $interbreadcrumb[] = array(
+        'url' => '../admin/index.php',
+        'name' => get_lang('PlatformAdmin')
+    );
+    $interbreadcrumb[] = array(
+        'url' => '../session/session_list.php',
+        'name' => get_lang('SessionList')
+    );
+    $interbreadcrumb[] = array(
+        'url' => '../session/resume_session.php?id_session='.$sessionId,
+        'name' => get_lang('SessionOverview')
+    );
 }
 
 $view = isset($_REQUEST['view']) ? $_REQUEST['view'] : '';
@@ -213,7 +219,12 @@ Display::display_header($nameTools, 'Tracking');
 
 /* MAIN CODE */
 
-$actionsLeft = Display::return_icon('user_na.png', get_lang('StudentsTracking'), array(), ICON_SIZE_MEDIUM);
+$actionsLeft = Display::return_icon(
+    'user_na.png',
+    get_lang('StudentsTracking'),
+    array(),
+    ICON_SIZE_MEDIUM
+);
 $actionsLeft .= Display::url(
     Display::return_icon('group.png', get_lang('GroupReporting'), array(), ICON_SIZE_MEDIUM),
     'course_log_groups.php?'.api_get_cidreq()
@@ -278,10 +289,25 @@ echo Display::toolbarAction(
 
 $course_name = get_lang('Course').' '.$courseInfo['name'];
 if ($session_id) {
-    $titleSession = Display::return_icon('session.png', get_lang('Session'), array(), ICON_SIZE_SMALL).' '.api_get_session_name($session_id);
-    $titleCourse = Display::return_icon('course.png', get_lang('Course'), array(), ICON_SIZE_SMALL).' '.$course_name;
+    $titleSession = Display::return_icon(
+        'session.png',
+        get_lang('Session'),
+        array(),
+        ICON_SIZE_SMALL
+    ).' '.api_get_session_name($session_id);
+    $titleCourse = Display::return_icon(
+        'course.png',
+        get_lang('Course'),
+        array(),
+        ICON_SIZE_SMALL
+    ).' '.$course_name;
 } else {
-    $titleSession = Display::return_icon('course.png', get_lang('Course'), array(), ICON_SIZE_SMALL).' '.$courseInfo['name'];
+    $titleSession = Display::return_icon(
+        'course.png',
+        get_lang('Course'),
+        array(),
+        ICON_SIZE_SMALL
+    ).' '.$courseInfo['name'];
 }
 $teacherList = CourseManager::get_teacher_list_from_course_code_to_string(
     $courseInfo['code'],
@@ -312,7 +338,9 @@ if (!empty($coaches)) {
     $html .= $coaches;
 }
 
-if (api_is_platform_admin(true) || api_is_session_general_coach()) {
+if (api_is_platform_admin(true) ||
+    api_is_session_general_coach()
+) {
     $sessionList = SessionManager::get_session_by_course($courseInfo['real_id']);
 
     if (!empty($sessionList)) {
@@ -397,7 +425,8 @@ if (count($a_students) > 0) {
         'users_tracking',
         array('TrackingCourseLog', 'get_number_of_users'),
         array('TrackingCourseLog', 'get_user_data'),
-        (api_is_western_name_order() xor api_sort_by_first_name()) ? 3 : 2);
+        (api_is_western_name_order() xor api_sort_by_first_name()) ? 3 : 2
+    );
 
     $parameters['cidReq'] = Security::remove_XSS($_GET['cidReq']);
     $parameters['id_session'] = $session_id;
@@ -514,31 +543,30 @@ if (count($a_students) > 0) {
 echo Display::panel($html, $titleSession);
 // Send the csv file if asked.
 if ($export_csv) {
-    $csv_headers = array();
-
-    $csv_headers[] = get_lang('OfficialCode', '');
+    $csv_headers = [];
+    $csv_headers[] = get_lang('OfficialCode');
     if ($is_western_name_order) {
-        $csv_headers[] = get_lang('FirstName', '');
-        $csv_headers[] = get_lang('LastName', '');
+        $csv_headers[] = get_lang('FirstName');
+        $csv_headers[] = get_lang('LastName');
     } else {
-        $csv_headers[] = get_lang('LastName', '');
-        $csv_headers[] = get_lang('FirstName', '');
+        $csv_headers[] = get_lang('LastName');
+        $csv_headers[] = get_lang('FirstName');
     }
-    $csv_headers[] = get_lang('Login', ''); //
-    $csv_headers[] = get_lang('TrainingTime', '');
-    $csv_headers[] = get_lang('CourseProgress', '');
-    $csv_headers[] = get_lang('ExerciseProgress', '');
-    $csv_headers[] = get_lang('ExerciseAverage', '');
-    $csv_headers[] = get_lang('Score', '');
-    $csv_headers[] = get_lang('Student_publication', '');
-    $csv_headers[] = get_lang('Messages', '');
+    $csv_headers[] = get_lang('Login');
+    $csv_headers[] = get_lang('TrainingTime');
+    $csv_headers[] = get_lang('CourseProgress');
+    $csv_headers[] = get_lang('ExerciseProgress');
+    $csv_headers[] = get_lang('ExerciseAverage');
+    $csv_headers[] = get_lang('Score');
+    $csv_headers[] = get_lang('Student_publication');
+    $csv_headers[] = get_lang('Messages');
 
     if (empty($session_id)) {
         $csv_headers[] = get_lang('Survey');
     }
 
-    $csv_headers[] = get_lang('FirstLoginInCourse', '');
-    $csv_headers[] = get_lang('LatestLoginInCourse', '');
+    $csv_headers[] = get_lang('FirstLoginInCourse');
+    $csv_headers[] = get_lang('LatestLoginInCourse');
 
     if (isset($_GET['additional_profile_field'])) {
         foreach ($_GET['additional_profile_field'] as $fieldId) {
@@ -546,7 +574,18 @@ if ($export_csv) {
         }
     }
     ob_end_clean();
-    array_unshift($csv_content, $csv_headers); // Adding headers before the content.
+
+     // Adding headers before the content.
+    array_unshift($csv_content, $csv_headers);
+
+    if ($session_id) {
+        $sessionData = [];
+        $sessionInfo = api_get_session_info($session_id);
+        $sessionDates = SessionManager::parseSessionDates($sessionInfo);
+
+        array_unshift($csv_content, [get_lang('Date'), $sessionDates['access']]);
+        array_unshift($csv_content, [get_lang('SessionName'), $sessionInfo['name']]);
+    }
 
     Export::arrayToCsv($csv_content, 'reporting_student_list');
     exit;

+ 2 - 1
main/work/work.lib.php

@@ -4129,12 +4129,13 @@ function addDir($formValues, $user_id, $courseInfo, $groupId, $session_id)
 
     $dirName = '/'.$created_dir;
     $today = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
+    $title = isset($formValues['work_title']) ? $formValues['work_title'] : $formValues['new_dir'];
 
     $workTable = new CStudentPublication();
     $workTable
         ->setCId($course_id)
         ->setUrl($dirName)
-        ->setTitle($formValues['new_dir'])
+        ->setTitle($title)
         ->setDescription($formValues['description'])
         ->setActive(true)
         ->setAccepted(true)

+ 1 - 3
plugin/clockworksms/install.php

@@ -8,8 +8,6 @@
  * @package chamilo.plugin.clockworksms
  * @author  Imanol Losada <imanol.losada@beeznest.com>
  */
-/**
- * Initialization
- */
+
 require_once __DIR__.'/config.php';
 ClockworksmsPlugin::create()->install();

+ 89 - 88
plugin/clockworksms/lang/english.php

@@ -1,7 +1,7 @@
 <?php
 
-$strings['plugin_title']        = "SMS Sending";
-$strings['plugin_comment']      = "When enabled and an email sent successfully, a text message is sent to the user.";
+$strings['plugin_title'] = "SMS Sending";
+$strings['plugin_comment'] = "When enabled and an email sent successfully, a text message is sent to the user.";
 
 $strings['api_key'] = "Clockwork SMS key";
 $strings['api_key_help'] = "This is the Clockwork SMS server security key. <a target='_blank' href='http://www.clockworksms.com/platforms/chamilo/'>Click here</a> to get it.";
@@ -13,90 +13,91 @@ $strings['tool_enable_help'] = "Choose if you want to enable SMS sending tool.
 $strings['type'] = "Send SMS when";
 $strings['mobile_phone_number'] = "Mobile Phone (include country dialing code only)";
 
-$strings['MessageWelcomeXLoginXPasswordX']                              = "A user is added to the platform";
-$strings['MessageXNewFileSharedCourseXByX']                             = "A file is added to dropbox";
-$strings['MessageXAccountApprovedConnectX']                             = "An account is approved";
-$strings['MessageXNewCourseXBeenCreatedX']                              = "A new course is created";
-$strings['MessageXNewUserXSubscribedCourseX']                           = "A user is subscribed to a course";
-$strings['MessageXNewCourseSuggestedTeacherX']                          = "A new course is suggested";
-$strings['MessageXCourseOpeningRequestCodeXRegistered']                 = "A new course opening request is registered";
-$strings['MessageXCourseOpeningRequestCourseCodeXApproved']             = "A new course opening request is approved";
-$strings['MessageXRequestOpenCourseCodeXReject']                        = "A new course opening request is rejected";
-$strings['MessageXCourseOpeningRequestCourseCodeX']                     = "Additional information is required for a new course opening request";
-$strings['MessageXBeenSubscribedCourseX']                               = "A user is added to the course but not registered to it yet";
-$strings['MessageXAssignmentBeenCreatedCourseX']                        = "Homework is created";
-$strings['MessageXAccountCreatedUpdatedLoginXPasswordX']                = "A user account is created or updated";
-$strings['MessageXPasswordUpdatedLoginXPasswordX']                      = "A user password is updated";
-$strings['MessageXRequestedPasswordChange']                             = "A user requests a password change";
-$strings['MessageXReceivedNewPersonalMessages']                         = "New personal messages are received in user's inbox or forum";
-$strings['MessageXNewUserXPendingApproval']                             = "A new user registration is pending for approval";
-$strings['MessageXXPostedForumXCourseX']                                = "A user posts in forum";
-$strings['MessageXXXCheckEmailConnectMoreInfo']                         = "An announcement is sent";
-$strings['MessageXXStudentXAnsweredTestX']                              = "A student solves an exercise";
-$strings['MessageXXStudentXAnsweredTestXOpenQuestion']                  = "A student solves an open question";
-$strings['MessageXXStudentXAnsweredTestXVoiceQuestion']                 = "A student solves a voice question";
-$strings['MessageXXAnswerOpenQuestionTestXReviewed']                    = "An open question answer is reviewed";
-$strings['MessageXXNewThreadXStartedForumX']                            = "A new thread is started in forum";
-$strings['MessageXXNewAnswerPostedXForumX']                             = "A new answer is posted in forum";
-$strings['MessageXXNewSystemAnnouncementAdded']                         = "A new system announcement is added and the user does not want to send a test email";
-$strings['MessageXTestXNewSystemAnnouncementAdded']                     = "A new system announcement is added and the user wants to send a test email";
-$strings['MessageXXSystemAnnouncementUpdate']                           = "A new system announcement is updated and the user does not want to send a test email";
-$strings['MessageXTestXSystemAnnouncementUpdate']                       = "A new system announcement is updated and the user wants to send a test email";
-$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper']  = "An assignment is uploaded and there is no current session (this will be sent only to coaches)";
-$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper']   = "An assignment is uploaded (this will be sent only to teachers)";
-$strings['MessageXUserXUploadedAssignmentXCourseX']                     = "... and there is no current session (this will be sent only to coaches)";
-$strings['MessageXUserXUploadedAssignmentXCheckX']                      = "... (this will be sent only to teachers)";
-$strings['MessageXSubscribedSessionX']                                  = "A session is created or updated and new users are subscribed";
-$strings['MessageXSubscribedSessionXCSV']                               = "New users are subscribed to a session importing a CSV file";
-$strings['MessageXUserXSuggestedBeFriends']                             = "A friendship invitation is received";
-$strings['MessageXUserXAnsweredInboxMessage']                           = "A message reply is received in inbox";
-$strings['MessageXBeenInvitedJoinGroupX']                               = "A group join invitation is received";
-$strings['MessageXMessagesSentEditedGroupXEdited']                      = "A group topic message is updated";
-$strings['MessageXMessagesSentEditedGroupXAdded']                       = "A group topic message is added";
-$strings['MessageXBeenInvitedCompleteSurveyXCourseX']                   = "A new survey is created";
-$strings['MessageXReminderAssignmentXCourseXDue']                       = "A reminder is sent to students who have not uploaded their assignment yet";
-$strings['MessageXUserDetailsModified']                                 = "User details have been updated";
+$strings['MessageWelcomeXLoginXPasswordX'] = "A user is added to the platform";
+$strings['MessageXNewFileSharedCourseXByX'] = "A file is added to dropbox";
+$strings['MessageXAccountApprovedConnectX'] = "An account is approved";
+$strings['MessageXNewCourseXBeenCreatedX'] = "A new course is created";
+$strings['MessageXNewUserXSubscribedCourseX'] = "A user is subscribed to a course";
+$strings['MessageXNewCourseSuggestedTeacherX'] = "A new course is suggested";
+$strings['MessageXCourseOpeningRequestCodeXRegistered'] = "A new course opening request is registered";
+$strings['MessageXCourseOpeningRequestCourseCodeXApproved'] = "A new course opening request is approved";
+$strings['MessageXRequestOpenCourseCodeXReject'] = "A new course opening request is rejected";
+$strings['MessageXCourseOpeningRequestCourseCodeX'] = "Additional information is required for a new course opening request";
+$strings['MessageXBeenSubscribedCourseX'] = "A user is added to the course but not registered to it yet";
+$strings['MessageXAssignmentBeenCreatedCourseX'] = "Homework is created";
+$strings['MessageXAccountCreatedUpdatedLoginXPasswordX'] = "A user account is created or updated";
+$strings['MessageXPasswordUpdatedLoginXPasswordX'] = "A user password is updated";
+$strings['MessageXRequestedPasswordChange'] = "A user requests a password change";
+$strings['MessageXReceivedNewPersonalMessages'] = "New personal messages are received in user's inbox or forum";
+$strings['MessageXNewUserXPendingApproval'] = "A new user registration is pending for approval";
+$strings['MessageXXPostedForumXCourseX'] = "A user posts in forum";
+$strings['MessageXXXCheckEmailConnectMoreInfo'] = "An announcement is sent";
+$strings['MessageXXStudentXAnsweredTestX'] = "A student solves an exercise";
+$strings['MessageXXStudentXAnsweredTestXOpenQuestion'] = "A student solves an open question";
+$strings['MessageXXStudentXAnsweredTestXVoiceQuestion'] = "A student solves a voice question";
+$strings['MessageXXAnswerOpenQuestionTestXReviewed'] = "An open question answer is reviewed";
+$strings['MessageXXNewThreadXStartedForumX'] = "A new thread is started in forum";
+$strings['MessageXXNewAnswerPostedXForumX'] = "A new answer is posted in forum";
+$strings['MessageXXNewSystemAnnouncementAdded'] = "A new system announcement is added and the user does not want to send a test email";
+$strings['MessageXTestXNewSystemAnnouncementAdded'] = "A new system announcement is added and the user wants to send a test email";
+$strings['MessageXXSystemAnnouncementUpdate'] = "A new system announcement is updated and the user does not want to send a test email";
+$strings['MessageXTestXSystemAnnouncementUpdate'] = "A new system announcement is updated and the user wants to send a test email";
+$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper'] = "An assignment is uploaded and there is no current session (this will be sent only to coaches)";
+$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] = "An assignment is uploaded (this will be sent only to teachers)";
+$strings['MessageXUserXUploadedAssignmentXCourseX'] = "... and there is no current session (this will be sent only to coaches)";
+$strings['MessageXUserXUploadedAssignmentXCheckX'] = "... (this will be sent only to teachers)";
+$strings['MessageXSubscribedSessionX'] = "A session is created or updated and new users are subscribed";
+$strings['MessageXSubscribedSessionXCSV'] = "New users are subscribed to a session importing a CSV file";
+$strings['MessageXUserXSuggestedBeFriends'] = "A friendship invitation is received";
+$strings['MessageXUserXAnsweredInboxMessage'] = "A message reply is received in inbox";
+$strings['MessageXBeenInvitedJoinGroupX'] = "A group join invitation is received";
+$strings['MessageXMessagesSentEditedGroupXEdited'] = "A group topic message is updated";
+$strings['MessageXMessagesSentEditedGroupXAdded'] = "A group topic message is added";
+$strings['MessageXBeenInvitedCompleteSurveyXCourseX'] = "A new survey is created";
+$strings['MessageXReminderAssignmentXCourseXDue'] = "A reminder is sent to students who have not uploaded their assignment yet";
+$strings['MessageXUserDetailsModified'] = "User details have been updated";
+
+$strings['WelcomeXLoginXPasswordX'] = "Welcome to %s. Here are your user account details: login: %s, password: %s";
+$strings['XNewFileSharedCourseXByX'] = "%s: A new file has been shared with you in course %s by %s";
+$strings['XAccountApprovedConnectX'] = "%s: Your account has been approved by an administrator. You can now connect to %s";
+$strings['XNewCourseXBeenCreatedX'] = "%s: A new course (%s) has been created by %s";
+$strings['XNewUserXSubscribedCourseX'] = "%s: A new user (%s) has just subscribed to your course (%s)";
+$strings['XNewCourseSuggestedTeacherX'] = "%s: A new course has been suggested by teacher (%s). Please connect to the admin page to review it";
+$strings['XCourseOpeningRequestCodeXRegistered'] = "%s: Your course opening request (code %s) has been registered. You will be informed when it is approved";
+$strings['XCourseOpeningRequestCourseCodeXApproved'] = "%s: Your course opening request for course code %s has been approved. Connect to your portal to use it";
+$strings['XRequestOpenCourseCodeXReject'] = "%s: We are sorry to inform you that your request to open course code %s has been rejected";
+$strings['XCourseOpeningRequestCourseCodeX'] = "%s: Your course opening request for course code %s requires more information. Check e-mail for more info";
+$strings['XBeenSubscribedCourseX'] = "%s: You have been subscribed to course %s";
+$strings['XAssignmentBeenCreatedCourseX'] = "%s: A new assignment has been created in course %s. Please connect for more info";
+$strings['XAccountCreatedUpdatedLoginXPasswordX'] = "%s: Your account has been created or updated. You can now login as %s, password: %s";
+$strings['XPasswordUpdatedLoginXPasswordX'] = "%s: Your password has been updated. You can now login as %s, password: %s";
+$strings['XRequestedPasswordChange'] = "%s: You have requested a password change. Please check your e-mail for more information";
+$strings['XReceivedNewPersonalMessages'] = "%s: You have received new personal messages in your inbox or in the forum. Please check your e-mail for more info";
+$strings['XNewUserXPendingApproval'] = "%s: A new user (%s) registration is pending your approval. Please connect to the admin panel to review";
+$strings['XXPostedForumXCourseX'] = "%s: %s just posted on forum %s in course %s";
+$strings['XXXCheckEmailConnectMoreInfo'] = "%s: %s: %s. Check your e-mail or connect for more info";
+$strings['XXStudentXAnsweredTestX'] = "%s: %s: Student %s has just answered test %s";
+$strings['XXStudentXAnsweredTestXOpenQuestion'] = "%s: %s: Student %s answered test %s's open question. Please connect to review";
+$strings['XXStudentXAnsweredTestXVoiceQuestion'] = "%s: %s: Student %s answered test %s's voice question. Please connect to review";
+$strings['XXAnswerOpenQuestionTestXReviewed'] = "%s: %s: Your answer to an open question in test %s has been reviewed";
+$strings['XXNewThreadXStartedForumX'] = "%s: %s: A new thread (%s) has been started in forum %s";
+$strings['XXNewAnswerPostedXForumX'] = "%s: %s: A new answer has been posted to (%s) in forum %s";
+$strings['XXNewSystemAnnouncementAdded'] = "%s: %s";
+$strings['XTestXNewSystemAnnouncementAdded'] = "%s (test): %s";
+$strings['XXSystemAnnouncementUpdate'] = "%s: %s (update)";
+$strings['XTestXSystemAnnouncementUpdate'] = "%s (test): %s";
+$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper'] = "%s: User %s uploaded assignment %s in course %s";
+$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] = "%s: User %s uploaded assignment %s. Check %s";
+$strings['XUserXUploadedAssignmentXCourseX'] = "%s: User %s uploaded assignment %s in course %s";
+$strings['XUserXUploadedAssignmentXCheckX'] = "%s: User %s uploaded assignment %s. Check %s";
+$strings['XSubscribedSessionX'] = "%s: You have been subscribed to session %s";
+$strings['XSubscribedSessionXCSV'] = "%s: You have been subscribed to session %s";
+$strings['XUserXSuggestedBeFriends'] = "%s: User %s suggested you should be friends. Check your inbox or e-mail for details";
+$strings['XUserXAnsweredInboxMessage'] = "%s: User %s just answered your Inbox message";
+$strings['XBeenInvitedJoinGroupX'] = "%s: you have been invited to join group %s. Check your Inbox for details";
+$strings['XMessagesSentEditedGroupXEdited'] = "%s: Messages sent or edited in group %s. Check your Inbox for details";
+$strings['XMessagesSentEditedGroupXAdded'] = "%s: Messages sent or edited in group %s. Check your Inbox for details";
+$strings['XBeenInvitedCompleteSurveyXCourseX'] = "%s: You have been invited to complete survey %s in course %s";
+$strings['XReminderAssignmentXCourseXDue'] = "%s: This is a simple reminder that your assignment (%s) in course %s is still due";
+$strings['XUserDetailsModified'] = "%s: Your user details have been modified. Please check your e-mail for more information";
 
-$strings['WelcomeXLoginXPasswordX']                                     = "Welcome to %s. Here are your user account details: login: %s, password: %s";
-$strings['XNewFileSharedCourseXByX']                                    = "%s: A new file has been shared with you in course %s by %s";
-$strings['XAccountApprovedConnectX']                                    = "%s: Your account has been approved by an administrator. You can now connect to %s";
-$strings['XNewCourseXBeenCreatedX']                                     = "%s: A new course (%s) has been created by %s";
-$strings['XNewUserXSubscribedCourseX']                                  = "%s: A new user (%s) has just subscribed to your course (%s)";
-$strings['XNewCourseSuggestedTeacherX']                                 = "%s: A new course has been suggested by teacher (%s). Please connect to the admin page to review it";
-$strings['XCourseOpeningRequestCodeXRegistered']                        = "%s: Your course opening request (code %s) has been registered. You will be informed when it is approved";
-$strings['XCourseOpeningRequestCourseCodeXApproved']                    = "%s: Your course opening request for course code %s has been approved. Connect to your portal to use it";
-$strings['XRequestOpenCourseCodeXReject']                               = "%s: We are sorry to inform you that your request to open course code %s has been rejected";
-$strings['XCourseOpeningRequestCourseCodeX']                            = "%s: Your course opening request for course code %s requires more information. Check e-mail for more info";
-$strings['XBeenSubscribedCourseX']                                      = "%s: You have been subscribed to course %s";
-$strings['XAssignmentBeenCreatedCourseX']                               = "%s: A new assignment has been created in course %s. Please connect for more info";
-$strings['XAccountCreatedUpdatedLoginXPasswordX']                       = "%s: Your account has been created or updated. You can now login as %s, password: %s";
-$strings['XPasswordUpdatedLoginXPasswordX']                             = "%s: Your password has been updated. You can now login as %s, password: %s";
-$strings['XRequestedPasswordChange']                                    = "%s: You have requested a password change. Please check your e-mail for more information";
-$strings['XReceivedNewPersonalMessages']                                = "%s: You have received new personal messages in your inbox or in the forum. Please check your e-mail for more info";
-$strings['XNewUserXPendingApproval']                                    = "%s: A new user (%s) registration is pending your approval. Please connect to the admin panel to review";
-$strings['XXPostedForumXCourseX']                                       = "%s: %s just posted on forum %s in course %s";
-$strings['XXXCheckEmailConnectMoreInfo']                                = "%s: %s: %s. Check your e-mail or connect for more info";
-$strings['XXStudentXAnsweredTestX']                                     = "%s: %s: Student %s has just answered test %s";
-$strings['XXStudentXAnsweredTestXOpenQuestion']                         = "%s: %s: Student %s answered test %s's open question. Please connect to review";
-$strings['XXStudentXAnsweredTestXVoiceQuestion']                        = "%s: %s: Student %s answered test %s's voice question. Please connect to review";
-$strings['XXAnswerOpenQuestionTestXReviewed']                           = "%s: %s: Your answer to an open question in test %s has been reviewed";
-$strings['XXNewThreadXStartedForumX']                                   = "%s: %s: A new thread (%s) has been started in forum %s";
-$strings['XXNewAnswerPostedXForumX']                                    = "%s: %s: A new answer has been posted to (%s) in forum %s";
-$strings['XXNewSystemAnnouncementAdded']                                = "%s: %s";
-$strings['XTestXNewSystemAnnouncementAdded']                            = "%s (test): %s";
-$strings['XXSystemAnnouncementUpdate']                                  = "%s: %s (update)";
-$strings['XTestXSystemAnnouncementUpdate']                              = "%s (test): %s";
-$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper']         = "%s: User %s uploaded assignment %s in course %s";
-$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper']          = "%s: User %s uploaded assignment %s. Check %s";
-$strings['XUserXUploadedAssignmentXCourseX']                            = "%s: User %s uploaded assignment %s in course %s";
-$strings['XUserXUploadedAssignmentXCheckX']                             = "%s: User %s uploaded assignment %s. Check %s";
-$strings['XSubscribedSessionX']                                         = "%s: You have been subscribed to session %s";
-$strings['XSubscribedSessionXCSV']                                      = "%s: You have been subscribed to session %s";
-$strings['XUserXSuggestedBeFriends']                                    = "%s: User %s suggested you should be friends. Check your inbox or e-mail for details";
-$strings['XUserXAnsweredInboxMessage']                                  = "%s: User %s just answered your Inbox message";
-$strings['XBeenInvitedJoinGroupX']                                      = "%s: you have been invited to join group %s. Check your Inbox for details";
-$strings['XMessagesSentEditedGroupXEdited']                             = "%s: Messages sent or edited in group %s. Check your Inbox for details";
-$strings['XMessagesSentEditedGroupXAdded']                              = "%s: Messages sent or edited in group %s. Check your Inbox for details";
-$strings['XBeenInvitedCompleteSurveyXCourseX']                          = "%s: You have been invited to complete survey %s in course %s";
-$strings['XReminderAssignmentXCourseXDue']                              = "%s: This is a simple reminder that your assignment (%s) in course %s is still due";
-$strings['XUserDetailsModified']                                        = "%s: Your user details have been modified. Please check your e-mail for more information";

+ 88 - 88
plugin/clockworksms/lang/spanish.php

@@ -1,7 +1,7 @@
 <?php
 
-$strings['plugin_title']        = "Envío de SMS";
-$strings['plugin_comment']      = "Ofrece la posibilidad de enviar SMS a celulares cuando se envían e-mails de notificación.";
+$strings['plugin_title'] = "Envío de SMS";
+$strings['plugin_comment'] = "Ofrece la posibilidad de enviar SMS a celulares cuando se envían e-mails de notificación.";
 
 $strings['api_key'] = "Clave Clockwork SMS";
 $strings['api_key_help'] = "Ésta es la clave de seguridad de su servidor Clockwork SMS. Para obtenerla, <a target='_blank' href='http://www.clockworksms.com/platforms/chamilo/'>haga click aquí</a>";
@@ -13,90 +13,90 @@ $strings['tool_enable_help'] = "Escoja si desea activar la herramienta de envío
 $strings['sms_types'] = "Enviar un SMS cuando";
 $strings['mobile_phone_number'] = "Celular (incluya sólo el código de llamada del país)";
 
-$strings['MessageWelcomeXLoginXPasswordX']                              = "Se añada un usuario a la plataforma";
-$strings['MessageXNewFileSharedCourseXByX']                             = "Un archivo se añada a dropbox";
-$strings['MessageXAccountApprovedConnectX']                             = "Se apruebe una cuenta de usuario";
-$strings['MessageXNewCourseXBeenCreatedX']                              = "Se cree un curso nuevo";
-$strings['MessageXNewUserXSubscribedCourseX']                           = "Un usuario se suscriba a un curso";
-$strings['MessageXNewCourseSuggestedTeacherX']                          = "Un profesor sugiera un curso nuevo";
-$strings['MessageXCourseOpeningRequestCodeXRegistered']                 = "Se registre una solicitud de apertura de curso";
-$strings['MessageXCourseOpeningRequestCourseCodeXApproved']             = "Se apruebe una solicitud de apertura de curso";
-$strings['MessageXRequestOpenCourseCodeXReject']                        = "Se rechace una solicitud de apertura de curso";
-$strings['MessageXCourseOpeningRequestCourseCodeX']                     = "Se requiera más información de una solicitud de apertura de curso";
-$strings['MessageXBeenSubscribedCourseX']                               = "Se le suscriba a un curso a un usuario que aún no está registrado";
-$strings['MessageXAssignmentBeenCreatedCourseX']                        = "Se cree una nueva tarea en un curso";
-$strings['MessageXAccountCreatedUpdatedLoginXPasswordX']                = "Se cree o actualice una cuenta de usuario";
-$strings['MessageXPasswordUpdatedLoginXPasswordX']                      = "Se actualice la contraseña de un usuario";
-$strings['MessageXRequestedPasswordChange']                             = "Un usuario solicite un cambio de contraseña";
-$strings['MessageXReceivedNewPersonalMessages']                         = "Se reciban mensajes personales nuevos en la bandeja de entrada o en el foro";
-$strings['MessageXNewUserXPendingApproval']                             = "Una inscripción de un nuevo usuario esté pendiente de aprobación";
-$strings['MessageXXPostedForumXCourseX']                                = "Un usuario escriba en el foro";
-$strings['MessageXXXCheckEmailConnectMoreInfo']                         = "Se envíe una notificación";
-$strings['MessageXXStudentXAnsweredTestX']                              = "Un estudiante resuelva un ejercicio de un examen";
-$strings['MessageXXStudentXAnsweredTestXOpenQuestion']                  = "Un estudiante conteste a una pregunta abierta de un examen";
-$strings['MessageXXStudentXAnsweredTestXVoiceQuestion']                 = "Un estudiante conteste a una pregunta de voz de un examen";
-$strings['MessageXXAnswerOpenQuestionTestXReviewed']                    = "Se revise una pregunta abierta de un examen";
-$strings['MessageXXNewThreadXStartedForumX']                            = "Se cree un hilo nuevo en el foro";
-$strings['MessageXXNewAnswerPostedXForumX']                             = "Se escriba una respuesta nueva en el foro";
-$strings['MessageXXNewSystemAnnouncementAdded']                         = "Se añada una notificación y el usuario no desee enviar un examen por correo electrónico";
-$strings['MessageXTestXNewSystemAnnouncementAdded']                     = "Se añada una notificación y el usuario desee enviar un examen por correo electrónico";
-$strings['MessageXXSystemAnnouncementUpdate']                           = "Se actualice una notificación y el usuario no desee enviar un examen por correo electrónico";
-$strings['MessageXTestXSystemAnnouncementUpdate']                       = "Se actualice una notificación y el usuario desee enviar un examen por correo electrónico";
-$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper']  = "Un estudiante suba su tarea y no exista una sesión (se enviará sólo a coordinadores)";
-$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper']   = "Un estudiante suba su tarea (se enviará sólo a profesores)";
-$strings['MessageXUserXUploadedAssignmentXCourseX']                     = "... y no exista una sesión (se enviará sólo a coordinadores)";
-$strings['MessageXUserXUploadedAssignmentXCheckX']                      = "... (se enviará sólo a profesores)";
-$strings['MessageXSubscribedSessionX']                                  = "Se cree o edite una sesión nueva y se suscriban a usuarios nuevos";
-$strings['MessageXSubscribedSessionXCSV']                               = "Se suscriban a usuarios nuevos desde un archivo CSV";
-$strings['MessageXUserXSuggestedBeFriends']                             = "Se reciba una invitación de amistad";
-$strings['MessageXUserXAnsweredInboxMessage']                           = "Se reciba la contestación a un mensaje en la bandeja de entrada";
-$strings['MessageXBeenInvitedJoinGroupX']                               = "Se reciba una invitación para unirse a un grupo";
-$strings['MessageXMessagesSentEditedGroupXEdited']                      = "Se actualice un mensaje en un tema de grupo";
-$strings['MessageXMessagesSentEditedGroupXAdded']                       = "Se añada un mensaje en un tema de grupo";
-$strings['MessageXBeenInvitedCompleteSurveyXCourseX']                   = "Se cree una encuesta nueva";
-$strings['MessageXReminderAssignmentXCourseXDue']                       = "Se envíe un recordatorio a los estudiantes que no hayan enviado su tarea";
-$strings['MessageXUserDetailsModified']                                 = "Se actualice información de un usuario";
+$strings['MessageWelcomeXLoginXPasswordX'] = "Se añada un usuario a la plataforma";
+$strings['MessageXNewFileSharedCourseXByX'] = "Un archivo se añada a dropbox";
+$strings['MessageXAccountApprovedConnectX'] = "Se apruebe una cuenta de usuario";
+$strings['MessageXNewCourseXBeenCreatedX'] = "Se cree un curso nuevo";
+$strings['MessageXNewUserXSubscribedCourseX'] = "Un usuario se suscriba a un curso";
+$strings['MessageXNewCourseSuggestedTeacherX'] = "Un profesor sugiera un curso nuevo";
+$strings['MessageXCourseOpeningRequestCodeXRegistered'] = "Se registre una solicitud de apertura de curso";
+$strings['MessageXCourseOpeningRequestCourseCodeXApproved'] = "Se apruebe una solicitud de apertura de curso";
+$strings['MessageXRequestOpenCourseCodeXReject'] = "Se rechace una solicitud de apertura de curso";
+$strings['MessageXCourseOpeningRequestCourseCodeX'] = "Se requiera más información de una solicitud de apertura de curso";
+$strings['MessageXBeenSubscribedCourseX'] = "Se le suscriba a un curso a un usuario que aún no está registrado";
+$strings['MessageXAssignmentBeenCreatedCourseX'] = "Se cree una nueva tarea en un curso";
+$strings['MessageXAccountCreatedUpdatedLoginXPasswordX'] = "Se cree o actualice una cuenta de usuario";
+$strings['MessageXPasswordUpdatedLoginXPasswordX'] = "Se actualice la contraseña de un usuario";
+$strings['MessageXRequestedPasswordChange'] = "Un usuario solicite un cambio de contraseña";
+$strings['MessageXReceivedNewPersonalMessages'] = "Se reciban mensajes personales nuevos en la bandeja de entrada o en el foro";
+$strings['MessageXNewUserXPendingApproval'] = "Una inscripción de un nuevo usuario esté pendiente de aprobación";
+$strings['MessageXXPostedForumXCourseX'] = "Un usuario escriba en el foro";
+$strings['MessageXXXCheckEmailConnectMoreInfo'] = "Se envíe una notificación";
+$strings['MessageXXStudentXAnsweredTestX'] = "Un estudiante resuelva un ejercicio de un examen";
+$strings['MessageXXStudentXAnsweredTestXOpenQuestion'] = "Un estudiante conteste a una pregunta abierta de un examen";
+$strings['MessageXXStudentXAnsweredTestXVoiceQuestion'] = "Un estudiante conteste a una pregunta de voz de un examen";
+$strings['MessageXXAnswerOpenQuestionTestXReviewed'] = "Se revise una pregunta abierta de un examen";
+$strings['MessageXXNewThreadXStartedForumX'] = "Se cree un hilo nuevo en el foro";
+$strings['MessageXXNewAnswerPostedXForumX'] = "Se escriba una respuesta nueva en el foro";
+$strings['MessageXXNewSystemAnnouncementAdded'] = "Se añada una notificación y el usuario no desee enviar un examen por correo electrónico";
+$strings['MessageXTestXNewSystemAnnouncementAdded'] = "Se añada una notificación y el usuario desee enviar un examen por correo electrónico";
+$strings['MessageXXSystemAnnouncementUpdate'] = "Se actualice una notificación y el usuario no desee enviar un examen por correo electrónico";
+$strings['MessageXTestXSystemAnnouncementUpdate'] = "Se actualice una notificación y el usuario desee enviar un examen por correo electrónico";
+$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper'] = "Un estudiante suba su tarea y no exista una sesión (se enviará sólo a coordinadores)";
+$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] = "Un estudiante suba su tarea (se enviará sólo a profesores)";
+$strings['MessageXUserXUploadedAssignmentXCourseX'] = "... y no exista una sesión (se enviará sólo a coordinadores)";
+$strings['MessageXUserXUploadedAssignmentXCheckX'] = "... (se enviará sólo a profesores)";
+$strings['MessageXSubscribedSessionX'] = "Se cree o edite una sesión nueva y se suscriban a usuarios nuevos";
+$strings['MessageXSubscribedSessionXCSV'] = "Se suscriban a usuarios nuevos desde un archivo CSV";
+$strings['MessageXUserXSuggestedBeFriends'] = "Se reciba una invitación de amistad";
+$strings['MessageXUserXAnsweredInboxMessage'] = "Se reciba la contestación a un mensaje en la bandeja de entrada";
+$strings['MessageXBeenInvitedJoinGroupX'] = "Se reciba una invitación para unirse a un grupo";
+$strings['MessageXMessagesSentEditedGroupXEdited'] = "Se actualice un mensaje en un tema de grupo";
+$strings['MessageXMessagesSentEditedGroupXAdded'] = "Se añada un mensaje en un tema de grupo";
+$strings['MessageXBeenInvitedCompleteSurveyXCourseX'] = "Se cree una encuesta nueva";
+$strings['MessageXReminderAssignmentXCourseXDue'] = "Se envíe un recordatorio a los estudiantes que no hayan enviado su tarea";
+$strings['MessageXUserDetailsModified'] = "Se actualice información de un usuario";
 
-$strings['WelcomeXLoginXPasswordX']                                     = "Bienvenido a %s. Éstos son sus datos de acceso: usuario: %s, contraseña: %s";
-$strings['XNewFileSharedCourseXByX']                                    = "%s: Un nuevo archivo ha sido compartido contigo en el curso %s por %s";
-$strings['XAccountApprovedConnectX']                                    = "%s: Su cuenta ha sido aprobada por un administrador. Ya puede conectarse a %s";
-$strings['XNewCourseXBeenCreatedX']                                     = "%s: Un nuevo curso (%s) ha sido creado por %s";
-$strings['XNewUserXSubscribedCourseX']                                  = "%s: Un nuevo usuario (%s) se ha suscrito a su curso (%s)";
-$strings['XNewCourseSuggestedTeacherX']                                 = "%s: Un nuevo curso ha sido sugerido por el profesor (%s). Por favor, conéctese a la página de administración para revisarlo";
-$strings['XCourseOpeningRequestCodeXRegistered']                        = "%s: Su solicitud de apertura de curso (código %s) ha sido registrada. Será informado cuando ésta sea aprobada";
-$strings['XCourseOpeningRequestCourseCodeXApproved']                    = "%s: Su solicitud de apertura de curso para el código de curso %s ha sido aprobada. Conéctese a su portal para usarlo";
-$strings['XRequestOpenCourseCodeXReject']                               = "%s: Lamentamos informarle que su solicitud de apertura de curso para el código de curso %s ha sido rechazada";
-$strings['XCourseOpeningRequestCourseCodeX']                            = "%s: Su solicitud de apertura de curso para el código de curso %s requiere más información. Compruebe su e-mail para más información";
-$strings['XBeenSubscribedCourseX']                                      = "%s: Ha sido suscrito al curso %s";
-$strings['XAssignmentBeenCreatedCourseX']                               = "%s: Una nueva tarea ha sido creada en el curso %s. Por favor, conéctese para más información";
-$strings['XAccountCreatedUpdatedLoginXPasswordX']                       = "%s: Su cuenta ha sido creada o actualizada. Ya puede conectarse como %s, contraseña: %s";
-$strings['XPasswordUpdatedLoginXPasswordX']                             = "%s: Su contraseña ha sido actualizada. Ya puede conectarse como %s, contraseña: %s";
-$strings['XRequestedPasswordChange']                                    = "%s: Ha solicitado un cambio de contraseña. Por favor, compruebe su e-mail para más información";
-$strings['XReceivedNewPersonalMessages']                                = "%s: Ha recibido mensajes personales nuevos en su bandeja de entrada o en el foro. Por favor, compruebe su e-mail para más información";
-$strings['XNewUserXPendingApproval']                                    = "%s: Una inscripción de un nuevo usuario (%s) está pendiente de su aprobación. Por favor, conéctese al panel de administración para revisarla";
-$strings['XXPostedForumXCourseX']                                       = "%s: %s acaba de escribir en el foro %s del curso %s";
-$strings['XXXCheckEmailConnectMoreInfo']                                = "%s: %s: %s. Compruebe su e-mail o conéctese para más información";
-$strings['XXStudentXAnsweredTestX']                                     = "%s: %s: El estudiante %s acaba de contestar al test %s";
-$strings['XXStudentXAnsweredTestXOpenQuestion']                         = "%s: %s: El estudiante %s contestó a la pregunta abierta del test %s. Por favor, conéctese para revisarla";
-$strings['XXStudentXAnsweredTestXVoiceQuestion']                        = "%s: %s: El estudiante %s contestó a la pregunta de voz del test %s. Por favor, conéctese para revisarla";
-$strings['XXAnswerOpenQuestionTestXReviewed']                           = "%s: %s: Su respuesta a la pregunta abierta en el test %s ha sido revisada.";
-$strings['XXNewThreadXStartedForumX']                                   = "%s: %s: Se ha comenzado un nuevo hilo (%s) en el foro %s";
-$strings['XXNewAnswerPostedXForumX']                                    = "%s: %s: Se ha escrito una nueva respuesta a (%s) en el foro %s";
-$strings['XXNewSystemAnnouncementAdded']                                = "%s: %s";
-$strings['XTestXNewSystemAnnouncementAdded']                            = "%s (prueba): %s";
-$strings['XXSystemAnnouncementUpdate']                                  = "%s: %s (actualización)";
-$strings['XTestXSystemAnnouncementUpdate']                              = "%s (prueba): %s";
-$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper']         = "%s: El usuario %s subió la tarea %s al curso %s";
-$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper']          = "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
-$strings['XUserXUploadedAssignmentXCourseX']                            = "%s: El usuario %s subió la tarea %s al curso %s";
-$strings['XUserXUploadedAssignmentXCheckX']                             = "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
-$strings['XSubscribedSessionX']                                         = "%s: Ha sido suscrito a la sesión %s";
-$strings['XSubscribedSessionXCSV']                                      = "%s: Ha sido suscrito a la sesión %s";
-$strings['XUserXSuggestedBeFriends']                                    = "%s: El usuario %s le sugirió que podrían ser amigos. Compruebe su bandeja de entrada o su e-mail para más detalles";
-$strings['XUserXAnsweredInboxMessage']                                  = "%s: El usuario acaba de contestar a su mensaje de la bandeja de entrada";
-$strings['XBeenInvitedJoinGroupX']                                      = "%s: Ha sido invitado a unirse al grupo %s. Compruebe su bandeja de entrada para más detalles";
-$strings['XMessagesSentEditedGroupXEdited']                             = "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
-$strings['XMessagesSentEditedGroupXAdded']                              = "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
-$strings['XBeenInvitedCompleteSurveyXCourseX']                          = "%s: Ha sido invitado a completar la encuesta %s del curso %s";
-$strings['XReminderAssignmentXCourseXDue']                              = "%s: Se le recuerda que su tarea (%s) del curso %s aún está pendiente";
-$strings['XUserDetailsModified']                                        = "%s: Su información de usuario ha sido modificada. Compruebe su e-mail para más información";
+$strings['WelcomeXLoginXPasswordX'] = "Bienvenido a %s. Éstos son sus datos de acceso: usuario: %s, contraseña: %s";
+$strings['XNewFileSharedCourseXByX'] = "%s: Un nuevo archivo ha sido compartido contigo en el curso %s por %s";
+$strings['XAccountApprovedConnectX'] = "%s: Su cuenta ha sido aprobada por un administrador. Ya puede conectarse a %s";
+$strings['XNewCourseXBeenCreatedX'] = "%s: Un nuevo curso (%s) ha sido creado por %s";
+$strings['XNewUserXSubscribedCourseX'] = "%s: Un nuevo usuario (%s) se ha suscrito a su curso (%s)";
+$strings['XNewCourseSuggestedTeacherX'] = "%s: Un nuevo curso ha sido sugerido por el profesor (%s). Por favor, conéctese a la página de administración para revisarlo";
+$strings['XCourseOpeningRequestCodeXRegistered'] = "%s: Su solicitud de apertura de curso (código %s) ha sido registrada. Será informado cuando ésta sea aprobada";
+$strings['XCourseOpeningRequestCourseCodeXApproved'] = "%s: Su solicitud de apertura de curso para el código de curso %s ha sido aprobada. Conéctese a su portal para usarlo";
+$strings['XRequestOpenCourseCodeXReject'] = "%s: Lamentamos informarle que su solicitud de apertura de curso para el código de curso %s ha sido rechazada";
+$strings['XCourseOpeningRequestCourseCodeX'] = "%s: Su solicitud de apertura de curso para el código de curso %s requiere más información. Compruebe su e-mail para más información";
+$strings['XBeenSubscribedCourseX'] = "%s: Ha sido suscrito al curso %s";
+$strings['XAssignmentBeenCreatedCourseX'] = "%s: Una nueva tarea ha sido creada en el curso %s. Por favor, conéctese para más información";
+$strings['XAccountCreatedUpdatedLoginXPasswordX'] = "%s: Su cuenta ha sido creada o actualizada. Ya puede conectarse como %s, contraseña: %s";
+$strings['XPasswordUpdatedLoginXPasswordX'] = "%s: Su contraseña ha sido actualizada. Ya puede conectarse como %s, contraseña: %s";
+$strings['XRequestedPasswordChange'] = "%s: Ha solicitado un cambio de contraseña. Por favor, compruebe su e-mail para más información";
+$strings['XReceivedNewPersonalMessages'] = "%s: Ha recibido mensajes personales nuevos en su bandeja de entrada o en el foro. Por favor, compruebe su e-mail para más información";
+$strings['XNewUserXPendingApproval'] = "%s: Una inscripción de un nuevo usuario (%s) está pendiente de su aprobación. Por favor, conéctese al panel de administración para revisarla";
+$strings['XXPostedForumXCourseX'] = "%s: %s acaba de escribir en el foro %s del curso %s";
+$strings['XXXCheckEmailConnectMoreInfo'] = "%s: %s: %s. Compruebe su e-mail o conéctese para más información";
+$strings['XXStudentXAnsweredTestX'] = "%s: %s: El estudiante %s acaba de contestar al test %s";
+$strings['XXStudentXAnsweredTestXOpenQuestion'] = "%s: %s: El estudiante %s contestó a la pregunta abierta del test %s. Por favor, conéctese para revisarla";
+$strings['XXStudentXAnsweredTestXVoiceQuestion'] = "%s: %s: El estudiante %s contestó a la pregunta de voz del test %s. Por favor, conéctese para revisarla";
+$strings['XXAnswerOpenQuestionTestXReviewed'] = "%s: %s: Su respuesta a la pregunta abierta en el test %s ha sido revisada.";
+$strings['XXNewThreadXStartedForumX'] = "%s: %s: Se ha comenzado un nuevo hilo (%s) en el foro %s";
+$strings['XXNewAnswerPostedXForumX'] = "%s: %s: Se ha escrito una nueva respuesta a (%s) en el foro %s";
+$strings['XXNewSystemAnnouncementAdded'] = "%s: %s";
+$strings['XTestXNewSystemAnnouncementAdded'] = "%s (prueba): %s";
+$strings['XXSystemAnnouncementUpdate'] = "%s: %s (actualización)";
+$strings['XTestXSystemAnnouncementUpdate'] = "%s (prueba): %s";
+$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper'] = "%s: El usuario %s subió la tarea %s al curso %s";
+$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] = "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
+$strings['XUserXUploadedAssignmentXCourseX'] = "%s: El usuario %s subió la tarea %s al curso %s";
+$strings['XUserXUploadedAssignmentXCheckX'] = "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
+$strings['XSubscribedSessionX'] = "%s: Ha sido suscrito a la sesión %s";
+$strings['XSubscribedSessionXCSV'] = "%s: Ha sido suscrito a la sesión %s";
+$strings['XUserXSuggestedBeFriends'] = "%s: El usuario %s le sugirió que podrían ser amigos. Compruebe su bandeja de entrada o su e-mail para más detalles";
+$strings['XUserXAnsweredInboxMessage'] = "%s: El usuario acaba de contestar a su mensaje de la bandeja de entrada";
+$strings['XBeenInvitedJoinGroupX'] = "%s: Ha sido invitado a unirse al grupo %s. Compruebe su bandeja de entrada para más detalles";
+$strings['XMessagesSentEditedGroupXEdited'] = "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
+$strings['XMessagesSentEditedGroupXAdded'] = "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
+$strings['XBeenInvitedCompleteSurveyXCourseX'] = "%s: Ha sido invitado a completar la encuesta %s del curso %s";
+$strings['XReminderAssignmentXCourseXDue'] = "%s: Se le recuerda que su tarea (%s) del curso %s aún está pendiente";
+$strings['XUserDetailsModified'] = "%s: Su información de usuario ha sido modificada. Compruebe su e-mail para más información";

+ 41 - 42
plugin/clockworksms/lib/clockworksms.lib.php

@@ -72,10 +72,15 @@ class Clockworksms implements SmsPluginLibraryInterface
     public function getMobilePhoneNumberById($userId)
     {
         $mobilePhoneNumberExtraField = new ExtraField('user');
-        $mobilePhoneNumberExtraField = $mobilePhoneNumberExtraField->get_handler_field_info_by_field_variable('mobile_phone_number');
+        $mobilePhoneNumberExtraField = $mobilePhoneNumberExtraField->get_handler_field_info_by_field_variable(
+            'mobile_phone_number'
+        );
 
         $mobilePhoneNumberExtraFieldValue = new ExtraFieldValue('user');
-        $mobilePhoneNumberExtraFieldValue = $mobilePhoneNumberExtraFieldValue->get_values_by_handler_and_field_id($userId, $mobilePhoneNumberExtraField['id']);
+        $mobilePhoneNumberExtraFieldValue = $mobilePhoneNumberExtraFieldValue->get_values_by_handler_and_field_id(
+            $userId,
+            $mobilePhoneNumberExtraField['id']
+        );
 
         return $mobilePhoneNumberExtraFieldValue['value'];
     }
@@ -96,61 +101,46 @@ class Clockworksms implements SmsPluginLibraryInterface
     {
         $trimmedKey = trim(CONFIG_SECURITY_API_KEY);
         if (!empty($trimmedKey)) {
-            $phoneExists = array_key_exists("mobilePhoneNumber", $additionalParameters);
+            $phoneExists = array_key_exists('mobilePhoneNumber', $additionalParameters);
             $to = $phoneExists ? $additionalParameters['mobilePhoneNumber'] : $this->getMobilePhoneNumberById($additionalParameters['userId']);
 
             $message = array(
-                "to" => $to,
-                "message" => $this->getSms($additionalParameters)
+                'to' => $to,
+                'message' => $this->getSms($additionalParameters)
             );
 
             if (!empty($message['message'])) {
-                $result = $this->api->send($message);
-
-                // Commented for future message logging / tracking purposes
-                /*if ($result["success"]) {
-                    echo "Message sent - ID: " . $result["id"];
-                } else {
-                    echo "Message failed - Error: " . $result["error_message"];
-                }*/
+                $this->api->send($message);
             }
-
         }
     }
 
     /**
      * buildSms (builds an SMS from a template and data)
-     * @param   object  ClockworksmsPlugin object
-     * @param   object  Template object
-     * @param   string  Template file name
-     * @param   string  Text key from lang file
-     * @param   array   Data to fill message variables (if any)
-     * @return  object  Template object with message property updated
+     * @param ClockworksmsPlugin $plugin
+     * @param Template $tpl
+     * @param string  Template file name
+     * @param string $messageKey Text key from lang file
+     * @param array $parameters  Data to fill message variables (if any)
+     * @return string
      */
-    public function buildSms($plugin, $tpl, $templateName, $messageKey, $parameters = null)
-    {
-        $result = Database::select(
-            'selected_value',
-            'settings_current',
-            array(
-                'where'=> array('variable = ?' => array('clockworksms_message'.$messageKey))
-            )
-        );
-
-        //if (empty($result)) {
-        if (0) {
-            $tpl->assign('message', '');
-        } else {
-            $templatePath = 'clockworksms/sms_templates/';
-            $content = $tpl->fetch($templatePath.$templateName);
-            $message = $plugin->get_lang($messageKey);
-            if ($parameters !== null) {
-                $message = vsprintf($message, $parameters);
-            }
-            $tpl->assign('message', $message);
+    public function buildSms(
+        $plugin,
+        $tpl,
+        $templateName,
+        $messageKey,
+        $parameters = []
+    ) {
+        // Send direct message with out using plugin get_lang
+        if (isset($parameters['direct_message'])) {
+            return $parameters['direct_message'];
         }
 
-        return $tpl->params['message'];
+        $message = $plugin->get_lang($messageKey);
+        if ($parameters !== null) {
+            $message = vsprintf($message, $parameters);
+        }
+        return $message;
     }
 
     /**
@@ -321,6 +311,15 @@ class Clockworksms implements SmsPluginLibraryInterface
                     )
                 );
                 break;
+            case SmsPlugin::CERTIFICATE_NOTIFICATION:
+                return $this->buildSms(
+                    $plugin,
+                    $tpl,
+                    'certificate_notification.tpl',
+                    '',
+                    $additionalParameters
+                );
+                break;
             // Message types to be implemented. Fill the array parameter with arguments.
             /*case SmsPlugin::ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD:
                 return $this->buildSms(

+ 1 - 0
plugin/clockworksms/sms_templates/certificate_notification.tpl

@@ -0,0 +1 @@
+{{ message }}

+ 0 - 3
plugin/clockworksms/uninstall.php

@@ -9,8 +9,5 @@
  * @package chamilo.plugin.clockworksms
  * @author  Imanol Losada <imanol.losada@beeznest.com>
  */
-/**
- * Queries
- */
 require_once __DIR__.'/config.php';
 ClockworksmsPlugin::create()->uninstall();