Browse Source

Merge 1.11.x

Julio 8 years ago
parent
commit
3097d30dc9
33 changed files with 302 additions and 4097 deletions
  1. 5 1
      app/Migrations/Schema/V111/Version111.php
  2. 0 570
      main/admin/add_users_to_group.php
  3. 19 11
      main/admin/dashboard_add_users_to_user.php
  4. 0 181
      main/admin/group_add.php
  5. 0 176
      main/admin/group_edit.php
  6. 0 407
      main/admin/group_list.php
  7. 23 0
      main/admin/user_edit.php
  8. 51 27
      main/admin/user_information.php
  9. 2 2
      main/course_description/listing.php
  10. 17 1
      main/exercice/exercise.class.php
  11. 8 8
      main/exercice/exercise_submit.php
  12. 24 3
      main/exercice/overview.php
  13. 2 2
      main/exercice/result.php
  14. 1 0
      main/inc/lib/api.lib.php
  15. 0 8
      main/inc/lib/database.constants.inc.php
  16. 27 0
      main/inc/lib/exercise.lib.php
  17. 1 0
      main/inc/lib/export.lib.inc.php
  18. 0 1502
      main/inc/lib/group_portal_manager.lib.php
  19. 1 1
      main/inc/lib/template.lib.php
  20. 1 1
      main/inc/lib/urlmanager.lib.php
  21. 99 23
      main/inc/lib/usermanager.lib.php
  22. 0 555
      main/install/install.lib.php
  23. 5 5
      main/social/invitations.php
  24. 1 15
      main/webservices/registration.soap.php
  25. 2 2
      plugin/advanced_subscription/ajax/advanced_subscription.ajax.php
  26. 1 1
      plugin/advanced_subscription/test/mails.php
  27. 1 0
      plugin/bbb/lib/bbb.lib.php
  28. 9 1
      src/Chamilo/CoreBundle/Composer/ScriptHandler.php
  29. 0 125
      src/Chamilo/CoreBundle/Entity/GroupRelGroup.php
  30. 0 95
      src/Chamilo/CoreBundle/Entity/GroupRelTag.php
  31. 0 125
      src/Chamilo/CoreBundle/Entity/GroupRelUser.php
  32. 0 245
      src/Chamilo/CoreBundle/Entity/Groups.php
  33. 2 4
      tests/scripts/userfields_to_groups.php

+ 5 - 1
app/Migrations/Schema/V111/Version111.php

@@ -131,8 +131,12 @@ class Version111 extends AbstractMigrationChamilo
         $this->addSql('UPDATE track_e_default SET default_date = NULL WHERE default_date = "0000-00-00 00:00:00"');
         $this->addSql('ALTER TABLE track_e_default CHANGE default_date default_date DATETIME');
 
-
         $this->addSql('ALTER TABLE track_e_exercises CHANGE expired_time_control expired_time_control DATETIME');
+
+        $this->addSql('DROP TABLE group_rel_user');
+        $this->addSql('DROP TABLE group_rel_tag');
+        $this->addSql('DROP TABLE group_rel_group');
+        $this->addSql('DROP TABLE groups');
     }
 
     /**

+ 0 - 570
main/admin/add_users_to_group.php

@@ -1,570 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-/**
-*	@package chamilo.admin
-*/
-// resetting the course id
-$cidReset = true;
-
-// including some necessary files
-require_once '../inc/global.inc.php';
-
-// setting the section (for the tabs)
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// Access restrictions
-api_protect_admin_script(true);
-
-// setting breadcrumbs
-$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'group_list.php','name' => get_lang('GroupList'));
-
-// Database Table Definitions
-$tbl_group			= Database::get_main_table(TABLE_MAIN_GROUP);
-$tbl_user			= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_group_rel_user	= Database::get_main_table(TABLE_USERGROUP_REL_USER);
-$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-$needle = null;
-$user_anonymous = api_get_anonymous_id();
-
-// setting the name of the tool
-$tool_name = get_lang('SubscribeUsersToGroup');
-$group_id = intval($_GET['id']);
-$without_user_id = null;
-
-$add_type = 'multiple';
-if (isset($_REQUEST['add_type']) && $_REQUEST['add_type'] != '') {
-    $add_type = Security::remove_XSS($_REQUEST['add_type']);
-}
-
-//checking for extra field with filter on
-$xajax = new xajax();
-$xajax->registerFunction('search_users');
-function search_users($needle, $type, $relation_type)
-{
-    global $tbl_user, $tbl_user_rel_access_url, $tbl_group_rel_user, $group_id;
-    $xajax_response = new xajaxResponse();
-    $return = $return_origin = $return_destination = '';
-    $without_user_id = $without_user_id = $condition_relation = '';
-
-    if (!empty($group_id) && !empty($relation_type)) {
-        $group_id = intval($group_id);
-        $relation_type = intval($relation_type);
-        // get user_id from relation type and group id
-        $sql = "SELECT user_id FROM $tbl_group_rel_user
-                WHERE group_id = '$group_id'
-                AND relation_type IN (".GROUP_USER_PERMISSION_ADMIN.",".GROUP_USER_PERMISSION_READER.",".GROUP_USER_PERMISSION_PENDING_INVITATION.",".GROUP_USER_PERMISSION_MODERATOR.", ".GROUP_USER_PERMISSION_HRM.") ";
-        $res = Database::query($sql);
-        $user_ids = array();
-        if (Database::num_rows($res) > 0) {
-            while ($row = Database::fetch_row($res)) {
-                $user_ids[] = $row[0];
-            }
-            $without_user_id = " AND user.user_id NOT IN(".implode(',', $user_ids).") ";
-        }
-
-        $condition_relation = " AND groups.relation_type = '$relation_type' ";
-
-        // data for destination user list
-        $sql = "SELECT user.user_id, user.username, user.lastname, user.firstname
-                FROM $tbl_group_rel_user groups
-                INNER JOIN  $tbl_user user ON user.user_id = groups.user_id
-                WHERE groups.group_id = '$group_id' $condition_relation ";
-
-        $rs_destination = Database::query($sql);
-        if (Database::num_rows($rs_destination) > 0) {
-            $return_destination .= '<select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
-            while ($row = Database::fetch_array($rs_destination)) {
-                $person_name = api_get_person_name($row['firstname'], $row['lastname']);
-                $return_destination .= '<option value="'.$row['user_id'].'">'.
-                    $person_name.' ('.$row['username'].')</option>';
-            }
-            $return_destination .= '</select>';
-        } else {
-            $return_destination .= '<select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;"></select>';
-        }
-        $xajax_response->addAssign('ajax_destination_list','innerHTML', api_utf8_encode($return_destination));
-    } else {
-        $return_destination .= '<select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;"></select>';
-        $xajax_response->addAssign('ajax_destination_list','innerHTML', api_utf8_encode($return_destination));
-
-        if ($type == 'single') {
-            $return.= '';
-            $xajax_response->addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));
-        } else {
-            $return_origin .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;"></select>';
-            $xajax_response->addAssign('ajax_origin_list_multiple', 'innerHTML', api_utf8_encode($return_origin));
-        }
-    }
-
-    if (!empty($needle) && !empty($type)) {
-        $user_anonymous = api_get_anonymous_id();
-        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-        if ($type == 'single') {
-            if (!empty($group_id) && !empty($relation_type)) {
-                // search users where username or firstname or lastname begins likes $needle
-                $sql = "SELECT user_id, username, lastname, firstname
-                        FROM $tbl_user user
-                        WHERE (username LIKE '$needle%' OR firstname LIKE '$needle%' OR lastname LIKE '$needle%')
-                        AND user_id<>'$user_anonymous' $without_user_id $order_clause LIMIT 11";
-                if (api_is_multiple_url_enabled()) {
-                    $access_url_id = api_get_current_access_url_id();
-                    if ($access_url_id != -1) {
-                        $sql = "SELECT user.user_id, username, lastname, firstname FROM $tbl_user user
-                                INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=user.user_id)
-                                WHERE access_url_id = '$access_url_id'  AND (username LIKE '$needle%' OR firstname LIKE '$needle%' OR lastname LIKE '$needle%')
-                                AND user.user_id<>'$user_anonymous' $without_user_id $order_clause LIMIT 11 ";
-                    }
-                }
-                $rs_single = Database::query($sql);
-                $i=0;
-                while ($user = Database :: fetch_array($rs_single)) {
-                    $i++;
-                    if ($i<=10) {
-                        $person_name = api_get_person_name($user['firstname'], $user['lastname']);
-                        $return .= '<a href="javascript: void(0);" onclick="javascript: add_user(\''.$user['user_id'].'\',\''.$person_name.' ('.$user['username'].')'.'\')">'.$person_name.' ('.$user['username'].')</a><br />';
-                    } else {
-                        $return .= '...<br />';
-                    }
-                }
-                $xajax_response->addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));
-            } else {
-                $xajax_response->addAlert(get_lang('YouMustChooseARelationType'));
-                $xajax_response->addClear('user_to_add', 'value');
-            }
-
-        } else {
-            // multiple
-            if (!empty($group_id) && !empty($relation_type)) {
-                $sql = "SELECT user_id, username, lastname, firstname FROM $tbl_user user
-                        WHERE ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND user_id<>'$user_anonymous' $without_user_id $order_clause ";
-                if (api_is_multiple_url_enabled()) {
-                    $access_url_id = api_get_current_access_url_id();
-                    if ($access_url_id != -1) {
-                        $sql = "SELECT user.user_id, username, lastname, firstname
-                                FROM $tbl_user user
-                                INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=user.user_id)
-                                WHERE
-                                    access_url_id = '$access_url_id' AND
-                                    ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND
-                                    user.user_id<>'$user_anonymous' $without_user_id $order_clause ";
-                    }
-                }
-
-                $rs_multiple = Database::query($sql);
-                $return_origin .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
-                while ($user = Database :: fetch_array($rs_multiple)) {
-                    $person_name = api_get_person_name($user['firstname'], $user['lastname']);
-                    $return_origin .= '<option value="'.$user['user_id'].'">'.
-                        $person_name.' ('.$user['username'].')</option>';
-                }
-                $return_origin .= '</select>';
-                $xajax_response->addAssign('ajax_origin_list_multiple', 'innerHTML', api_utf8_encode($return_origin));
-            }
-        }
-    }
-
-    return $xajax_response;
-}
-
-$xajax->processRequests();
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script>
-function add_user (code, content) {
-	destination = document.getElementById("destination_users");
-	for (i=0;i<destination.length;i++) {
-		if (destination.options[i].text == content) {
-            return false;
-		}
-	}
-
-	destination.options[destination.length] = new Option(content,code);
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-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;
-		}
-	}
-}
-
-function validate_filter() {
-    document.formulaire.add_type.value = \''.$add_type.'\';
-    document.formulaire.form_sent.value=0;
-    document.formulaire.submit();
-}
-</script>';
-
-$form_sent = 0;
-$errorMsg = $firstLetterUser = $firstLetterSession='';
-$UserList = $SessionList = array();
-$users = $sessions = array();
-$noPHP_SELF = true;
-$group_info = GroupPortalManager::get_group_data($group_id);
-$group_name = $group_info['name'];
-
-Display::display_header($group_name);
-
-if (isset($_POST['form_sent']) && $_POST['form_sent']) {
-    $form_sent = $_POST['form_sent'];
-    $firstLetterUser = isset($_POST['firstLetterUser']) ? $_POST['firstLetterUser'] : null;
-    $UserList = $_POST['sessionUsersList'];
-    $group_id = intval($_POST['id']);
-    $relation_type = intval($_POST['relation']);
-
-    if (!is_array($UserList)) {
-        $UserList = array();
-    }
-
-    if ($form_sent == 1) {
-        $users_by_group = GroupPortalManager::get_users_by_group($group_id, null, array($relation_type));
-        $user_id_relation    = array_keys($users_by_group);
-        $user_relation_diff  = array_diff($user_id_relation, $UserList);
-        if (!empty($user_relation_diff)) {
-            foreach ($user_relation_diff as $user_id) {
-                GroupPortalManager::delete_user_rel_group($user_id, $group_id);
-            }
-        }
-        $result = GroupPortalManager::add_users_to_groups($UserList, array($group_id), $relation_type);
-        Display :: display_confirmation_message(get_lang('UsersEdited'));
-    }
-}
-
-$nosessionUsersList = $sessionUsersList = array();
-$ajax_search = $add_type == 'unique' ? true : false;
-
-$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-
-if ($ajax_search) {
-
-    // data for destination list
-    if (isset($_POST['id']) && isset($_POST['relation'])) {
-        // data for destination user list
-        $id = intval($_POST['id']);
-        $relation_type = intval($_POST['relation']);
-        $condition_relation = " AND groups.relation_type = '$relation_type' ";
-        $sql = "SELECT user.user_id, user.username, user.lastname, user.firstname
-                FROM $tbl_group_rel_user groups
-                INNER JOIN  $tbl_user user ON user.user_id = groups.user_id
-                WHERE groups.group_id = '$id' $condition_relation ";
-        $rs_destination = Database::query($sql);
-        if (Database::num_rows($rs_destination) > 0) {
-            while ($row_destination_list = Database::fetch_array($rs_destination)) {
-                $sessionUsersList[$row_destination_list['user_id']] = $row_destination_list ;
-            }
-        }
-    }
-} else {
-
-    $many_users = false;
-    $sql = "SELECT count(user_id) FROM $tbl_user user
-            WHERE ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND
-            user_id<>'$user_anonymous' $without_user_id ";
-
-    if (api_is_multiple_url_enabled()) {
-        $access_url_id = api_get_current_access_url_id();
-        if ($access_url_id != -1) {
-            $sql = "SELECT count(user.user_id) FROM $tbl_user user
-                    INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=user.user_id)
-                    WHERE
-                        access_url_id = '$access_url_id' AND
-                        ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND
-                        user.user_id<>'$user_anonymous' $without_user_id ";
-        }
-    }
-    $rs_count  = Database::query($sql);
-    $row_count = 0;
-    if (Database::num_rows($rs_count)) {
-        $row_count = Database::fetch_row($rs_count);
-        $row_count = $row_count[0];
-    }
-
-    if ($row_count > 2) {
-        $many_users = true;
-    }
-
-    // data for origin list
-    if (isset($_GET['id'])) {
-        $id = intval($_GET['id']);
-        $needle = isset($_POST['firstLetterUser']) ? Database::escape_string($_POST['firstLetterUser']) : null;
-        $needle = api_convert_encoding($needle, $charset, 'utf-8');
-        $user_anonymous = api_get_anonymous_id();
-        // get user_id from relation type and group id
-        $sql = "SELECT user_id FROM $tbl_group_rel_user
-                WHERE group_id = $id
-                AND relation_type IN (".GROUP_USER_PERMISSION_ADMIN.", ".GROUP_USER_PERMISSION_READER.",".GROUP_USER_PERMISSION_PENDING_INVITATION.",".GROUP_USER_PERMISSION_MODERATOR.", ".GROUP_USER_PERMISSION_HRM.") ";
-        $res = Database::query($sql);
-        $user_ids = array();
-        if (Database::num_rows($res) > 0) {
-            while ($row = Database::fetch_row($res)) {
-                $user_ids[] = $row[0];
-            }
-            $without_user_id = " AND user.user_id NOT IN(".implode(',', $user_ids).") ";
-        }
-
-        $sql = "SELECT user_id, username, lastname, firstname FROM $tbl_user user
-                WHERE ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND user_id<>'$user_anonymous' $without_user_id $order_clause ";
-        if (api_is_multiple_url_enabled()) {
-            $access_url_id = api_get_current_access_url_id();
-            if ($access_url_id != -1) {
-                $sql = "SELECT user.user_id, username, lastname, firstname FROM $tbl_user user
-                        INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=user.user_id)
-                        WHERE access_url_id = '$access_url_id'
-                        AND ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%'
-                        AND user.user_id<>'$user_anonymous' $without_user_id $order_clause ";
-            }
-        }
-        $rs_origin_list = Database::query($sql);
-        while ($row_origin_list = Database::fetch_array($rs_origin_list)) {
-            $nosessionUsersList[$row_origin_list['user_id']] = $row_origin_list;
-        }
-    }
-
-    // data for destination list
-    if (isset($_POST['id']) && isset($_POST['relation'])) {
-        // data for destination user list
-        $id = intval($_POST['id']);
-        $relation_type = intval($_POST['relation']);
-        $condition_relation = " AND groups.relation_type = '$relation_type' ";
-
-        $sql = "SELECT user.user_id, user.username, user.lastname, user.firstname
-                FROM $tbl_group_rel_user groups
-                INNER JOIN  $tbl_user user ON user.user_id = groups.user_id
-                WHERE groups.group_id = '$id' $condition_relation ";
-        $rs_destination = Database::query($sql);
-        if (Database::num_rows($rs_destination) > 0) {
-            while ($row_destination_list = Database::fetch_array($rs_destination)) {
-                $sessionUsersList[$row_destination_list['user_id']] = $row_destination_list ;
-            }
-        }
-    }
-}
-
-if ($add_type == 'multiple') {
-    $link_add_type_unique = '<a href="'.api_get_self().'?id='.$group_id.'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
-    $link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple');
-} else {
-    $link_add_type_unique = Display::return_icon('single.gif').get_lang('SessionAddTypeUnique');
-    $link_add_type_multiple = '<a href="'.api_get_self().'?id='.$group_id.'&add_type=multiple">'.Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').'</a>';
-}
-?>
-
-<div class="actions">
-	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
-</div>
-
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?id=<?php echo $group_id; ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?>>
-<?php echo '<legend>'.$tool_name.' ('.$group_info['name'].')</legend>'; ?>
-<?php if ($add_type=='multiple') { ?>
-<select name="relation" id="relation" onchange="xajax_search_users(document.getElementById('firstLetterUser').value,'multiple',this.value)">
-<?php } else { ?>
-<select name="relation" id="relation" onchange="xajax_search_users(document.getElementById('user_to_add').value,'single',this.value);">
-<?php } ?>
-<option value=""><?php echo get_lang('SelectARelationType')?></option>
-<option value="<?php echo GROUP_USER_PERMISSION_ADMIN ?>" <?php echo ((isset($_POST['relation']) && $_POST['relation']==GROUP_USER_PERMISSION_ADMIN)?'selected=selected':'') ?> > <?php echo get_lang('Admin') ?></option>
-<option value="<?php echo GROUP_USER_PERMISSION_READER ?>" <?php echo ((isset($_POST['relation']) && $_POST['relation']==GROUP_USER_PERMISSION_READER)?'selected=selected':'') ?> > <?php echo get_lang('Reader') ?></option>
-<option value="<?php echo GROUP_USER_PERMISSION_PENDING_INVITATION ?>" <?php echo ((isset($_POST['relation']) && $_POST['relation']==GROUP_USER_PERMISSION_PENDING_INVITATION)?'selected=selected':'') ?> > <?php echo get_lang('PendingInvitation') ?></option>
-<option value="<?php echo GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER ?>" <?php echo ((isset($_POST['relation']) && $_POST['relation']==GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER)?'selected=selected':'') ?> > <?php echo get_lang('WaitingForAdminResponse') ?></option>
-<option value="<?php echo GROUP_USER_PERMISSION_MODERATOR ?>" <?php echo ((isset($_POST['relation']) && $_POST['relation']==GROUP_USER_PERMISSION_MODERATOR)?'selected=selected':'') ?> > <?php echo get_lang('Moderator') ?></option>
-<option value="<?php echo GROUP_USER_PERMISSION_HRM ?>" <?php echo ((isset($_POST['relation']) && $_POST['relation']==GROUP_USER_PERMISSION_HRM)?'selected=selected':'') ?> > <?php echo get_lang('Drh') ?></option>
-</select>
-<input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="id" value="<?php echo $group_id ?>" />
-<input type="hidden" name="add_type" value="<?php echo $add_type ?>" />
-
-<?php
-if (!empty($errorMsg)) {
-    Display::display_normal_message($errorMsg);
-}
-?>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-<tr>
-  <td align="center"><b><?php echo get_lang('UserListInPlatform') ?> :</b>
-  </td>
-  <td>&nbsp;</td>
-  <td align="center"><b><?php echo get_lang('UsersInGroup') ?> :</b></td>
-</tr>
-<?php if ($add_type=='multiple') { ?>
-<tr>
-<td align="center">
-<?php echo get_lang('FirstLetterUser'); ?> :
-	<div id="firstLetter">
-        <select name="firstLetterUser" id="firstLetterUser" onchange = "xajax_search_users(this.value,'multiple',document.getElementById('relation').value)" >
-            <option value = "%"><?php echo get_lang('All') ?></option>
-              <?php
-                $selected_letter = isset($_POST['firstLetterUser']) ? $_POST['firstLetterUser'] : null;
-                echo Display :: get_alphabet_options($selected_letter);
-              ?>
-	     </select>
-    </div>
-</td>
-<td align="center">&nbsp;</td>
-</tr>
-<?php } ?>
-<tr>
-  <td align="center">
-  <div id="content_source">
-  	  <?php
-  	  if (!($add_type=='multiple')) {
-  	  	?>
-		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,'single',document.getElementById('relation').value)" />
-		<div id="ajax_list_users_single"></div>
-		<?php
-  	  } else {
-  	  ?>
-  	  <div id="ajax_origin_list_multiple">
-	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">
-		<?php
-		if (!empty($nosessionUsersList)) {
-			foreach($nosessionUsersList as $enreg) {
-			?>
-				<option value="<?php echo $enreg['user_id']; ?>"  > <?php echo $enreg['firstname'].' '.$enreg['lastname'].' ('.$enreg['username'].')'; ?></option>
-			<?php
-			}
-		}
-		?>
-	  </select>
-	  </div>
-	<?php
-  	  }
-  	  unset($nosessionUsersList);
-  	 ?>
-  </div>
-  </td>
-  <td width="10%" valign="middle" align="center">
-  <?php
-  if ($ajax_search) {
-  ?>
-    <button class="btn btn-default" type="button" onclick="remove_item(document.getElementById('destination_users'))" ><em class="fa fa-arrow-left"></em></button>
-  <?php
-  } else {
-  ?>
-  	<button class="btn btn-default" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))"><em class="fa fa-arrow-right"></em></button>
-	<br /><br />
-	<button class="btn btn-default" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))"><em class="fa fa-arrow-left"></em></button>
-	<?php
-  }
-  ?>
-	<br /><br /><br /><br /><br />
-  </td>
-  <td align="center">
-  <div id="ajax_destination_list">
-  <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;">
-	<?php
-	if (!empty($sessionUsersList)) {
-		foreach($sessionUsersList as $enreg) { ?>
-			<option value="<?php echo $enreg['user_id']; ?>">
-                <?php echo $enreg['firstname'].' '.$enreg['lastname'].' ('.$enreg['username'].')'; ?>
-            </option>
-	<?php }
-	} unset($sessionUsersList);
-    ?>
-  </select>
-  </div>
-  </td>
-</tr>
-<tr>
-	<td colspan="3" align="center">
-		<br />
-		<?php
-		echo '<button class="btn btn-success" type="button" value="" onclick="valide()" ><em class="fa fa-floppy-o"></em> '.get_lang('SubscribeUsersToGroup').'</button>';
-		?>
-	</td>
-</tr>
-</table>
-</form>
-
-<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);
-
-}
-
-function sortOptions(options) {
-	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;
-}
-
-function valide() {
-	var relation_select = document.getElementById('relation');
-	if (relation_select && relation_select.value=="") {
-		alert("<?php echo get_lang('YouMustChooseARelationType')?>");
-		return false;
-	} else {
-		var options = document.getElementById('destination_users').options;
-		for (i = 0 ; i<options.length ; i++)
-			options[i].selected = true;
-		document.forms.formulaire.submit();
-	}
-}
-
-function loadUsersInSelect(select) {
-	var xhr_object = null;
-
-	if (window.XMLHttpRequest) // Firefox
-		xhr_object = new XMLHttpRequest();
-	else if(window.ActiveXObject) // Internet Explorer
-		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
-	else  // XMLHttpRequest non supporté par le navigateur
-	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
-
-	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-	nosessionUsers = makepost(document.getElementById('origin_users'));
-	sessionUsers = makepost(document.getElementById('destination_users'));
-	nosessionClasses = makepost(document.getElementById('origin_classes'));
-	sessionClasses = makepost(document.getElementById('destination_classes'));
-	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
-
-	xhr_object.onreadystatechange = function() {
-		if(xhr_object.readyState == 4) {
-			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
-			//alert(xhr_object.responseText);
-		}
-	}
-}
-
-function makepost(select) {
-	var options = select.options;
-	var ret = "";
-	for (i = 0 ; i<options.length ; i++)
-		ret = ret + options[i].value +'::'+options[i].text+";;";
-	return ret;
-}
-</script>
-<?php
-
-Display::display_footer();

+ 19 - 11
main/admin/dashboard_add_users_to_user.php

@@ -5,6 +5,7 @@
 *	Interface for assigning users to Human Resources Manager
 *	@package chamilo.admin
 */
+
 // resetting the course id
 $cidReset = true;
 
@@ -293,7 +294,7 @@ if (isset($_POST['formSent']) && intval($_POST['formSent']) == 1) {
             $affected_rows = UserManager::suscribe_users_to_hr_manager($user_id, $user_list);
             break;
         case STUDENT_BOSS:
-            $affected_rows = UserManager::subscribeUsersToBoss($user_id, $user_list);
+            $affected_rows = UserManager::subscribeBossToUsers($user_id, $user_list);
             break;
         default:
             $affected_rows = 0;
@@ -308,20 +309,26 @@ if (isset($_POST['formSent']) && intval($_POST['formSent']) == 1) {
 Display::display_header($tool_name);
 
 // actions
-
+$actionsLeft = '';
 if ($userStatus != STUDENT_BOSS) {
     $actionsLeft = Display::url(
-        Display::return_icon('course-add.png', get_lang('AssignCourses'), null, ICON_SIZE_MEDIUM ), "dashboard_add_courses_to_user.php?user=$user_id"
+        Display::return_icon('course-add.png', get_lang('AssignCourses'), null, ICON_SIZE_MEDIUM ),
+        "dashboard_add_courses_to_user.php?user=$user_id"
     );
 
     $actionsLeft .= Display::url(
-        Display::return_icon('session-add.png', get_lang('AssignSessions'), null, ICON_SIZE_MEDIUM ) , "dashboard_add_sessions_to_user.php?user=$user_id"
+        Display::return_icon('session-add.png', get_lang('AssignSessions'), null, ICON_SIZE_MEDIUM ) ,
+        "dashboard_add_sessions_to_user.php?user=$user_id"
     );
 }
 
-$actionsRight = Display::url('<em class="fa fa-search"></em> ' . get_lang('AdvancedSearch'), '#', array('class' => 'btn btn-default advanced_options', 'id' => 'advanced_search'));
+$actionsRight = Display::url(
+    '<em class="fa fa-search"></em> ' . get_lang('AdvancedSearch'),
+    '#',
+    array('class' => 'btn btn-default advanced_options', 'id' => 'advanced_search')
+);
 
-$toolbar = Display::toolbarAction('toolbar-dashboard', $content = array( 0 => $actionsLeft, 1 => $actionsRight ));
+$toolbar = Display::toolbarAction('toolbar-dashboard', [$actionsLeft, $actionsRight]);
 echo $toolbar;
 
 echo '<div id="advanced_search_options" style="display:none">';
@@ -329,8 +336,12 @@ $searchForm->display();
 echo '</div>';
 
 echo Display::page_header(
-    sprintf(get_lang('AssignUsersToX'), api_get_person_name($user_info['firstname'], $user_info['lastname'])),
-        null, $size = 'h3'
+    sprintf(
+        get_lang('AssignUsersToX'),
+        api_get_person_name($user_info['firstname'], $user_info['lastname'])
+    ),
+    null,
+    'h3'
 );
 
 $assigned_users_to_hrm = array();
@@ -492,11 +503,8 @@ if(!empty($msg)) {
                 </select>
             </div>
         </div>
-
     </div>
 </div>
-
 </form>
-
 <?php
 Display::display_footer();

+ 0 - 181
main/admin/group_add.php

@@ -1,181 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
-*	@package chamilo.admin
-*/
-
-$cidReset = true;
-
-// Including necessary libraries.
-require_once '../inc/global.inc.php';
-$libpath = api_get_path(LIBRARY_PATH);
-
-// Section for the tabs
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// User permissions
-api_protect_admin_script();
-
-$group_id = 0;
-
-$htmlHeadXtra[] = '<script>
-textarea = "";
-num_characters_permited = 255;
-function text_longitud(){
-   num_characters = document.forms[0].description.value.length;
-  if (num_characters > num_characters_permited){
-      document.forms[0].description.value = textarea;
-   }else{
-      textarea = document.forms[0].description.value;
-   }
-}
-</script>';
-
-// Database table definitions
-if (!empty($_GET['message'])) {
-    $message = urldecode($_GET['message']);
-}
-
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$tool_name = get_lang('AddGroups');
-
-// Create the form
-$form = new FormValidator('group_add');
-$form->addElement('header', $tool_name);
-
-// name
-$form->addElement('text', 'name', get_lang('Name'), array('size' => 60, 'maxlength' => 120));
-$form->applyFilter('name', 'html_filter');
-$form->applyFilter('name', 'trim');
-$form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-
-// Description
-$form->addElement(
-    'textarea',
-    'description',
-    get_lang('Description'),
-    array('rows' => 3, 'cols' => 58, 'onKeyDown' => "text_longitud()", 'onKeyUp' => "text_longitud()")
-);
-$form->applyFilter('description', 'html_filter');
-$form->applyFilter('description', 'trim');
-
-// url
-$form->addElement('text', 'url', get_lang('Url'), array('size' => 35));
-$form->applyFilter('url', 'html_filter');
-$form->applyFilter('url', 'trim');
-
-// Picture
-$form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
-$form->addRule(
-    'picture',
-    get_lang('OnlyImagesAllowed').' ('.implode(', ', $allowed_picture_types).')',
-    'filetype',
-    $allowed_picture_types
-);
-
-//Group Parentship
-$groups = array();
-$groups[0] = get_lang('NoParentship');
-$groups = $groups + GroupPortalManager::get_groups_list($group_id);
-
-$group_data['parent_group'] = GroupPortalManager::get_parent_group($group_id);
-$form->addElement('select', 'parent_group', get_lang('GroupParentship'), $groups, array());
-
-// Status
-$status = array();
-$status[GROUP_PERMISSION_OPEN] = get_lang('Open');
-$status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
-
-$form->addElement('select', 'visibility', get_lang('GroupPermissions'), $status);
-
-// Set default values
-$defaults['status'] = GROUP_PERMISSION_OPEN;
-
-$form->setDefaults($defaults);
-
-// Submit button
-$form->addButtonCreate(get_lang('Add'));
-
-// Validate form
-if ($form->validate()) {
-	$check = Security::check_token('post');
-	if ($check) {
-		$values = $form->exportValues();
-
-        $picture_element = $form->getElement('picture');
-        $picture = $picture_element->getValue();
-        $picture_uri = '';
-        $name = $values['name'];
-        $description = $values['description'];
-        $url = $values['url'];
-        $status = intval($values['visibility']);
-        $picture = $_FILES['picture'];
-        $parent_group_id = intval($values['parent_group']);
-
-		$group_id = GroupPortalManager::add($name, $description, $url, $status);
-        GroupPortalManager::set_parent_group($group_id,$parent_group_id);
-
-		if (!empty($picture['name'])) {
-            $picture_uri = GroupPortalManager::update_group_picture(
-                $group_id,
-                $_FILES['picture']['name'],
-                $_FILES['picture']['tmp_name']
-            );
-            GroupPortalManager::update(
-                $group_id,
-                $name,
-                $description,
-                $url,
-                $status,
-                $picture_uri
-            );
-		}
-
-		//@todo send emails
-
-/*		if (!empty($email) && $send_mail) {
-			$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
-			$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
-
-			$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-			$email_admin = api_get_setting('emailAdministrator');
-
-			if ($_configuration['multiple_access_urls']) {
-				$access_url_id = api_get_current_access_url_id();
-				if ($access_url_id != -1) {
-					$url = api_get_access_url($access_url_id);
-					$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
-				}
-			}
-			else {
-				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
-			}
-			@api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
-		}*/
-
-		Security::clear_token();
-		$tok = Security::get_token();
-		header('Location: group_list.php?action=show_message&message='.urlencode(get_lang('GroupAdded')).'&sec_token='.$tok);
-        exit ();
-	}
-} else {
-	if (isset($_POST['submit'])) {
-		Security::clear_token();
-	}
-	$token = Security::get_token();
-	$form->addElement('hidden', 'sec_token');
-	$form->setConstants(array('sec_token' => $token));
-}
-
-// Display form
-Display::display_header($tool_name);
-
-if (!empty($message)) {
-    Display::display_normal_message(stripslashes($message));
-}
-$form->display();
-
-// Footer
-Display::display_footer();

+ 0 - 176
main/admin/group_edit.php

@@ -1,176 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
-*	@package chamilo.admin
-*/
-$cidReset = true;
-require_once '../inc/global.inc.php';
-$this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script();
-
-$libpath = api_get_path(LIBRARY_PATH);
-
-$group_id = isset($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
-$tool_name = get_lang('GroupEdit');
-
-$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'group_list.php','name' => get_lang('GroupList'));
-
-$table_group = Database::get_main_table(TABLE_MAIN_GROUP);
-
-$htmlHeadXtra[] = '<script type="text/javascript">
-textarea = "";
-num_characters_permited = 255;
-function text_longitud(){
-   num_characters = document.forms[0].description.value.length;
-  if (num_characters > num_characters_permited){
-      document.forms[0].description.value = textarea;
-   }else{
-      textarea = document.forms[0].description.value;
-   }
-}
-</script>';
-
-$sql = "SELECT * FROM $table_group WHERE id = '".$group_id."'";
-$res = Database::query($sql);
-if (Database::num_rows($res) != 1) {
-	header('Location: group_list.php');
-	exit;
-}
-
-$group_data = Database::fetch_array($res, 'ASSOC');
-
-// Create the form
-$form = new FormValidator('group_edit', 'post', '', '', array('style' => 'width: 60%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
-$form->addElement('header', '', $tool_name);
-$form->addElement('hidden', 'id', $group_id);
-
-// name
-$form->addElement('text', 'name', get_lang('Name'), array('size'=>60, 'maxlength'=>120));
-$form->applyFilter('name', 'html_filter');
-$form->applyFilter('name', 'trim');
-$form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-
-// Description
-$form->addElement(
-	'textarea',
-	'description',
-	get_lang('Description'),
-	array(
-		'rows' => 3,
-		'cols' => 58,
-		'onKeyDown' => "text_longitud()",
-		'onKeyUp' => "text_longitud()",
-	)
-);
-$form->applyFilter('description', 'html_filter');
-$form->applyFilter('description', 'trim');
-
-// url
-$form->addElement('text', 'url', get_lang('Url'), array('size' => 35));
-$form->applyFilter('url', 'html_filter');
-$form->applyFilter('url', 'trim');
-// Picture
-$form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
-if (strlen($group_data['picture_uri']) > 0) {
-	$form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
-}
-
-// Group parent
-$groups = array();
-$groups = GroupPortalManager::get_groups_list($group_id);
-$groups[0] = get_lang('NoParentship');
-$group_data['parent_group'] = GroupPortalManager::get_parent_group($group_id);
-$form->addElement('select', 'parent_group', get_lang('GroupParentship'), $groups, array());
-
-
-// Status
-$status = array();
-$status[GROUP_PERMISSION_OPEN] = get_lang('Open');
-$status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
-$form->addElement('select', 'visibility', get_lang('GroupPermissions'), $status, array());
-
-// Submit button
-$form->addButtonUpdate(get_lang('ModifyInformation'));
-
-// Set default values
-$form->setDefaults($group_data);
-
-// Validate form
-if ( $form->validate()) {
-	$group = $form->exportValues();
-
-	$picture_element = $form->getElement('picture');
-	$picture = $picture_element->getValue();
-
-	$picture_uri = $group_data['picture_uri'];
-	if ($group['delete_picture']) {
-		$picture_uri = GroupPortalManager::delete_group_picture($group_id);
-		}
-	elseif (!empty($picture['name'])) {
-        $picture_uri = GroupPortalManager::update_group_picture(
-            $group_id,
-            $_FILES['picture']['name'],
-            $_FILES['picture']['tmp_name']
-        );
-	}
-
-	$name = $group['name'];
-	$description = $group['description'];
-	$url = $group['url'];
-	$status = intval($group['visibility']);
-	$parent_group_id = intval($group['parent_group']);
-
-    GroupPortalManager::update(
-        $group_id,
-        $name,
-        $description,
-        $url,
-        $status,
-        $picture_uri
-    );
-    GroupPortalManager::set_parent_group($group_id, $parent_group_id);
-
-	$tok = Security::get_token();
-	header('Location: group_list.php?action=show_message&message='.urlencode(get_lang('GroupUpdated')).'&sec_token='.$tok);
-	exit();
-}
-
-Display::display_header($tool_name);
-
-// Group picture
-$image_path = GroupPortalManager::get_group_picture_path_by_id($group_id, 'web');
-$image_dir = $image_path['dir'];
-$image = $image_path['file'];
-$image_file = ($image != '' ? $image_dir.$image : Display::returnIconPath('unknown_group.jpg'));
-$image_size = api_getimagesize($image_file);
-
-$img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
-
-if ($image_size['width'] > 300) {
-    // limit display width to 300px
-	$img_attributes .= 'width="300" ';
-}
-
-// get the path,width and height from original picture
-$big_image = $image_dir.'big_'.$image;
-$big_image_size = api_getimagesize($big_image);
-$big_image_width = $big_image_size['width'];
-$big_image_height = $big_image_size['height'];
-$url_big_image = $big_image.'?rnd='.time();
-
-if ($image == '') {
-	echo '<img '.$img_attributes.' />';
-} else {
-	echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
-}
-
-// Display form
-$form->display();
-
-// Footer
-Display::display_footer();

+ 0 - 407
main/admin/group_list.php

@@ -1,407 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
-  @author Bart Mollet
- * 	@package chamilo.admin
-
- */
-$cidReset = true;
-require_once '../inc/global.inc.php';
-
-$this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script(true);
-
-/**
- * Get the total number of users on the platform
- * @see SortableTable#get_total_number_of_items()
- */
-function get_number_of_groups() {
-    $group_table = Database :: get_main_table(TABLE_MAIN_GROUP);
-    $sql = "SELECT COUNT(g.id) AS total_number_of_items FROM $group_table g";
-
-    // adding the filter to see the user's only of the current access_url
-    /*
-      global $_configuration;
-      if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls'] && api_get_current_access_url_id()!=-1) {
-      $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-      $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-      }
-     */
-    if (isset($_GET['keyword'])) {
-        $keyword = Database::escape_string(trim($_GET['keyword']));
-        $sql .= " WHERE (g.name LIKE '%".$keyword."%' OR g.description LIKE '%".$keyword."%'  OR  g.url LIKE '%".$keyword."%' )";
-    }
-
-    // adding the filter to see the user's only of the current access_url
-    /*
-      if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls'] && api_get_current_access_url_id()!=-1) {
-      $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-      } */
-
-    $res = Database::query($sql);
-    $obj = Database::fetch_object($res);
-    return $obj->total_number_of_items;
-}
-
-/**
- * Get the users to display on the current page (fill the sortable-table)
- * @param   int     offset of first user to recover
- * @param   int     Number of users to get
- * @param   int     Column to sort on
- * @param   string  Order (ASC,DESC)
- * @see SortableTable#get_table_data($from)
- */
-function get_group_data($from, $number_of_items, $column, $direction) {
-    $group_table = Database :: get_main_table(TABLE_MAIN_GROUP);
-
-    $sql = "SELECT
-                 g.id			AS col0,
-                 g.name			AS col1,
-                 g.description 	AS col2,
-                 g.visibility 	AS col3,
-                 g.id			AS col4
-             FROM $group_table g ";
-
-    // adding the filter to see the user's only of the current access_url
-    /* global $_configuration;
-      if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls'] && api_get_current_access_url_id()!=-1) {
-      $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-      $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-      } */
-
-    if (isset($_GET['keyword'])) {
-        $keyword = Database::escape_string(trim($_GET['keyword']));
-        $sql .= " WHERE (g.name LIKE '%".$keyword."%' OR g.description LIKE '%".$keyword."%'  OR  g.url LIKE '%".$keyword."%' )";
-    }
-    /*
-      // adding the filter to see the user's only of the current access_url
-      if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls'] && api_get_current_access_url_id()!=-1) {
-      $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-      } */
-
-    if (!in_array($direction, array('ASC', 'DESC'))) {
-        $direction = 'ASC';
-    }
-    $column = intval($column);
-    $from = intval($from);
-    $number_of_items = intval($number_of_items);
-
-    $sql .= " ORDER BY col$column $direction ";
-    $sql .= " LIMIT $from,$number_of_items";
-
-    $res = Database::query($sql);
-
-    $users = array();
-    $t = time();
-
-    // Status
-    $status = array();
-    $status[GROUP_PERMISSION_OPEN] = get_lang('Open');
-    $status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
-
-    $result = Database::select(
-        'tGroupRelGroup.group_id, tGroup.id, tGroup.name',
-        Database::get_main_table(TABLE_MAIN_GROUP_REL_GROUP).
-        " AS tGroupRelGroup RIGHT JOIN ".Database::get_main_table(TABLE_MAIN_GROUP).
-        " AS tGroup ON tGroupRelGroup.subgroup_id = tGroup.id"
-    );
-    $groupRelations = array();
-    foreach ($result as $row) {
-        $groupRelations[$row['id']] = $row;
-    }
-    $groups = array();
-    while ($group = Database::fetch_row($res)) {
-        $name = null;
-        $id = $group[0];
-        // Loops while the current group is a subgroup
-        while (isset($groupRelations[$id]['group_id'])) {
-            $name = $name ?
-                $groupRelations[$id]['name'] . " > " . $name :
-                $groupRelations[$id]['name'];
-            $id = $groupRelations[$id]['group_id'];
-        }
-        // The base group
-        $name = $name ?
-            $groupRelations[$id]['name'] . " > " . $name :
-            $groupRelations[$id]['name'];
-        $group[3] = $status[$group[3]];
-        $group['1'] = '<a href="'.api_get_path(WEB_CODE_PATH).'social/group_view.php?id='.$group['0'].'">'.$name.'</a>';
-        $groups[] = $group;
-    }
-    return $groups;
-}
-
-function get_recent_group_data($from = 0, $number_of_items = 5, $column, $direction) {
-    $group_table = Database :: get_main_table(TABLE_MAIN_GROUP);
-
-    $sql = "SELECT
-                 g.id			AS col0,
-                 g.name			AS col1,
-                 g.description 	AS col2,
-                 g.visibility 	AS col3,
-                 g.id			AS col4
-             FROM $group_table g ";
-
-    // adding the filter to see the user's only of the current access_url
-    /* global $_configuration;
-      if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls'] && api_get_current_access_url_id()!=-1) {
-      $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-      $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-      } */
-
-    if (isset($_GET['keyword'])) {
-        $keyword = Database::escape_string(trim($_GET['keyword']));
-        $sql .= " WHERE (g.name LIKE '%".$keyword."%' OR g.description LIKE '%".$keyword."%'  OR  g.url LIKE '%".$keyword."%' )";
-    }
-    /*
-      // adding the filter to see the user's only of the current access_url
-      if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls'] && api_get_current_access_url_id()!=-1) {
-      $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-      } */
-
-    if (!in_array($direction, array('ASC', 'DESC'))) {
-        $direction = 'ASC';
-    }
-    $column = intval($column);
-    $from = intval($from);
-    $number_of_items = intval($number_of_items);
-
-    $sql .= " ORDER BY col$column $direction ";
-    $sql .= " LIMIT $from,$number_of_items";
-
-    $res = Database::query($sql);
-
-    $users = array();
-    $t = time();
-    while ($group = Database::fetch_row($res)) {
-        // forget about the expiration date field
-        $groups[] = $group;
-    }
-    return $groups;
-}
-
-/**
- * Build the modify-column of the table
- * @param   int     The user id
- * @param   string  URL params to add to table links
- * @param   array   Row of elements to alter
- * @return string Some HTML-code with modify-buttons
- */
-function modify_filter($group_id, $url_params, $row) {
-    global $charset;
-    $result = null;
-    if (api_is_platform_admin()) {
-        $result .= '<a href="'.api_get_path(WEB_CODE_PATH).'admin/add_users_to_group.php?id='.$group_id.'">'.Display::return_icon('subscribe_users_social_network.png', get_lang('AddUsersToGroup'), '', ICON_SIZE_SMALL).'</a>';
-        $result .= '<a href="group_edit.php?id='.$group_id.'">'.Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;&nbsp;';
-        $result .= '<a href="group_list.php?action=delete_group&group_id='.$group_id.'&'.$url_params.'&sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
-    }
-    return $result;
-}
-
-/**
- * Build the active-column of the table to lock or unlock a certain user
- * lock = the user can no longer use this account
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @param int $active the current state of the account
- * @param int $user_id The user id
- * @param string $url_params
- * @return string Some HTML-code with the lock/unlock button
- */
-function active_filter($active, $url_params, $row)
-{
-    $_user = api_get_user_info();
-
-    if ($active == '1') {
-        $action = 'lock';
-        $image = 'right';
-    } elseif ($active == '-1') {
-        $action = 'edit';
-        $image = 'expired';
-    } elseif ($active == '0') {
-        $action = 'unlock';
-        $image = 'wrong';
-    }
-
-    if ($action == 'edit') {
-        $result = Display::return_icon($image.'.gif', get_lang('AccountExpired'));
-    } elseif ($row['0'] <> $_user['user_id']) { // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
-        $result = '<a href="user_list.php?action='.$action.'&user_id='.$row['0'].'&'.$url_params.'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
-    }
-    return $result;
-}
-
-/**
- * Lock or unlock a user
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @param int $status, do we want to lock the user ($status=lock) or unlock it ($status=unlock)
- * @param int $user_id The user id
- * @return language variable
- */
-function lock_unlock_user($status, $user_id) {
-    $user_table = Database :: get_main_table(TABLE_MAIN_USER);
-    if ($status == 'lock') {
-        $status_db = '0';
-        $return_message = get_lang('UserLocked');
-    }
-    if ($status == 'unlock') {
-        $status_db = '1';
-        $return_message = get_lang('UserUnlocked');
-    }
-
-    if (($status_db == '1' OR $status_db == '0') AND is_numeric($user_id)) {
-        $sql = "UPDATE $user_table SET active=".intval($status_db)."
-                WHERE user_id=".intval($user_id)."";
-        $result = Database::query($sql);
-    }
-
-    if ($result) {
-        return $return_message;
-    }
-}
-
-/**
- * Instead of displaying the integer of the status, we give a translation for the status
- *
- * @param integer $status
- * @return string translation
- *
- * @version march 2008
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- */
-function status_filter($status) {
-    $statusname = api_get_status_langvars();
-    return $statusname[$status];
-}
-
-// INIT SECTION
-$action = isset($_GET["action"]) ? $_GET["action"] : null;
-
-if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
-    $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-    $interbreadcrumb[] = array("url" => 'group_list.php', "name" => get_lang('GroupList'));
-    $tool_name = get_lang('SearchAUser');
-    Display :: display_header($tool_name);
-    //api_display_tool_title($tool_name);
-    $form = new FormValidator('advanced_search', 'get');
-    $form->addElement('header', '', $tool_name);
-    $form->addText('keyword_firstname', get_lang('FirstName'), false);
-    $form->addText('keyword_lastname', get_lang('LastName'), false);
-    $form->addText('keyword_username', get_lang('LoginName'), false);
-    $form->addText('keyword_email', get_lang('Email'), false);
-    $form->addText('keyword_officialcode', get_lang('OfficialCode'), false);
-    $status_options = array();
-    $status_options['%'] = get_lang('All');
-    $status_options[STUDENT] = get_lang('Student');
-    $status_options[COURSEMANAGER] = get_lang('Teacher');
-    $status_options[SESSIONADMIN] = get_lang('Administrator'); //
-    $form->addElement('select', 'keyword_status', get_lang('Status'), $status_options);
-    $active_group = array();
-    $active_group[] = $form->createElement('checkbox', 'keyword_active', '', get_lang('Active'));
-    $active_group[] = $form->createElement('checkbox', 'keyword_inactive', '', get_lang('Inactive'));
-    $form->addGroup($active_group, '', get_lang('ActiveAccount'), '<br/>', false);
-    $form->addButtonSearch(get_lang('SearchUsers'));
-    $defaults['keyword_active'] = 1;
-    $defaults['keyword_inactive'] = 1;
-    $form->setDefaults($defaults);
-    $form->display();
-} else {
-    $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-    $tool_name = get_lang('GroupList');
-    Display :: display_header($tool_name, "");
-
-    //api_display_tool_title($tool_name);
-    if (isset($_GET['action'])) {
-        $check = Security::check_token('get');
-        if ($check) {
-            switch ($_GET['action']) {
-                case 'delete_group':
-                    if (api_is_platform_admin()) {
-                        if (GroupPortalManager :: delete($_GET['group_id'])) {
-                            Display :: display_confirmation_message(get_lang('GroupDeleted'));
-                        } else {
-                            Display :: display_error_message(get_lang('CannotDeleteGroup'));
-                        }
-                    }
-                    break;
-                case 'lock':
-                    $message = lock_unlock_user('lock', $_GET['user_id']);
-                    Display :: display_normal_message($message);
-                    break;
-                case 'unlock':
-                    $message = lock_unlock_user('unlock', $_GET['user_id']);
-                    Display :: display_normal_message($message);
-                    break;
-            }
-            Security::clear_token();
-        }
-    }
-    if (isset($_POST['action'])) {
-        $check = Security::check_token('get');
-        if ($check) {
-            switch ($_POST['action']) {
-                case 'delete' :
-                    if (api_is_platform_admin()) {
-                        $number_of_selected_groups = count($_POST['id']);
-                        $number_of_deleted_groups = 0;
-                        foreach ($_POST['id'] as $index => $group_id) {
-                            if (GroupPortalManager :: delete($group_id)) {
-                                $number_of_deleted_groups++;
-                            }
-                        }
-                    }
-                    if ($number_of_selected_groups == $number_of_deleted_groups) {
-                        Display :: display_confirmation_message(get_lang('SelectedGroupsDeleted'));
-                    } else {
-                        Display :: display_error_message(get_lang('SomeGroupsNotDeleted'));
-                    }
-                    break;
-            }
-            Security::clear_token();
-        }
-    }
-    // Create a search-box
-    $form = new FormValidator('search_simple', 'get', '', '', null, false);
-    $renderer = & $form->defaultRenderer();
-    $renderer->setCustomElementTemplate('<span>{element}</span> ');
-    $form->addElement('text', 'keyword', get_lang('Keyword'));
-    $form->addButtonSearch(get_lang('Search'));
-    echo '<div class="actions" style="width:100%;">';
-    if (api_is_platform_admin()) {
-        echo '<span style="float:right;">'.
-        '<a href="'.api_get_path(WEB_CODE_PATH).'admin/group_add.php">'.Display::return_icon('create_group_social_network.png', get_lang('AddGroups'), '', ICON_SIZE_MEDIUM).'</a>'.
-        '</span>';
-    }
-    $form->display();
-    echo '</div>';
-    if (isset($_GET['keyword'])) {
-        $parameters = array('keyword' => Security::remove_XSS($_GET['keyword']));
-    }
-    // Create a sortable table with user-data
-    $parameters['sec_token'] = Security::get_token();
-
-    // get the list of all admins to mark them in the users list
-    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
-    $sql_admin = "SELECT user_id FROM $admin_table";
-    $res_admin = Database::query($sql_admin);
-    $_admins_list = array();
-    while ($row_admin = Database::fetch_row($res_admin)) {
-        $_admins_list[] = $row_admin[0];
-    }
-
-    $table = new SortableTable('group_list', 'get_number_of_groups', 'get_group_data', 2);
-    $table->set_additional_parameters($parameters);
-    $table->set_header(0, '', false);
-    $table->set_header(1, get_lang('Name'));
-    $table->set_header(2, get_lang('Description'));
-    $table->set_header(3, get_lang('Visibility'));
-    $table->set_header(4, '', false);
-    $table->set_column_filter(4, 'modify_filter');
-    //$table->set_column_filter(6, 'status_filter');
-    //$table->set_column_filter(7, 'active_filter');
-    //$table->set_column_filter(8, 'modify_filter');
-    if (api_is_platform_admin())
-        $table->set_form_actions(array('delete' => get_lang('DeleteFromPlatform')));
-    $table->display();
-}
-Display :: display_footer();

+ 23 - 0
main/admin/user_edit.php

@@ -345,6 +345,25 @@ if (!$user_data['platform_admin']) {
 	$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
 	$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 }
+$studentBossList = UserManager::getStudentBossList($user_data['user_id']);
+
+$conditions = ['status' => STUDENT_BOSS];
+$studentBoss = UserManager::get_user_list($conditions);
+$studentBossToSelect = [];
+
+if ($studentBoss) {
+    foreach ($studentBoss as $bossId => $userData) {
+        $bossInfo = api_get_user_info($userData['user_id']);
+        $studentBossToSelect[$bossInfo['user_id']] =  $bossInfo['complete_name_with_username'];
+    }
+}
+
+if ($studentBossList) {
+    $studentBossList = array_column($studentBossList, 'boss_id');
+}
+
+$user_data['student_boss'] = array_values($studentBossList);
+$form->addElement('advmultiselect', 'student_boss', get_lang('StudentBoss'), $studentBossToSelect);
 
 // EXTRA FIELDS
 $extraField = new ExtraField('user');
@@ -461,6 +480,10 @@ if ($form->validate()) {
             $reset_password
         );
 
+        if (isset($user['student_boss'])) {
+            UserManager::subscribeUserToBossList($user_id, $user['student_boss']);
+        }
+
 		if (api_get_setting('openid_authentication') == 'true' && !empty($user['openid'])) {
 			$up = UserManager::update_openid($user_id, $user['openid']);
 		}

+ 51 - 27
main/admin/user_information.php

@@ -21,6 +21,7 @@ if (!isset($_GET['user_id'])) {
     api_not_allowed();
 }
 $user = api_get_user_info($_GET['user_id'], true);
+$userId = $user['user_id'];
 $tool_name = $user['complete_name'].(empty($user['official_code'])?'':' ('.$user['official_code'].')');
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
@@ -31,7 +32,7 @@ $editUser = null;
 if (api_is_platform_admin()) {
     $login_as_icon =
         '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php'
-        .'?action=login_as&user_id='.$user['user_id'].'&'
+        .'?action=login_as&user_id='.$userId.'&'
         .'sec_token='.$_SESSION['sec_token'].'">'
         .Display::return_icon('login_as.png', get_lang('LoginAs'),
             array(), ICON_SIZE_MEDIUM).'</a>';
@@ -42,20 +43,20 @@ if (api_is_platform_admin()) {
             array(),
             ICON_SIZE_MEDIUM
         ),
-        api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user['user_id']
+        api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$userId
     );
 
     $exportLink = Display::url(
         Display::return_icon(
             'export_csv.png', get_lang('ExportAsCSV'),'', ICON_SIZE_MEDIUM
         ),
-        api_get_self().'?user_id='.$user['user_id'].'&action=export'
+        api_get_self().'?user_id='.$userId.'&action=export'
     );
     $vCardExportLink = Display::url(
         Display::return_icon(
             'vcard.png', get_lang('UserInfo'),'', ICON_SIZE_MEDIUM
         ),
-        api_get_path(WEB_PATH).'main/social/vcard_export.php?userId='.$user['user_id']
+        api_get_path(WEB_PATH).'main/social/vcard_export.php?userId='.$userId
     );
     
 }
@@ -65,11 +66,10 @@ $creatorId = $user['creator_id'];
 $creatorInfo = api_get_user_info($creatorId);
 $registrationDate = $user['registration_date'];
 
-$csvContent = array();
-
 $table = new HTML_Table(array('class' => 'data_table'));
 $table->setHeaderContents(0, 0, get_lang('Information'));
-$csvContent[] = get_lang('Information');
+
+$csvContent[] = [get_lang('Information')];
 $data = array(
     get_lang('Name') => $user['complete_name'],
     get_lang('Email') => $user['email'],
@@ -104,10 +104,10 @@ $userInformation = $table->toHtml();
 
 $table = new HTML_Table(array('class' => 'data_table'));
 $table->setHeaderContents(0, 0, get_lang('Tracking'));
-$csvContent[] = get_lang('Tracking');
+$csvContent[] = [get_lang('Tracking')];
 $data = array(
-    get_lang('FirstLogin') => Tracking :: get_first_connection_date($user['user_id']),
-    get_lang('LatestLogin') => Tracking :: get_last_connection_date($user['user_id'], true)
+    get_lang('FirstLogin') => Tracking :: get_first_connection_date($userId),
+    get_lang('LatestLogin') => Tracking :: get_last_connection_date($userId, true)
 );
 $row = 1;
 foreach ($data as $label => $item) {
@@ -126,8 +126,7 @@ $tbl_session = Database:: get_main_table(TABLE_MAIN_SESSION);
 $tbl_course = Database:: get_main_table(TABLE_MAIN_COURSE);
 $tbl_user = Database:: get_main_table(TABLE_MAIN_USER);
 
-$user_id = $user['user_id'];
-$sessions = SessionManager::get_sessions_by_user($user_id, true);
+$sessions = SessionManager::get_sessions_by_user($userId, true);
 $personal_course_list = array();
 $courseToolInformationTotal = null;
 if (count($sessions) > 0) {
@@ -159,7 +158,7 @@ if (count($sessions) > 0) {
         foreach ($session_item['courses'] as $my_course) {
             $courseInfo = api_get_course_info_by_id($my_course['real_id']);
             $sessionStatus = SessionManager::get_user_status_in_session(
-                $user['user_id'],
+                $userId,
                 $courseInfo['real_id'],
                 $id_session
             );
@@ -179,20 +178,20 @@ if (count($sessions) > 0) {
                 Display::return_icon('course_home.gif', get_lang('CourseHomepage')).'</a>';
 
             if ($my_course['status'] == STUDENT) {
-                $tools .= '<a href="user_information.php?action=unsubscribeSessionCourse&course_code='.$courseInfo['code'].'&user_id='.$user['user_id'].'&id_session='.$id_session.'">'.
+                $tools .= '<a href="user_information.php?action=unsubscribeSessionCourse&course_code='.$courseInfo['code'].'&user_id='.$userId.'&id_session='.$id_session.'">'.
                     Display::return_icon('delete.png', get_lang('Delete')).'</a>';
             }
 
             $timeSpent = api_time_to_hms(
                 Tracking :: get_time_spent_on_the_course(
-                    $user['user_id'],
+                    $userId,
                     $courseInfo['real_id'],
                     $id_session
                 )
             );
 
             $totalForumMessages = CourseManager::getCountPostInForumPerUser(
-                $user['user_id'],
+                $userId,
                 $courseInfo['real_id'],
                 $id_session
             );
@@ -213,7 +212,7 @@ if (count($sessions) > 0) {
             $data[] = $row;
 
             $result = TrackingUserLogCSV::getToolInformation(
-                $user['user_id'],
+                $userId,
                 $courseInfo,
                 $id_session
             );
@@ -261,7 +260,7 @@ $courseToolInformationTotal = null;
  */
 $sql = 'SELECT * FROM '.$table_course_user.' cu, '.$table_course.' c
         WHERE
-            cu.user_id = '.$user['user_id'].' AND
+            cu.user_id = '.$userId.' AND
             cu.c_id = c.id AND
             cu.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' ';
 $res = Database::query($sql);
@@ -297,20 +296,20 @@ if (Database::num_rows($res) > 0) {
             '<a href="course_edit.php?id='.$course->c_id.'">'.
             Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
         if ($course->status == STUDENT) {
-            $tools .= '<a href="user_information.php?action=unsubscribe&course_code='.$courseCode.'&user_id='.$user['user_id'].'">'.
+            $tools .= '<a href="user_information.php?action=unsubscribe&course_code='.$courseCode.'&user_id='.$userId.'">'.
                 Display::return_icon('delete.png', get_lang('Delete')).'</a>';
         }
 
         $timeSpent = api_time_to_hms(
             Tracking :: get_time_spent_on_the_course(
-                $user['user_id'],
+                $userId,
                 $courseInfo['real_id'],
                 0
             )
         );
 
         $totalForumMessages = CourseManager::getCountPostInForumPerUser(
-            $user['user_id'],
+            $userId,
             $course->id,
             0
         );
@@ -328,7 +327,7 @@ if (Database::num_rows($res) > 0) {
         $data[] = $row;
 
         $result = TrackingUserLogCSV::getToolInformation(
-            $user['user_id'],
+            $userId,
             $courseInfo,
             0
         );
@@ -352,9 +351,9 @@ if (Database::num_rows($res) > 0) {
 /**
  * Show the URL in which this user is subscribed
  */
-$urlInformation = null;
+$urlInformation = '';
 if (api_is_multiple_url_enabled()) {
-    $urlList = UrlManager::get_access_url_from_user($user['user_id']);
+    $urlList = UrlManager::get_access_url_from_user($userId);
     if (count($urlList) > 0) {
         $header = array();
         $header[] = array('URL', true);
@@ -381,6 +380,25 @@ if (api_is_multiple_url_enabled()) {
         $urlInformation = '<p>'.get_lang('NoUrlForThisUser').'</p>';
     }
 }
+
+
+$studentBossList = UserManager::getStudentBossList($userId);
+$studentBossListToString = '';
+if ($studentBossList) {
+    $table = new HTML_Table(array('class' => 'data_table'));
+    $table->setHeaderContents(0, 0, get_lang('User'));
+    $csvContent[] = [get_lang('StudentBoss')];
+
+    $row = 1;
+    foreach ($studentBossList as $studentBossId) {
+        $studentBoss = api_get_user_info($studentBossId);
+        $table->setCellContents($row, 0, $studentBoss['complete_name_with_username']);
+        $csvContent[] = array($studentBoss['complete_name_with_username']);
+        $row++;
+    }
+    $studentBossListToString = $table->toHtml();
+}
+
 $message = null;
 
 if (isset($_GET['action'])) {
@@ -425,14 +443,13 @@ echo '<div class="actions">
 
 echo Display::page_header($tool_name);
 
-
 $fullUrlBig = UserManager::getUserPicture(
-    $user['user_id'],
+    $userId,
     USER_IMAGE_SIZE_BIG
 );
 
 $fullUrl = UserManager::getUserPicture(
-    $user['user_id'],
+    $userId,
     USER_IMAGE_SIZE_ORIGINAL
 );
 
@@ -453,8 +470,15 @@ echo $trackingInformation;
 echo '</div>';
 echo '</div>';
 
+if ($studentBossList) {
+    echo Display::page_subheader(get_lang('StudentBossList'));
+    echo $studentBossListToString;
+}
+
 echo Display::page_subheader(get_lang('SessionList'));
 echo $sessionInformation;
+
+echo Display::page_subheader(get_lang('CourseList'));
 echo $courseInformation;
 echo $urlInformation;
 

+ 2 - 2
main/course_description/listing.php

@@ -57,12 +57,12 @@ if (isset($descriptions) && count($descriptions) > 0) {
                     $description['title'] = $description['title'].' '.api_get_session_image(api_get_session_id(), $user_info['status']);
 
                     // delete
-                    $actions .= '<a href="'.api_get_self().'?id='.$description['id'].'&cidReq='.api_get_course_id().'&id_session='.$description['session_id'].'&action=delete&description_type='.$description['description_type'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,api_get_system_encoding())).'\')) return false;">';
+                    $actions .= '<a href="'.api_get_self().'?id='.$description['id'].'&'.api_get_cidreq_params(api_get_course_id(), $description['session_id']).'&action=delete&description_type='.$description['description_type'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,api_get_system_encoding())).'\')) return false;">';
                     $actions .= Display::return_icon('delete.png', get_lang('Delete'), array('style' => 'vertical-align:middle;float:right;'),ICON_SIZE_SMALL);
                     $actions .= '</a> ';
 
                     // edit
-                    $actions .= '<a href="'.api_get_self().'?id='.$description['id'].'&cidReq='.api_get_course_id().'&id_session='.$description['session_id'].'&action=edit&description_type='.$description['description_type'].'">';
+                    $actions .= '<a href="'.api_get_self().'?id='.$description['id'].'&'.api_get_cidreq_params(api_get_course_id(), $description['session_id']).'&action=edit&description_type='.$description['description_type'].'">';
                     $actions .= Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align:middle;float:right; padding-right:4px;'),ICON_SIZE_SMALL);
                     $actions .= '</a> ';
                 } else {

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

@@ -1928,6 +1928,16 @@ class Exercise
                     array('id' => 'result_disabled_2')
                 );
 
+
+                $radios_results_disabled[] = $form->createElement(
+                    'radio',
+                    'results_disabled',
+                    null,
+                    get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
+                    '4',
+                    array('id' => 'result_disabled_4')
+                );
+
                 $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
 
                 // Type of questions disposition on page
@@ -7705,7 +7715,13 @@ class Exercise
             $show_results = true;
         }
 
-        if (in_array($this->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES))) {
+        $showScoreOptions = [
+            RESULT_DISABLE_SHOW_SCORE_ONLY,
+            RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES,
+            RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT
+        ];
+
+        if (in_array($this->results_disabled, $showScoreOptions)) {
             $show_only_score = true;
         }
 

+ 8 - 8
main/exercice/exercise_submit.php

@@ -111,10 +111,10 @@ if (api_is_allowed_to_edit(null, true) && isset($_GET['preview']) && $_GET['prev
 
 /** @var \Exercise $exerciseInSession */
 $exerciseInSession = Session::read('objExercise');
-
 if (!isset($exerciseInSession) || isset($exerciseInSession) && ($exerciseInSession->id != $_GET['exerciseId'])) {
     // Construction of Exercise
     $objExercise = new Exercise();
+
     Session::write('firstTime', true);
     if ($debug) {error_log('1. Setting the $objExercise variable'); };
     Session::erase('questionList');
@@ -134,7 +134,6 @@ if (!isset($exerciseInSession) || isset($exerciseInSession) && ($exerciseInSessi
 } else {
     Session::write('firstTime', false);
 }
-
 //2. Checking if $objExercise is set
 if (!isset($objExercise) && isset($exerciseInSession)) {
 	if ($debug) { error_log('2. Loading $objExercise from session'); };
@@ -245,12 +244,14 @@ if ($objExercise->selectAttempts() > 0) {
 		if ($origin == 'learnpath') {
 			Display :: display_reduced_header();
 		} else {
-			Display :: display_header($nameTools,'Exercises');
+			Display :: display_header(get_lang('Exercises'));
 		}
 
 		echo $attempt_html;
-		if ($origin != 'learnpath')
-			Display :: display_footer();
+
+        if ($origin != 'learnpath') {
+            Display:: display_footer();
+        }
 		exit;
 	}
 }
@@ -460,9 +461,8 @@ if ($time_control) { //Sends the exercise form when the expired time is finished
 }
 
 // if the user has submitted the form
-
-$exercise_title			= $objExercise->selectTitle();
-$exercise_sound 		= $objExercise->selectSound();
+$exercise_title = $objExercise->selectTitle();
+$exercise_sound = $objExercise->selectSound();
 
 //in LP's is enabled the "remember question" feature?
 

+ 24 - 3
main/exercice/overview.php

@@ -169,6 +169,13 @@ if ($current_browser == 'Internet Explorer') {
     $btn_class = '';
 }
 
+$blockShowAnswers = false;
+if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
+    if (count($attempts) < $objExercise->attempts ) {
+        $blockShowAnswers = true;
+    }
+}
+
 if (!empty($attempts)) {
     $i = $counter;
     foreach ($attempts as $attempt_result) {
@@ -213,7 +220,8 @@ if (!empty($attempts)) {
             array(
                 RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
                 RESULT_DISABLE_SHOW_SCORE_ONLY,
-                RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES
+                RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES,
+                RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT
             )
         )) {
             $row['result'] = $score;
@@ -223,23 +231,36 @@ if (!empty($attempts)) {
                 $objExercise->results_disabled,
                 array(
                     RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
-                    RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES
+                    RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES,
+                    RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT
                 )
             )
             || (
                 $objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY &&
                 $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END)
         ) {
+            if ($blockShowAnswers) {
+                $attempt_link = '';
+            }
+
             $row['attempt_link'] = $attempt_link;
         }
         $my_attempt_array[] = $row;
         $i--;
     }
 
+    $header_names = [];
     $table = new HTML_Table(array('class' => 'table table-striped table-hover'));
 
-    //Hiding score and answer
+    // Hiding score and answer
     switch ($objExercise->results_disabled) {
+        case RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT:
+            if ($blockShowAnswers) {
+                $header_names = array(get_lang('Attempt'), get_lang('StartDate'), get_lang('IP'), get_lang('Score'));
+            } else {
+                $header_names = array(get_lang('Attempt'), get_lang('StartDate'), get_lang('IP'), get_lang('Score'), get_lang('Details'));
+            }
+            break;
         case RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS:
         case RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES:
             $header_names = array(get_lang('Attempt'), get_lang('StartDate'), get_lang('IP'), get_lang('Score'), get_lang('Details'));

+ 2 - 2
main/exercice/result.php

@@ -28,10 +28,10 @@ if (empty($id)) {
 
 $is_allowedToEdit = api_is_allowed_to_edit(null,true) || $is_courseTutor;
 
-//Getting results from the exe_id. This variable also contain all the information about the exercise
+// Getting results from the exe_id. This variable also contain all the information about the exercise
 $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id);
 
-//No track info
+// No track info
 if (empty($track_exercise_info)) {
     api_not_allowed($show_headers);
 }

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

@@ -446,6 +446,7 @@ define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and ex
 define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
 define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
 define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
+define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4); //Show final score only with categories
 
 define('EXERCISE_MAX_NAME_SIZE', 80);
 

+ 0 - 8
main/inc/lib/database.constants.inc.php

@@ -82,14 +82,6 @@ define('TABLE_MAIN_TAG', 'tag');
 define('TABLE_MAIN_USER_REL_TAG', 'user_rel_tag');
 define('TABLE_MAIN_EXTRA_FIELD_REL_TAG', 'extra_field_rel_tag');
 
-define('TABLE_MAIN_GROUP', 'groups');
-
-//User groups
-/*
-define('TABLE_MAIN_USER_REL_GROUP', 'group_rel_user');
-define('TABLE_MAIN_GROUP_REL_TAG', 'group_rel_tag');
-define('TABLE_MAIN_GROUP_REL_GROUP', 'group_rel_group');*/
-
 // Search engine
 define('TABLE_MAIN_SPECIFIC_FIELD', 'specific_field');
 define('TABLE_MAIN_SPECIFIC_FIELD_VALUES', 'specific_field_values');

+ 27 - 0
main/inc/lib/exercise.lib.php

@@ -3488,6 +3488,32 @@ HOTSPOT;
             $show_only_score = false;
         }
 
+        if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
+            $show_only_score = true;
+            if ($objExercise->attempts > 0) {
+                $attempts = Event::getExerciseResultsByUser(
+                    api_get_user_id(),
+                    $objExercise->id,
+                    api_get_course_int_id(),
+                    api_get_session_id(),
+                    $exercise_stat_info['orig_lp_id'],
+                    $exercise_stat_info['orig_lp_item_id'],
+                    'desc'
+                );
+
+                if ($attempts) {
+                    $numberAttempts = count($attempts);
+                    if ($save_user_result) {
+                        $numberAttempts++;
+                    }
+                    if ($numberAttempts >= $objExercise->attempts) {
+                        $show_results = true;
+                        $show_only_score = false;
+                    };
+                }
+            }
+        }
+
         if ($show_results || $show_only_score) {
             $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
             //Shows exercise header
@@ -3502,6 +3528,7 @@ HOTSPOT;
             );
         }
 
+
         // Display text when test is finished #4074 and for LP #4227
         $end_of_message = $objExercise->selectTextWhenFinished();
         if (!empty($end_of_message)) {

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

@@ -41,6 +41,7 @@ class Export
     public static function arrayToCsv($data, $filename = 'export')
     {
         if (empty($data)) {
+            
             return false;
         }
 

+ 0 - 1502
main/inc/lib/group_portal_manager.lib.php

@@ -1,1502 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Class GroupPortalManager
- * @deprecated use UserGroup functions.
- * Include/require it in your code to use its functionality.
- * @author Julio Montoya <gugli100@gmail.com>
- * @package chamilo.library
- */
-class GroupPortalManager
-{
-    /**
-     * Creates a new group
-     *
-     * @author Julio Montoya <gugli100@gmail.com>,
-     *
-     * @param	string	$name The URL of the site
-     * @param   string  $description The description of the site
-     * @param   string  $url
-     * @param	int		$visibility is active or not
-     * @param   string  $picture
-     *
-     * @return boolean if success
-     */
-    public static function add($name, $description, $url, $visibility, $picture = '')
-    {
-        $now = api_get_utc_datetime();
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP);
-        $sql = "INSERT INTO $table
-                   SET name 	= '".Database::escape_string($name)."',
-                   description = '".Database::escape_string($description)."',
-                   picture_uri = '".Database::escape_string($picture)."',
-                   url 		= '".Database::escape_string($url)."',
-                   visibility 	= '".Database::escape_string($visibility)."',
-                   created_on = '".$now."',
-                   updated_on = '".$now."'";
-        Database::query($sql);
-        $id = Database::insert_id();
-        if ($id) {
-            Event::addEvent(LOG_GROUP_PORTAL_CREATED, LOG_GROUP_PORTAL_ID, $id);
-
-            return $id;
-        }
-
-        return false;
-    }
-
-    /**
-     * Updates a group
-     * @author Julio Montoya <gugli100@gmail.com>,
-     *
-     * @param int $group_id The id
-     * @param string $name The description of the site
-     * @param string $description
-     * @param string $url
-     * @param int $visibility
-     * @param string $picture_uri
-     * @param bool $allowMemberGroupToLeave
-     * @return bool if success
-     */
-    public static function update($group_id, $name, $description, $url, $visibility, $picture_uri, $allowMemberGroupToLeave = null)
-    {
-        $group_id = intval($group_id);
-        $table = Database::get_main_table(TABLE_MAIN_GROUP);
-        $now = api_get_utc_datetime();
-        $groupLeaveCondition = null;
-        if (isset($allowMemberGroupToLeave)) {
-            $allowMemberGroupToLeave = $allowMemberGroupToLeave == true ? 1 : 0;
-            $groupLeaveCondition = " allow_members_leave_group = $allowMemberGroupToLeave , ";
-        }
-        $sql = "UPDATE $table SET
-                    name 	= '".Database::escape_string($name)."',
-                    description = '".Database::escape_string($description)."',
-                    picture_uri = '".Database::escape_string($picture_uri)."',
-                    url 		= '".Database::escape_string($url)."',
-                    visibility 	= '".Database::escape_string($visibility)."',
-                    $groupLeaveCondition
-                    updated_on 	= '".$now."'
-                WHERE id = '$group_id'";
-        $result = Database::query($sql);
-
-        return $result;
-    }
-
-    /**
-     * Deletes a group
-     * @author Julio Montoya
-     * @param int $id
-     * @return boolean true if success
-     * */
-    public static function delete($id)
-    {
-        $id = intval($id);
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP);
-        $sql = "DELETE FROM $table WHERE id = ".intval($id);
-        $result = Database::query($sql);
-        // Deleting all relationship with users and groups
-        self::delete_users($id);
-        // Delete group image
-        self::delete_group_picture($id);
-        Event::addEvent(LOG_GROUP_PORTAL_DELETED, LOG_GROUP_PORTAL_ID, $id);
-
-        return $result;
-    }
-
-    /**
-     * Gets data of all groups
-     * @author Julio Montoya
-     * @param int	$visibility
-     * @param int	$from which record the results will begin (use for pagination)
-     * @param int	$number_of_items
-     *
-     * @return array
-     * */
-    public static function get_all_group_data($visibility = GROUP_PERMISSION_OPEN, $from = 0, $number_of_items = 10)
-    {
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP);
-        $visibility = intval($visibility);
-        $sql = "SELECT * FROM $table WHERE visibility = $visibility ";
-        $res = Database::query($sql);
-        $data = array();
-        while ($item = Database::fetch_array($res)) {
-            $data[] = $item;
-        }
-
-        return $data;
-    }
-
-    /**
-     * Gets a list of all group
-     * @param int $without_this_one id of a group not to include (i.e. to exclude)
-     *
-     * @return array : id => name
-     * */
-    public static function get_groups_list($without_this_one = NULL)
-    {
-        $where = '';
-        if (isset($without_this_one) && (intval($without_this_one) == $without_this_one)) {
-            $where = "WHERE id <> $without_this_one";
-        }
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP);
-        $sql = "SELECT id, name FROM $table $where order by name";
-        $res = Database::query($sql);
-        $list = array();
-        while ($item = Database::fetch_assoc($res)) {
-            $list[$item['id']] = $item['name'];
-        }
-
-        return $list;
-    }
-
-    /**
-     * Gets the group data
-     * @param int $group_id
-     *
-     * @return array
-     */
-    public static function get_group_data($group_id)
-    {
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP);
-        $group_id = intval($group_id);
-        $sql = "SELECT * FROM $table WHERE id = $group_id ";
-        $res = Database::query($sql);
-        $item = array();
-        if (Database::num_rows($res) > 0) {
-            $item = Database::fetch_array($res, 'ASSOC');
-        }
-
-        return $item;
-    }
-
-    /**
-     * Set a parent group
-     * @param int $group_id
-     * @param int $parent_group_id if 0, we delete the parent_group association
-     * @param int $relation_type
-     * @return resource
-     **/
-    public static function set_parent_group($group_id, $parent_group_id, $relation_type = 1)
-    {
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP_REL_GROUP);
-        $group_id = intval($group_id);
-        $parent_group_id = intval($parent_group_id);
-        if ($parent_group_id == 0) {
-            $sql = "DELETE FROM $table WHERE subgroup_id = $group_id";
-        } else {
-            $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
-            $res = Database::query($sql);
-            if (Database::num_rows($res) == 0) {
-                $sql = "INSERT INTO $table SET group_id = $parent_group_id, subgroup_id = $group_id, relation_type = $relation_type";
-            } else {
-                $sql = "UPDATE $table SET group_id = $parent_group_id, relation_type = $relation_type
-                        WHERE subgroup_id = $group_id";
-            }
-        }
-        $res = Database::query($sql);
-        return $res;
-    }
-
-    /**
-     * Get the parent group
-     * @param int $group_id
-     * @param int $relation_type
-     * @return int parent_group_id or false
-     * */
-    public static function get_parent_group($group_id, $relation_type = 1)
-    {
-        $table = Database :: get_main_table(TABLE_MAIN_GROUP_REL_GROUP);
-        $group_id = intval($group_id);
-        $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
-        $res = Database::query($sql);
-        if (Database::num_rows($res) == 0) {
-            return 0;
-        } else {
-            $arr = Database::fetch_assoc($res);
-            return $arr['group_id'];
-        }
-    }
-
-    /**
-     * Get the subgroups ID from a group.
-     * The default $levels value is 10 considering it as a extensive level of depth
-     * @param int $groupId The parent group ID
-     * @param int $levels The depth levels
-     * @return array The list of ID
-     */
-    public static function getGroupsByDepthLevel($groupId, $levels = 10)
-    {
-        $groups = array();
-        $groupId = intval($groupId);
-
-        $groupTable = Database::get_main_table(TABLE_MAIN_GROUP);
-        $groupRelGroupTable = Database :: get_main_table(TABLE_MAIN_GROUP_REL_GROUP);
-
-        $select = "SELECT ";
-        $from = "FROM $groupTable g1 ";
-
-        for ($i = 1; $i <= $levels; $i++) {
-            $tableIndexNumber = $i;
-            $tableIndexJoinNumber = $i - 1;
-
-            $select .= "g$i.id as id_$i ";
-
-            $select .= ($i != $levels ? ", " : null);
-
-            if ($i == 1) {
-                $from .= "INNER JOIN $groupRelGroupTable gg0 ON g1.id = gg0.subgroup_id and gg0.group_id = $groupId ";
-            } else {
-                $from .= "LEFT JOIN $groupRelGroupTable gg$tableIndexJoinNumber ";
-                $from .= " ON g$tableIndexJoinNumber.id = gg$tableIndexJoinNumber.group_id ";
-                $from .= "LEFT JOIN $groupTable g$tableIndexNumber ";
-                $from .= " ON gg$tableIndexJoinNumber.subgroup_id = g$tableIndexNumber.id ";
-            }
-        }
-
-        $result = Database::query("$select $from");
-
-        while ($item = Database::fetch_assoc($result)) {
-            foreach ($item as $groupId) {
-                if (!empty($groupId)) {
-                    $groups[] = $groupId;
-                }
-            }
-        }
-
-        return array_map('intval', $groups);
-    }
-
-    /**
-     * @param int $root
-     * @param int $level
-     * @return array
-     */
-    public static function get_subgroups($root, $level)
-    {
-        $t_group = Database::get_main_table(TABLE_MAIN_GROUP);
-        $t_rel_group = Database :: get_main_table(TABLE_MAIN_GROUP_REL_GROUP);
-        $select_part = "SELECT ";
-        $cond_part = '';
-        for ($i = 1; $i <= $level; $i++) {
-            $g_number = $i;
-            $rg_number = $i - 1;
-            if ($i == $level) {
-                $select_part .= "g$i.id as id_$i, g$i.name as name_$i ";
-            } else {
-                $select_part .= "g$i.id as id_$i, g$i.name name_$i, ";
-            }
-            if ($i == 1) {
-                $cond_part .= "FROM $t_group g1 JOIN $t_rel_group rg0 on g1.id = rg0.subgroup_id and rg0.group_id = $root ";
-            } else {
-                $cond_part .= "LEFT JOIN $t_rel_group rg$rg_number on g$rg_number.id = rg$rg_number.group_id ";
-                $cond_part .= "LEFT JOIN $t_group g$g_number on rg$rg_number.subgroup_id = g$g_number.id ";
-            }
-        }
-        $sql = $select_part.' '.$cond_part;
-        $res = Database::query($sql);
-        $toReturn = array();
-
-        while ($item = Database::fetch_assoc($res)) {
-            foreach ($item as $key => $value) {
-                if ($key == 'id_1') {
-                    $toReturn[$value]['name'] = $item['name_1'];
-                } else {
-                    $temp = explode('_', $key);
-                    $indexKey = $temp[1];
-                    $stringKey = $temp[0];
-                    $previousKey = $stringKey.'_'.$indexKey - 1;
-                    if ($stringKey == 'id' && isset($item[$key])) {
-                        $toReturn[$item[$previousKey]]['hrms'][$indexKey]['name'] = $item['name_'.$indexKey];
-                    }
-                }
-            }
-        }
-        return $toReturn;
-    }
-
-    /**
-     * @param int $group_id
-     * @return array
-     */
-    public static function get_parent_groups($group_id)
-    {
-        $t_rel_group = Database :: get_main_table(TABLE_MAIN_GROUP_REL_GROUP);
-        $max_level = 10;
-        $select_part = "SELECT ";
-        $cond_part = '';
-        for ($i = 1; $i <= $max_level; $i++) {
-            $g_number = $i;
-            $rg_number = $i - 1;
-            if ($i == $max_level) {
-                $select_part .= "rg$rg_number.group_id as id_$rg_number ";
-            } else {
-                $select_part .="rg$rg_number.group_id as id_$rg_number, ";
-            }
-            if ($i == 1) {
-                $cond_part .= "FROM $t_rel_group rg0 LEFT JOIN $t_rel_group rg$i on rg$rg_number.group_id = rg$i.subgroup_id ";
-            } else {
-                $cond_part .= " LEFT JOIN $t_rel_group rg$i on rg$rg_number.group_id = rg$i.subgroup_id ";
-            }
-        }
-        $sql = $select_part.' '.$cond_part."WHERE rg0.subgroup_id='$group_id'";
-        $res = Database::query($sql);
-        $temp_arr = Database::fetch_array($res, 'NUM');
-        $toReturn = array();
-        if (is_array($temp_arr)) {
-            foreach ($temp_arr as $elt) {
-                if (isset($elt)) {
-                    $toReturn[] = $elt;
-                }
-            }
-        }
-
-        return $toReturn;
-    }
-
-    /**
-     * Gets the tags from a given group
-     * @param int $group_id
-     * @param bool $show_tag_links show group links or not
-     *
-     */
-    public static function get_group_tags($group_id, $show_tag_links = true)
-    {
-        $tag = Database :: get_main_table(TABLE_MAIN_TAG);
-        $table_group_rel_tag = Database :: get_main_table(TABLE_MAIN_GROUP_REL_TAG);
-        $group_id = intval($group_id);
-
-        $sql = "SELECT tag FROM $tag t
-                INNER JOIN $table_group_rel_tag gt
-                ON (gt.tag_id= t.id)
-                WHERE
-                    gt.group_id = $group_id ";
-        $res = Database::query($sql);
-        $tags = array();
-        if (Database::num_rows($res) > 0) {
-            while ($row = Database::fetch_array($res, 'ASSOC')) {
-                $tags[] = $row;
-            }
-        }
-
-        if ($show_tag_links) {
-            if (is_array($tags) && count($tags) > 0) {
-                foreach ($tags as $tag) {
-                    $tag_tmp[] = '<a href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tag['tag'].'">'.$tag['tag'].'</a>';
-                }
-                if (is_array($tags) && count($tags) > 0) {
-                    $tags = implode(', ', $tag_tmp);
-                }
-            } else {
-                $tags = '';
-            }
-        }
-        return $tags;
-    }
-
-    /**
-     * Gets the inner join from users and group table
-     * @param string $user_id
-     * @param string $relation_type
-     * @param bool $with_image
-     * @return array Database::store_result of the result
-     * @author Julio Montoya
-     **/
-    public static function get_groups_by_user($user_id = '', $relation_type = GROUP_USER_PERMISSION_READER, $with_image = false)
-    {
-        $table_group_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $tbl_group = Database::get_main_table(TABLE_MAIN_GROUP);
-        $user_id = intval($user_id);
-
-        if ($relation_type == 0) {
-            $where_relation_condition = '';
-        } else {
-            $relation_type = intval($relation_type);
-            $where_relation_condition = "AND gu.relation_type = $relation_type ";
-        }
-
-        $sql = "SELECT g.picture_uri, g.name, g.description, g.id, gu.relation_type
-				FROM $tbl_group g
-				INNER JOIN $table_group_rel_user gu
-				ON gu.group_id = g.id
-				WHERE
-				    gu.user_id = $user_id $where_relation_condition
-				ORDER BY created_on desc ";
-
-        $result = Database::query($sql);
-        $array = array();
-        if (Database::num_rows($result) > 0) {
-            while ($row = Database::fetch_array($result, 'ASSOC')) {
-                if ($with_image) {
-                    $picture = self::get_picture_group($row['id'], $row['picture_uri'], 80);
-                    $img = '<img src="'.$picture['file'].'" />';
-                    $row['picture_uri'] = $img;
-                }
-                $array[$row['id']] = $row;
-            }
-        }
-        return $array;
-    }
-
-    /** Gets the inner join of users and group table
-     * @param int  quantity of records
-     * @param bool show groups with image or not
-     * @return array  with group content
-     * @author Julio Montoya
-     * */
-    public static function get_groups_by_popularity($num = 6, $with_image = true)
-    {
-        $table_group_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $tbl_group = Database::get_main_table(TABLE_MAIN_GROUP);
-        if (empty($num)) {
-            $num = 6;
-        } else {
-            $num = intval($num);
-        }
-        // only show admins and readers
-        $where_relation_condition = " WHERE gu.relation_type IN ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
-        $sql = "SELECT DISTINCT count(user_id) as count, g.picture_uri, g.name, g.description, g.id
-				FROM $tbl_group g
-				INNER JOIN $table_group_rel_user gu
-				ON gu.group_id = g.id $where_relation_condition
-				GROUP BY g.id
-				ORDER BY count DESC
-				LIMIT $num";
-
-        $result = Database::query($sql);
-        $array = array();
-        while ($row = Database::fetch_array($result, 'ASSOC')) {
-            if ($with_image) {
-                $picture = self::get_picture_group($row['id'], $row['picture_uri'], 80);
-                $img = '<img src="'.$picture['file'].'" />';
-                $row['picture_uri'] = $img;
-            }
-            if (empty($row['id'])) {
-                continue;
-            }
-            $array[$row['id']] = $row;
-        }
-        return $array;
-    }
-
-    /**
-     * Gets the last groups created
-     * @param int  quantity of records
-     * @param bool show groups with image or not
-     * @return array  with group content
-     * @author Julio Montoya
-     * */
-    public static function get_groups_by_age($num = 6, $with_image = true)
-    {
-        $table_group_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $tbl_group = Database::get_main_table(TABLE_MAIN_GROUP);
-
-        if (empty($num)) {
-            $num = 6;
-        } else {
-            $num = intval($num);
-        }
-        $where_relation_condition = " WHERE gu.relation_type IN ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
-        $sql = "SELECT DISTINCT count(user_id) as count, g.picture_uri, g.name, g.description, g.id
-                FROM $tbl_group g INNER JOIN $table_group_rel_user gu
-                ON gu.group_id = g.id
-                $where_relation_condition
-                GROUP BY g.id
-                ORDER BY created_on DESC
-                LIMIT $num ";
-
-        $result = Database::query($sql);
-        $array = array();
-        while ($row = Database::fetch_array($result, 'ASSOC')) {
-            if ($with_image) {
-                $picture = self::get_picture_group($row['id'], $row['picture_uri'], 80);
-                $img = '<img src="'.$picture['file'].'" />';
-                $row['picture_uri'] = $img;
-            }
-            if (empty($row['id'])) {
-                continue;
-            }
-            $array[$row['id']] = $row;
-        }
-        return $array;
-    }
-
-    /**
-     * Gets the group's members
-     * @param int group id
-     * @param bool show image or not of the group
-     * @param array list of relation type use constants
-     * @param int from value
-     * @param int limit
-     * @param array image configuration, i.e array('height'=>'20px', 'size'=> '20px')
-     * @return array list of users in a group
-     */
-    public static function get_users_by_group(
-        $group_id,
-        $with_image = false,
-        $relation_type = array(),
-        $from = null,
-        $limit = null,
-        $image_conf = array('size' => USER_IMAGE_SIZE_MEDIUM, 'height' => 80)
-    ) {
-        $table_group_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-        $group_id = intval($group_id);
-
-        if (empty($group_id)) {
-            return array();
-        }
-
-        $limit_text = '';
-        if (isset($from) && isset($limit)) {
-            $from = intval($from);
-            $limit = intval($limit);
-            $limit_text = "LIMIT $from, $limit";
-        }
-
-        if (count($relation_type) == 0) {
-            $where_relation_condition = '';
-        } else {
-            $new_relation_type = array();
-            foreach ($relation_type as $rel) {
-                $rel = intval($rel);
-                $new_relation_type[] = "'$rel'";
-            }
-            $relation_type = implode(',', $new_relation_type);
-            if (!empty($relation_type))
-                $where_relation_condition = "AND gu.relation_type IN ($relation_type) ";
-        }
-
-        $sql = "SELECT
-                    picture_uri as image,
-                    u.id,
-                    u.firstname,
-                    u.lastname,
-                    relation_type
-    		    FROM $tbl_user u INNER JOIN $table_group_rel_user gu
-    			ON (gu.user_id = u.id)
-    			WHERE
-    			    gu.group_id= $group_id
-    			    $where_relation_condition
-    			ORDER BY relation_type, firstname $limit_text";
-
-        $result = Database::query($sql);
-        $array = array();
-        while ($row = Database::fetch_array($result, 'ASSOC')) {
-            if ($with_image) {
-                $picture = UserManager::getUserPicture($row['id']);
-                $row['image'] = '<img src="'.$picture.'" />';
-            }
-            $array[$row['id']] = $row;
-        }
-
-        return $array;
-    }
-
-    /**
-     * Gets all the members of a group no matter the relationship for more specifications use get_users_by_group
-     * @param int group id
-     * @return array
-     */
-    public static function get_all_users_by_group($group_id)
-    {
-        $table_group_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-        $group_id = intval($group_id);
-
-        if (empty($group_id)) {
-            return array();
-        }
-        $sql = "SELECT u.id, u.firstname, u.lastname, relation_type
-                FROM $tbl_user u
-                INNER JOIN $table_group_rel_user gu
-                ON (gu.user_id = u.id)
-                WHERE gu.group_id= $group_id
-                ORDER BY relation_type, firstname";
-
-        $result = Database::query($sql);
-        $array = array();
-        while ($row = Database::fetch_array($result, 'ASSOC')) {
-            $array[$row['id']] = $row;
-        }
-        return $array;
-    }
-
-    /**
-     * Gets the relationship between a group and a User
-     * @author Julio Montoya
-     * @param int user id
-     * @param int group_id
-     * @return int 0 if there are not relationship otherwise returns the user group
-     * */
-    public static function get_user_group_role($user_id, $group_id)
-    {
-        $em = Database::getManager();
-
-        $result = $em
-            ->getRepository('ChamiloCoreBundle:UsergroupRelUser')
-            ->findOneBy([
-                'usergroup' => intval($group_id),
-                'user' => intval($user_id)
-            ]);
-
-        if (!$result) {
-            return 0;
-        }
-
-        return $result->getRelationType();
-    }
-
-    /**
-     * Add a user into a group
-     * @author Julio Montoya
-     * @param  int user_id
-     * @param  int url_id
-     * @return boolean true if success
-     **/
-    public static function add_user_to_group($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
-    {
-        $result = false;
-
-        if (empty($user_id) || empty($group_id)) {
-            return false;
-        }
-
-        $em = Database::getManager();
-
-        $user = $em->find('ChamiloCoreBundle:User', $user_id);
-        $usergroup = $em->find('ChamiloCoreBundle:Usergroup', $group_id);
-        $role = self::get_user_group_role($user_id, $group_id);
-
-        if ($role == 0) {
-            $usergroupRelUser = new \Chamilo\CoreBundle\Entity\UsergroupRelUser();
-            $usergroupRelUser
-                ->setUser($user)
-                ->setUsergroup($usergroup)
-                ->setRelationType($relation_type);
-
-            $em->persist($usergroupRelUser);
-            $em->flush();
-
-            Event::addEvent(
-                LOG_GROUP_PORTAL_USER_SUBSCRIBED,
-                LOG_GROUP_PORTAL_REL_USER_ARRAY,
-                array(
-                    'user_id' => $user_id,
-                    'group_id' => $group_id,
-                    'relation_type' => $relation_type,
-                )
-            );
-
-            return true;
-        } else if ($role == GROUP_USER_PERMISSION_PENDING_INVITATION) {
-            // If somebody already invited me I can be added
-            self::update_user_role(
-                $user_id,
-                $group_id,
-                GROUP_USER_PERMISSION_READER
-            );
-
-            return true;
-        }
-
-        return $result;
-    }
-
-    /**
-     * Add a group of users into a group of URLs
-     * @author Julio Montoya
-     * @param  array $user_list of user_ids
-     * @param  array $group_list of url_ids
-     * @param string $relation_type
-     **/
-    public static function add_users_to_groups($user_list, $group_list, $relation_type = GROUP_USER_PERMISSION_READER)
-    {
-        $result_array = array();
-        $relation_type = intval($relation_type);
-
-        if (is_array($user_list) && is_array($group_list)) {
-            foreach ($group_list as $group_id) {
-                foreach ($user_list as $user_id) {
-                    $result = self::add_user_to_group($user_id, $group_id, $relation_type);
-                    if ($result) {
-                        $result_array[$group_id][$user_id] = 1;
-                    } else {
-                        $result_array[$group_id][$user_id] = 0;
-                    }
-                }
-            }
-        }
-        return $result_array;
-    }
-
-    /**
-     * Deletes a group and user relationship
-     * @author Julio Montoya
-     * @param int $group_id
-     * @param int $relation_type (optional)
-     * @return boolean true if success
-     * */
-    public static function delete_users($group_id, $relation_type = null)
-    {
-        $table = Database :: get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $condition_relation = "";
-        if (!empty($relation_type)) {
-            $relation_type = intval($relation_type);
-            $condition_relation = " AND relation_type = '$relation_type'";
-        }
-        $sql = "DELETE FROM $table
-                WHERE group_id = ".intval($group_id).$condition_relation;
-        $result = Database::query($sql);
-
-        Event::addEvent(
-            LOG_GROUP_PORTAL_USER_DELETE_ALL,
-            LOG_GROUP_PORTAL_REL_USER_ARRAY,
-            array('group_id' => $group_id, 'relation_type' => $relation_type)
-        );
-
-        return $result;
-    }
-
-    /**
-     * Deletes an url and session relationship
-     * @author Julio Montoya
-     * @param  int $user_id
-     * @param  int $group_id
-     * @return boolean true if success
-     * */
-    public static function delete_user_rel_group($user_id, $group_id)
-    {
-        $em = Database::getManager();
-
-        $result = $em
-            ->getRepository('ChamiloCoreBundle:UsergroupRelUser')
-            ->findOneBy([
-                'usergroup' => intval($group_id),
-                'user' => intval($user_id)
-            ]);
-
-        if (!$result) {
-            return false;
-        }
-
-        $em->remove($result);
-        $em->flush();
-
-        Event::addEvent(
-            LOG_GROUP_PORTAL_USER_UNSUBSCRIBED,
-            LOG_GROUP_PORTAL_REL_USER_ARRAY,
-            array('user_id' => $user_id, 'group_id' => $group_id)
-        );
-
-        return true;
-    }
-
-    /**
-     * Updates the group_rel_user table  with a given user and group ids
-     * @author Julio Montoya
-     * @param int  $user_id
-     * @param int  $group_id
-     * @param int  $relation_type
-     *
-     * @return bool
-     **/
-    public static function update_user_role($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
-    {
-        if (empty($user_id) || empty($group_id) || empty($relation_type)) {
-            return false;
-        }
-
-        $em = Database::getManager();
-        $group_id = intval($group_id);
-        $user_id = intval($user_id);
-
-        $usergroupUser = $em
-            ->getRepository('ChamiloCoreBundle:UsergroupRelUser')
-            ->findOneBy([
-                'user' => $user_id,
-                'usergroup' => $group_id
-            ]);
-
-        if (!$usergroupUser) {
-            return false;
-        }
-
-        $usergroupUser->setRelationType($relation_type);
-
-        $em->merge($usergroupUser);
-        $em->flush();
-
-        Event::addEvent(
-            LOG_GROUP_PORTAL_USER_UPDATE_ROLE,
-            LOG_GROUP_PORTAL_REL_USER_ARRAY,
-            array('user_id' => $user_id, 'group_id' => $group_id, 'relation_type' => $relation_type)
-        );
-        return true;
-
-    }
-
-    /**
-     * @param int $user_id
-     * @param int $group_id
-     */
-    public static function get_group_admin_list($user_id, $group_id)
-    {
-        $table_group_rel_user = Database :: get_main_table(TABLE_MAIN_USER_REL_GROUP);
-        $group_id = intval($group_id);
-        $user_id = intval($user_id);
-
-        $sql = "SELECT user_id FROM  $table_group_rel_user
-                WHERE
-                    relation_type = ".GROUP_USER_PERMISSION_ADMIN." AND
-                    user_id = $user_id AND
-                    group_id = $group_id";
-        Database::query($sql);
-    }
-
-    /**
-     * @param string $tag
-     * @param int $from
-     * @param int $number_of_items
-     * @param bool $getCount
-     * @return array
-     */
-    public static function get_all_group_tags($tag, $from = 0, $number_of_items = 10, $getCount = false)
-    {
-        // Database table definition
-        $group_table = Database::get_main_table(TABLE_MAIN_GROUP);
-        $table_tag = Database::get_main_table(TABLE_MAIN_TAG);
-        $table_group_tag_values = Database::get_main_table(TABLE_MAIN_GROUP_REL_TAG);
-        $field_id = 5;
-        $from = intval($from);
-        $number_of_items = intval($number_of_items);
-
-        // all the information of the field
-        if ($getCount) {
-            $select = "SELECT count(DISTINCT g.id) count";
-        } else {
-            $select = " SELECT DISTINCT g.id, g.name, g.description, g.picture_uri ";
-        }
-        $sql = " $select
-                FROM $group_table g
-                LEFT JOIN $table_group_tag_values tv ON (g.id AND tv.group_id)
-                LEFT JOIN $table_tag t ON (tv.tag_id = t.id)
-                WHERE
-                    tag LIKE '$tag%' AND field_id= $field_id OR
-                    (
-                       g.name LIKE '".Database::escape_string('%'.$tag.'%')."' OR
-                       g.description LIKE '".Database::escape_string('%'.$tag.'%')."' OR
-                       g.url LIKE '".Database::escape_string('%'.$tag.'%')."'
-                     )";
-
-        $sql .= " LIMIT $from, $number_of_items";
-
-        $result = Database::query($sql);
-        $return = array();
-        if (Database::num_rows($result) > 0) {
-            if ($getCount) {
-                $row = Database::fetch_array($result, 'ASSOC');
-                return $row['count'];
-            }
-            while ($row = Database::fetch_array($result, 'ASSOC')) {
-                $return[$row['id']] = $row;
-            }
-        }
-
-        return $return;
-    }
-
-    /**
-     * Creates new group pictures in various sizes of a user, or deletes user photos.
-     * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
-     * @param int	The group id
-     * @param string $file The common file name for the newly created photos.
-     * It will be checked and modified for compatibility with the file system.
-     * If full name is provided, path component is ignored.
-     * If an empty name is provided, then old user photos are deleted only, @see UserManager::delete_user_picture()
-     * as the prefered way for deletion.
-     * @param	string		$source_file The full system name of the image from which user photos will be created.
-     * @return	string/bool	Returns the resulting file name of created images which usually should be stored in DB.
-     * When deletion is recuested returns empty string. In case of internal error or negative validation returns FALSE.
-     */
-    public static function update_group_picture($group_id, $file = null, $source_file = null)
-    {
-        // Validation.
-        if (empty($group_id)) {
-            return false;
-        }
-        $delete = empty($file);
-        if (empty($source_file)) {
-            $source_file = $file;
-        }
-
-        // User-reserved directory where photos have to be placed.
-        $path_info = self::get_group_picture_path_by_id($group_id, 'system', true);
-
-        $path = $path_info['dir'];
-        // If this directory does not exist - we create it.
-        if (!file_exists($path)) {
-            @mkdir($path, api_get_permissions_for_new_directories(), true);
-        }
-
-        // The old photos (if any).
-        $old_file = $path_info['file'];
-
-        // Let us delete them.
-        if (!empty($old_file)) {
-            if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
-                $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
-                @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
-                @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
-                @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
-                @rename($path.$old_file, $path.$prefix.$old_file);
-            } else {
-                @unlink($path.'small_'.$old_file);
-                @unlink($path.'medium_'.$old_file);
-                @unlink($path.'big_'.$old_file);
-                @unlink($path.$old_file);
-            }
-        }
-
-        // Exit if only deletion has been requested. Return an empty picture name.
-        if ($delete) {
-            return '';
-        }
-
-        // Validation 2.
-        $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
-        $file = str_replace('\\', '/', $file);
-        $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
-        $extension = strtolower(substr(strrchr($filename, '.'), 1));
-        if (!in_array($extension, $allowed_types)) {
-            return false;
-        }
-
-        // This is the common name for the new photos.
-        if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
-            $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
-            $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
-            $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
-        } else {
-            $filename = api_replace_dangerous_char($filename);
-            if (PREFIX_IMAGE_FILENAME_WITH_UID) {
-                $filename = uniqid('').'_'.$filename;
-            }
-            // We always prefix user photos with user ids, so on setting
-            // api_get_setting('split_users_upload_directory') === 'true'
-            // the correspondent directories to be found successfully.
-            $filename = $group_id.'_'.$filename;
-        }
-
-        // Storing the new photos in 4 versions with various sizes.
-
-        $small = self::resize_picture($source_file, 22);
-        $medium = self::resize_picture($source_file, 85);
-        $normal = self::resize_picture($source_file, 200);
-
-        $big = new Image($source_file); // This is the original picture.
-        $ok = $small && $small->send_image($path.'small_'.$filename)
-            && $medium && $medium->send_image($path.'medium_'.$filename)
-            && $normal && $normal->send_image($path.'big_'.$filename)
-            && $big && $big->send_image($path.$filename);
-
-        return $ok ? $filename : false;
-    }
-
-    /**
-     * Gets the group picture URL or path from group ID (returns an array).
-     * The return format is a complete path, enabling recovery of the directory
-     * with dirname() or the file with basename(). This also works for the
-     * functions dealing with the user's productions, as they are located in
-     * the same directory.
-     * @internal Don't delete this function
-     * @param	integer	$id
-     * @param	string	$type Type of path to return (can be 'system', 'web')
-     * @param	bool	$preview Whether we want to have the directory name returned 'as if' there was a file or not
-     * (in the case we want to know which directory to create - otherwise no file means no split subdir)
-     * @param	bool	$anonymous If we want that the function returns the /main/img/unknown.jpg image set it at true
-     *
-     * @return	array 	Array of 2 elements: 'dir' and 'file' which contain the dir and file as the name implies
-     * if image does not exist it will return the unknow image if anonymous parameter is true if not it returns an empty
-     */
-    public static function get_group_picture_path_by_id($id, $type = 'web', $preview = false, $anonymous = false)
-    {
-        switch ($type) {
-            case 'system': // Base: absolute system path.
-                $base = api_get_path(SYS_UPLOAD_PATH);
-                break;
-            case 'web': // Base: absolute web path.
-            default:
-                $base = api_get_path(WEB_UPLOAD_PATH);
-                break;
-        }
-
-        $noPicturePath = array('dir' => $base.'img/', 'file' => 'unknown.jpg');
-
-        if (empty($id) || empty($type)) {
-            return $anonymous ? $noPicturePath : array('dir' => '', 'file' => '');
-        }
-
-        $id = intval($id);
-
-        $group_table = Database :: get_main_table(TABLE_MAIN_GROUP);
-        $sql = "SELECT picture_uri FROM $group_table WHERE id=".$id;
-        $res = Database::query($sql);
-
-        if (!Database::num_rows($res)) {
-            return $anonymous ? $noPicturePath : array('dir' => '', 'file' => '');
-        }
-
-        $user = Database::fetch_array($res);
-        $picture_filename = trim($user['picture_uri']);
-
-        if (api_get_setting('split_users_upload_directory') === 'true') {
-            if (!empty($picture_filename)) {
-                $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
-            } elseif ($preview) {
-                $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
-            } else {
-                $dir = $base.'groups/'.$id.'/';
-            }
-        } else {
-            $dir = $base.'groups/'.$id.'/';
-        }
-
-        if (empty($picture_filename) && $anonymous) {
-            return $noPicturePath;
-        }
-
-        return array('dir' => $dir, 'file' => $picture_filename);
-    }
-
-    /**
-     * Resize a picture
-     *
-     * @param  string file picture
-     * @param  int size in pixels
-     * @return obj image object
-     */
-    public static function resize_picture($file, $max_size_for_picture)
-    {
-        $temp = new Image($file);
-        $picture_infos = api_getimagesize($file);
-        if ($picture_infos['width'] > $max_size_for_picture) {
-            $thumbwidth = $max_size_for_picture;
-            if (empty($thumbwidth) or $thumbwidth == 0) {
-                $thumbwidth = $max_size_for_picture;
-            }
-            $new_height = round(($thumbwidth / $picture_infos['width']) * $picture_infos['height']);
-            if ($new_height > $max_size_for_picture)
-                $new_height = $thumbwidth;
-            $temp->resize($thumbwidth, $new_height, 0);
-        }
-
-        return $temp;
-    }
-
-    /**
-     * Gets the current group image
-     * @param string $id group id
-     * @param string $picture_file picture group name
-     * @param string $height
-     * @param string $size_picture picture size it can be small_, medium_or big_
-     * @param string $style css
-     * @return array with the file and the style of an image i.e $array['file'] $array['style']
-     */
-    public static function get_picture_group(
-        $id,
-        $picture_file,
-        $height,
-        $size_picture = GROUP_IMAGE_SIZE_MEDIUM,
-        $style = ''
-    ) {
-        $picture = array();
-        $picture['style'] = $style;
-        if ($picture_file == 'unknown.jpg') {
-            $picture['file'] = api_get_path(WEB_CODE_PATH).'img/'.$picture_file;
-            return $picture;
-        }
-
-        switch ($size_picture) {
-            case GROUP_IMAGE_SIZE_ORIGINAL:
-                $size_picture = '';
-                break;
-            case GROUP_IMAGE_SIZE_BIG:
-                $size_picture = 'big_';
-                break;
-            case GROUP_IMAGE_SIZE_MEDIUM:
-                $size_picture = 'medium_';
-                break;
-            case GROUP_IMAGE_SIZE_SMALL:
-                $size_picture = 'small_';
-                break;
-            default:
-                $size_picture = 'medium_';
-        }
-
-        $image_array_sys = self::get_group_picture_path_by_id($id, 'system', false, true);
-        $image_array = self::get_group_picture_path_by_id($id, 'web', false, true);
-        $file = $image_array_sys['dir'].$size_picture.$picture_file;
-        if (file_exists($file)) {
-            $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
-            $picture['style'] = '';
-            if ($height > 0) {
-                $dimension = api_getimagesize($picture['file']);
-                $margin = (($height - $dimension['width']) / 2);
-                //@ todo the padding-top should not be here
-                $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension['width'].'px; height:'.$dimension['height'].';" ';
-            }
-        } else {
-            $file = $image_array_sys['dir'].$picture_file;
-            if (file_exists($file) && !is_dir($file)) {
-                $picture['file'] = $image_array['dir'].$picture_file;
-            } else {
-                $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_group.png';
-            }
-        }
-        return $picture;
-    }
-
-    /**
-     * @param int $group_id
-     * @return string
-     */
-    public static function delete_group_picture($group_id)
-    {
-        return self::update_group_picture($group_id);
-    }
-
-    /**
-     * @param int $group_id
-     * @param int $user_id
-     * @return bool
-     */
-    public static function is_group_admin($group_id, $user_id = 0)
-    {
-        if (empty($user_id)) {
-            $user_id = api_get_user_id();
-        }
-        $user_role = GroupPortalManager::get_user_group_role($user_id, $group_id);
-        if (in_array($user_role, array(GROUP_USER_PERMISSION_ADMIN))) {
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * @param int $group_id
-     * @param int $user_id
-     * @return bool
-     */
-    public static function is_group_moderator($group_id, $user_id = 0)
-    {
-        if (empty($user_id)) {
-            $user_id = api_get_user_id();
-        }
-        $user_role = GroupPortalManager::get_user_group_role($user_id, $group_id);
-        if (in_array($user_role, array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR))) {
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * @param int $group_id
-     * @param int $user_id
-     * @return bool
-     */
-    public static function is_group_member($group_id, $user_id = 0)
-    {
-        if (empty($user_id)) {
-            $user_id = api_get_user_id();
-        }
-        $user_role = GroupPortalManager::get_user_group_role($user_id, $group_id);
-        $permissions = array(
-            GROUP_USER_PERMISSION_ADMIN,
-            GROUP_USER_PERMISSION_MODERATOR,
-            GROUP_USER_PERMISSION_READER,
-            GROUP_USER_PERMISSION_HRM
-        );
-
-        if (in_array($user_role, $permissions)) {
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * Shows the left column of the group page
-     * @param int $group_id
-     * @param int $user_id
-     *
-     */
-    public static function show_group_column_information($group_id, $user_id, $show = '')
-    {
-        global $relation_group_title, $my_group_role;
-        $html = '';
-
-        $group_info = GroupPortalManager::get_group_data($group_id);
-        // My relation with the group is set here.
-        $my_group_role = self::get_user_group_role($user_id, $group_id);
-
-        //@todo this must be move to default.css for dev use only
-        $html .= '<style>
-				#group_members { width:270px; height:300px; overflow-x:none; overflow-y: auto;}
-				.group_member_item { width:100px; height:130px; float:left; margin:5px 5px 15px 5px; }
-				.group_member_picture { display:block;
-					margin:0;
-					overflow:hidden; };
-		</style>';
-
-        //Loading group permission
-
-        $links = '';
-        switch ($my_group_role) {
-            case GROUP_USER_PERMISSION_READER:
-                // I'm just a reader
-                $relation_group_title = get_lang('IAmAReader');
-                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace' => '6')).'<span class="'.($show == 'invite_friends' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
-                if (GroupPortalManager::canLeave($group_info)) {
-                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.Display::return_icon('group_leave.png', get_lang('LeaveGroup'), array('hspace' => '6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
-                }
-                break;
-            case GROUP_USER_PERMISSION_ADMIN:
-                $relation_group_title = get_lang('IAmAnAdmin');
-                $links .= '<li><a href="group_edit.php?id='.$group_id.'">'.Display::return_icon('group_edit.png', get_lang('EditGroup'), array('hspace' => '6')).'<span class="'.($show == 'group_edit' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('EditGroup').'</span></a></li>';
-                $links .= '<li><a href="group_waiting_list.php?id='.$group_id.'">'.Display::return_icon('waiting_list.png', get_lang('WaitingList'), array('hspace' => '6')).'<span class="'.($show == 'waiting_list' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('WaitingList').'</span></a></li>';
-                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace' => '6')).'<span class="'.($show == 'invite_friends' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
-                if (GroupPortalManager::canLeave($group_info)) {
-                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.Display::return_icon('group_leave.png', get_lang('LeaveGroup'), array('hspace' => '6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
-                }
-                break;
-            case GROUP_USER_PERMISSION_PENDING_INVITATION:
-//				$links .=  '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('YouHaveBeenInvitedJoinNow'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('YouHaveBeenInvitedJoinNow').'</span></a></li>';
-                break;
-            case GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER:
-                $relation_group_title = get_lang('WaitingForAdminResponse');
-                break;
-            case GROUP_USER_PERMISSION_MODERATOR:
-                $relation_group_title = get_lang('IAmAModerator');
-                if ($group_info['visibility'] == GROUP_PERMISSION_CLOSED) {
-                    $links .= '<li><a href="group_waiting_list.php?id='.$group_id.'">'.Display::return_icon('waiting_list.png', get_lang('WaitingList'), array('hspace' => '6')).'<span class="'.($show == 'waiting_list' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('WaitingList').'</span></a></li>';
-                }
-                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace' => '6')).'<span class="'.($show == 'invite_friends' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
-                if (GroupPortalManager::canLeave($group_info)) {
-                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.Display::return_icon('group_leave.png', get_lang('LeaveGroup'), array('hspace' => '6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
-                }
-                break;
-            case GROUP_USER_PERMISSION_HRM:
-                $relation_group_title = get_lang('IAmAHRM');
-                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="ajax" data-size="lg" data-title="'.get_lang('ComposeMessage').' title="'.get_lang('ComposeMessage').'">'.Display::return_icon('new-message.png', get_lang('NewTopic'), array('hspace' => '6')).'<span class="social-menu-text4" >'.get_lang('NewTopic').'</span></a></li>';
-                $links .= '<li><a href="group_view.php?id='.$group_id.'">'.Display::return_icon('message_list.png', get_lang('MessageList'), array('hspace' => '6')).'<span class="'.($show == 'messages_list' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('MessageList').'</span></a></li>';
-                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace' => '6')).'<span class="'.($show == 'invite_friends' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
-                $links .= '<li><a href="group_members.php?id='.$group_id.'">'.Display::return_icon('member_list.png', get_lang('MemberList'), array('hspace' => '6')).'<span class="'.($show == 'member_list' ? 'social-menu-text-active' : 'social-menu-text4').'" >'.get_lang('MemberList').'</span></a></li>';
-                $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.Display::return_icon('delete_data.gif', get_lang('LeaveGroup'), array('hspace' => '6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
-                break;
-            default:
-                //$links .=  '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('JoinGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('JoinGroup').'</a></span></li>';
-                break;
-        }
-
-        if (!empty($links)) {
-            $html .= '<div class="well sidebar-nav"><ul class="nav nav-list">';
-            if (!empty($group_info['description'])) {
-                $html .= Display::tag('li', Security::remove_XSS($group_info['description'], STUDENT, true), array('class' => 'group_description'));
-            }
-            $html .= $links;
-            $html .= '</ul></div>';
-        }
-        return $html;
-    }
-
-    /**
-     * @param int $group_id
-     * @param int $topic_id
-     */
-    function delete_topic($group_id, $topic_id)
-    {
-        $table_message = Database::get_main_table(TABLE_MESSAGE);
-        $topic_id = intval($topic_id);
-        $group_id = intval($group_id);
-        $sql = "UPDATE $table_message SET msg_status=3
-                WHERE group_id = $group_id AND (id = '$topic_id' OR parent_id = $topic_id) ";
-        Database::query($sql);
-    }
-
-    /**
-     * @param int  $user_id
-     * @param int  $relation_type
-     * @param bool $with_image
-     * @return int
-     */
-    public static function get_groups_by_user_count($user_id = null, $relation_type = GROUP_USER_PERMISSION_READER, $with_image = false)
-    {
-        $table_group_rel_user	= Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
-		$tbl_group				= Database::get_main_table(TABLE_MAIN_GROUP);
-		$user_id = intval($user_id);
-
-		if ($relation_type == 0) {
-			$where_relation_condition = '';
-		} else {
-			$relation_type 			= intval($relation_type);
-			$where_relation_condition = "AND gu.relation_type = $relation_type ";
-		}
-
-		$sql = "SELECT count(g.id) as count
-				FROM $tbl_group g
-				INNER JOIN $table_group_rel_user gu
-				ON gu.group_id = g.id WHERE gu.user_id = $user_id $where_relation_condition ";
-
-		$result = Database::query($sql);
-		if (Database::num_rows($result) > 0) {
-			$row = Database::fetch_array($result, 'ASSOC');
-            return $row['count'];
-		}
-		return 0;
-    }
-
-    /**
-     * @param FormValidator $form
-     * @param array
-     *
-     * @return FormValidator
-     */
-    public static function setGroupForm($form, $groupData = array())
-    {
-        // Name
-        $form->addElement('text', 'name', get_lang('Name'), array('maxlength'=>120));
-        $form->applyFilter('name', 'html_filter');
-        $form->applyFilter('name', 'trim');
-        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-
-        // Description
-        $form->addElement(
-            'textarea',
-            'description',
-            get_lang('Description'),
-            array(
-                'cols' => 58,
-                'onKeyDown' => "textarea_maxlength()",
-                'onKeyUp' => "textarea_maxlength()",
-            )
-        );
-        $form->applyFilter('description', 'html_filter');
-        $form->applyFilter('description', 'trim');
-        $form->addRule('name', '', 'maxlength', 255);
-
-        // Url
-        $form->addElement('text', 'url', 'URL');
-        $form->applyFilter('url', 'html_filter');
-        $form->applyFilter('url', 'trim');
-
-        // Picture
-        $form->addElement('file', 'picture', get_lang('AddPicture'));
-        $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-        $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
-
-        if (!empty($groupData)) {
-            if (isset($groupData['picture_uri']) && strlen($groupData['picture_uri']) > 0) {
-                $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
-            }
-        }
-
-        // Status
-        $status = array();
-        $status[GROUP_PERMISSION_OPEN] = get_lang('Open');
-        $status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
-        $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $status, array());
-
-        if (!empty($groupData)) {
-            if (self::canLeaveFeatureEnabled($groupData)) {
-                $form->addElement('checkbox', 'allow_members_leave_group', '', get_lang('AllowMemberLeaveGroup'));
-            }
-            // Set default values
-            $form->setDefaults($groupData);
-        }
-
-        return $form;
-    }
-
-    /**
-     * Check if the can leave feature exists.
-     * @param array $groupData
-     * @return bool
-     */
-    public static function canLeaveFeatureEnabled($groupData)
-    {
-        if (isset($groupData['allow_members_leave_group'])) {
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * @param array $groupData
-     * @return bool
-     */
-    public static function canLeave($groupData)
-    {
-        if (self::canLeaveFeatureEnabled($groupData)) {
-            return $groupData['allow_members_leave_group'] == 1 ? true : false;
-        }
-        return true;
-    }
-
-    /**
-     * Get the group member list by a user and his group role
-     * @param int $userId The user ID
-     * @param int $relationType Optional. The relation type. GROUP_USER_PERMISSION_ADMIN by default
-     * @param boolean $includeSubgroupsUsers Optional. Whether include the users from subgroups
-     * @return array
-     */
-    public static function getGroupUsersByUser(
-        $userId,
-        $relationType = GROUP_USER_PERMISSION_ADMIN,
-        $includeSubgroupsUsers = true
-    )
-    {
-        $userId = intval($userId);
-
-        $groups = GroupPortalManager::get_groups_by_user($userId, $relationType);
-
-        $groupsId = array_keys($groups);
-        $subgroupsId = [];
-        $userIdList = [];
-
-        if ($includeSubgroupsUsers) {
-            foreach ($groupsId as $groupId) {
-                $subgroupsId = array_merge($subgroupsId, GroupPortalManager::getGroupsByDepthLevel($groupId));
-            }
-
-            $groupsId = array_merge($groupsId, $subgroupsId);
-        }
-
-        $groupsId = array_unique($groupsId);
-
-        if (empty($groupsId)) {
-            return [];
-        }
-
-        foreach ($groupsId as $groupId) {
-            $groupUsers = GroupPortalManager::get_users_by_group($groupId);
-
-            if (empty($groupUsers)) {
-                continue;
-            }
-
-            foreach ($groupUsers as $member) {
-                if ($member['user_id'] == $userId) {
-                    continue;
-                }
-
-                $userIdList[] = intval($member['user_id']);
-            }
-        }
-
-        return array_unique($userIdList);
-    }
-
-}

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

@@ -694,7 +694,7 @@ class Template
             'bootstrap/dist/js/bootstrap.min.js',
             'jquery-ui/jquery-ui.min.js',
             'moment/min/moment-with-locales.min.js',
-            'ckeditor/ckeditor.js',
+            api_is_anonymous() ? '' : 'ckeditor/ckeditor.js',
             'bootstrap-daterangepicker/daterangepicker.js',
             'jquery-timeago/jquery.timeago.js',
             'mediaelement/build/mediaelement-and-player.min.js',

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

@@ -345,7 +345,7 @@ class UrlManager
         }
         $where .= " AND (parent_id IS NULL) ";
 
-        $sql = "SELECT id, name, access_url_id
+        $sql = "SELECT u.id, name, access_url_id
                 FROM $table u
                 INNER JOIN $table_url_rel
                 ON $table_url_rel.course_category_id = u.id

+ 99 - 23
main/inc/lib/usermanager.lib.php

@@ -4138,7 +4138,7 @@ class UserManager
      * @param array $subscribedUsersId The id of suscribed users
      * @param action $relationType The relation type
      */
-    public static function subscribeUsersToUser($userId, $subscribedUsersId, $relationType)
+    public static function subscribeUsersToUser($userId, $subscribedUsersId, $relationType, $deleteUsersBeforeInsert = false)
     {
         $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -4148,40 +4148,48 @@ class UserManager
         $affectedRows = 0;
 
         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() . "";
+            // 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();
         } 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";
-
+                $sql = "DELETE FROM $userRelUserTable 
+                        WHERE 
+                          user_id = {$row['user_id']} AND 
+                          friend_user_id = $userId AND 
+                          relation_type = $relationType";
                 Database::query($sql);
             }
         }
 
+        if ($deleteUsersBeforeInsert) {
+            $sql = "DELETE FROM $userRelUserTable 
+                    WHERE 
+                        user_id = $userId AND
+                        relation_type = $relationType";
+            Database::query($sql);
+        }
+
         // Inserting new user list
         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)";
+                $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
+                        VALUES ($subscribedUserId, $userId, $relationType)";
 
                 $result = Database::query($sql);
-
                 $affectedRows = Database::affected_rows($result);
             }
         }
@@ -4823,16 +4831,44 @@ EOF;
     }
 
     /**
-     * Subscribe users to student boss
+     * Subscribe boss to students
+     * 
      * @param int $bossId The boss id
      * @param array $usersId The users array
      * @return int Affected rows
      */
-    public static function subscribeUsersToBoss($bossId, $usersId)
+    public static function subscribeBossToUsers($bossId, $usersId)
     {
         return self::subscribeUsersToUser($bossId, $usersId, USER_RELATION_TYPE_BOSS);
     }
 
+    /**
+     * Subscribe boss to students
+     *
+     * @param int $studentId
+     * @param array $bossList
+     * @return int Affected rows
+     */
+    public static function subscribeUserToBossList($studentId, $bossList)
+    {
+        $count = 1;
+        if ($bossList) {
+            $studentId = (int) $studentId;
+            $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
+            $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+            $sql = "DELETE FROM $userRelUserTable 
+                    WHERE user_id = $studentId AND relation_type = ".USER_RELATION_TYPE_BOSS;
+            Database::query($sql);
+
+            foreach ($bossList as $bossId) {
+                $sql = "INSERT IGNORE INTO $userRelUserTable (user_id, friend_user_id, relation_type)
+                        VALUES ($studentId, $bossId, ".USER_RELATION_TYPE_BOSS.")";
+
+                Database::query($sql);
+            }
+        }
+    }
+
     /**
      * Get users followed by student boss
      * @param int $userId
@@ -4862,8 +4898,18 @@ EOF;
         $lastConnectionDate = null
     ){
         return self::getUsersFollowedByUser(
-                $userId, $userStatus, $getOnlyUserId, $getSql, $getCount, $from, $numberItems, $column, $direction,
-                $active, $lastConnectionDate, STUDENT_BOSS
+            $userId,
+            $userStatus,
+            $getOnlyUserId,
+            $getSql,
+            $getCount,
+            $from,
+            $numberItems,
+            $column,
+            $direction,
+            $active,
+            $lastConnectionDate,
+            STUDENT_BOSS
         );
     }
 
@@ -4977,7 +5023,7 @@ EOF;
      * @param $userId
      * @return bool
      */
-    public static function getStudentBoss($userId)
+    public static function getFirstStudentBoss($userId)
     {
         $userId = intval($userId);
         if ($userId > 0) {
@@ -5003,6 +5049,36 @@ EOF;
         return false;
     }
 
+    /**
+     * Get the boss user ID from a followed user id
+     * @param $userId
+     * @return bool
+     */
+    public static function getStudentBossList($userId)
+    {
+        $userId = intval($userId);
+        if ($userId > 0) {
+            $userRelTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
+            $result = Database::select(
+                'DISTINCT friend_user_id AS boss_id',
+                $userRelTable,
+                array(
+                    'where' => array(
+                        'user_id = ? AND relation_type = ? ' => array(
+                            $userId,
+                            USER_RELATION_TYPE_BOSS,
+                        )
+                    )
+                ),
+                'all'
+            );
+
+            return $result;
+        }
+
+        return false;
+    }
+
     /**
      * Get either a Gravatar URL or complete image tag for a specified email address.
      *

+ 0 - 555
main/install/install.lib.php

@@ -2064,561 +2064,6 @@ function fixIds(EntityManager $em)
         error_log('fixIds');
     }
 
-    // Create temporary indexes to increase speed of the following operations
-    // Adding and removing indexes will usually take much less time than
-    // the execution without indexes of the queries in this function, particularly
-    // for large tables
-    $sql = "ALTER TABLE c_document ADD INDEX tmpidx_doc(c_id, id)";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_student_publication ADD INDEX tmpidx_stud (c_id, id)";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_quiz ADD INDEX tmpidx_quiz (c_id, id)";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_item_property ADD INDEX tmpidx_ip (to_group_id)";
-    $connection->executeQuery($sql);
-
-    $sql = "SELECT * FROM c_lp_item";
-    $result = $connection->fetchAll($sql);
-    foreach ($result as $item) {
-        $courseId = $item['c_id'];
-        $iid = isset($item['iid']) ? intval($item['iid']) : 0;
-        $ref = isset($item['ref']) ? intval($item['ref']) : 0;
-        $sql = null;
-
-        $newId = '';
-
-        switch ($item['item_type']) {
-            case TOOL_LINK:
-                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_STUDENTPUBLICATION:
-                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_QUIZ:
-                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_DOCUMENT:
-                $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_FORUM:
-                $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND forum_id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case 'thread':
-                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-        }
-
-        if (!empty($sql) && !empty($newId) && !empty($iid)) {
-            $sql = "UPDATE c_lp_item SET ref = $newId WHERE iid = $iid";
-
-            $connection->executeQuery($sql);
-        }
-    }
-
-    // Set NULL if session = 0
-    $sql = "UPDATE c_item_property SET session_id = NULL WHERE session_id = 0";
-    $connection->executeQuery($sql);
-
-    // Set NULL if group = 0
-    $sql = "UPDATE c_item_property SET to_group_id = NULL WHERE to_group_id = 0";
-    $connection->executeQuery($sql);
-
-    // Set NULL if insert_user_id = 0
-    $sql = "UPDATE c_item_property SET insert_user_id = NULL WHERE insert_user_id = 0";
-    $connection->executeQuery($sql);
-
-    // Delete session data of sessions that don't exist.
-    $sql = "DELETE FROM c_item_property
-            WHERE session_id IS NOT NULL AND session_id NOT IN (SELECT id FROM session)";
-    $connection->executeQuery($sql);
-
-    // Delete group data of groups that don't exist.
-    $sql = "DELETE FROM c_item_property
-            WHERE to_group_id IS NOT NULL AND to_group_id NOT IN (SELECT DISTINCT id FROM c_group_info)";
-    $connection->executeQuery($sql);
-
-    // This updates the group_id with c_group_info.iid instead of c_group_info.id
-
-    if ($debug) {
-        error_log('update iids');
-    }
-
-    $groupTableToFix = [
-        'c_group_rel_user',
-        'c_group_rel_tutor',
-        'c_permission_group',
-        'c_role_group',
-        'c_survey_invitation',
-        'c_attendance_calendar_rel_group'
-    ];
-
-    foreach ($groupTableToFix as $table) {
-        $sql = "SELECT * FROM $table";
-        $result = $connection->fetchAll($sql);
-        foreach ($result as $item) {
-            $iid = $item['iid'];
-            $courseId = $item['c_id'];
-            $groupId = intval($item['group_id']);
-
-            // Fix group id
-            if (!empty($groupId)) {
-                $sql = "SELECT * FROM c_group_info
-                        WHERE c_id = $courseId AND id = $groupId
-                        LIMIT 1";
-                $data = $connection->fetchAssoc($sql);
-                if (!empty($data)) {
-                    $newGroupId = $data['iid'];
-                    $sql = "UPDATE $table SET group_id = $newGroupId
-                            WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                } else {
-                    // The group does not exists clean this record
-                    $sql = "DELETE FROM $table WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-    }
-
-    // Fix c_item_property
-    if ($debug) {
-        error_log('update c_item_property');
-    }
-
-    $sql = "SELECT * FROM course";
-    $courseList = $connection->fetchAll($sql);
-    if ($debug) {
-        error_log('Getting course list');
-    }
-
-    $totalCourse = count($courseList);
-    $counter = 0;
-
-    foreach ($courseList as $courseData) {
-        $courseId = $courseData['id'];
-        if ($debug) {
-            error_log('Updating course: '.$courseData['code']);
-        }
-
-        $sql = "SELECT * FROM c_item_property WHERE c_id = $courseId";
-        $result = $connection->fetchAll($sql);
-
-        foreach ($result as $item) {
-            //$courseId = $item['c_id'];
-            $sessionId = intval($item['session_id']);
-            $groupId = intval($item['to_group_id']);
-            $iid = $item['iid'];
-            $ref = $item['ref'];
-
-            // Fix group id
-            if (!empty($groupId)) {
-                $sql = "SELECT * FROM c_group_info
-                        WHERE c_id = $courseId AND id = $groupId";
-                $data = $connection->fetchAssoc($sql);
-                if (!empty($data)) {
-                    $newGroupId = $data['iid'];
-                    $sql = "UPDATE c_item_property SET to_group_id = $newGroupId
-                            WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                } else {
-                    // The group does not exists clean this record
-                    $sql = "DELETE FROM c_item_property WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                }
-            }
-
-            $sql = '';
-            $newId = '';
-            switch ($item['tool']) {
-                case TOOL_LINK:
-                    $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
-                    break;
-                case TOOL_STUDENTPUBLICATION:
-                    $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case TOOL_QUIZ:
-                    $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case TOOL_DOCUMENT:
-                    $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case TOOL_FORUM:
-                    $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case 'thread':
-                    $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND id = $ref";
-                    break;
-            }
-
-            if (!empty($sql) && !empty($newId)) {
-                $data = $connection->fetchAssoc($sql);
-                if (isset($data['iid'])) {
-                    $newId = $data['iid'];
-                }
-                $sql = "UPDATE c_item_property SET ref = $newId WHERE iid = $iid";
-                $connection->executeQuery($sql);
-            }
-
-            if ($debug) {
-                // Print a status in the log once in a while
-                error_log("Process item #$counter/$totalCourse");
-            }
-            $counter++;
-        }
-    }
-
-    if ($debug) {
-        error_log('update gradebook_link');
-    }
-
-    // Fix gradebook_link
-    $sql = "SELECT * FROM gradebook_link";
-    $result = $connection->fetchAll($sql);
-    foreach ($result as $item) {
-        $courseCode = $item['course_code'];
-        $courseInfo = api_get_course_info($courseCode);
-
-        if (empty($courseInfo)) {
-            continue;
-        }
-        $courseId = $courseInfo['real_id'];
-        $ref = $item['ref_id'];
-        $iid = $item['id'];
-        $sql = '';
-
-        switch ($item['type']) {
-            case LINK_LEARNPATH:
-                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
-                break;
-            case LINK_STUDENTPUBLICATION:
-                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
-                break;
-            case LINK_EXERCISE:
-                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
-                break;
-            case LINK_ATTENDANCE:
-                //$sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
-                break;
-            case LINK_FORUM_THREAD:
-                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
-                break;
-        }
-
-        if (!empty($sql)) {
-            $data = $connection->fetchAssoc($sql);
-            if (isset($data) && isset($data['iid'])) {
-                $newId = $data['iid'];
-                $sql = "UPDATE gradebook_link SET ref_id = $newId
-                        WHERE id = $iid";
-                $connection->executeQuery($sql);
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('update groups');
-    }
-
-    $sql = "SELECT * FROM groups";
-    $result = $connection->executeQuery($sql);
-    $groups = $result->fetchAll();
-
-    $oldGroups = array();
-
-    if (!empty($groups)) {
-        foreach ($groups as $group) {
-            if (empty($group['name'])) {
-                continue;
-            }
-
-            /*$group['description'] = Database::escape_string($group['description']);
-            $group['name'] = Database::escape_string($group['name']);
-            $sql = "INSERT INTO usergroup (name, group_type, description, picture, url, visibility, updated_at, created_at)
-                    VALUES ('{$group['name']}', '1', '{$group['description']}', '{$group['picture_uri']}', '{$group['url']}', '{$group['visibility']}', '{$group['updated_on']}', '{$group['created_on']}')";
-            */
-            $params = [
-                'name' => $group['name'],
-                'description' => $group['description'],
-                'group_type' => 1,
-                'picture' => $group['picture_uri'],
-                'url' => $group['url'],
-                'visibility' => $group['visibility'],
-                'updated_at' => $group['updated_on'],
-                'created_at' => $group['created_on']
-            ];
-            $connection->insert('usergroup', $params);
-            //$connection->executeQuery($sql);
-            $id = $connection->lastInsertId('id');
-            $oldGroups[$group['id']] = $id;
-        }
-    }
-
-    if (!empty($oldGroups)) {
-        foreach ($oldGroups as $oldId => $newId) {
-            $path = \GroupPortalManager::get_group_picture_path_by_id(
-                $oldId,
-                'system'
-            );
-
-            if (!empty($path)) {
-                $newPath = str_replace(
-                    "groups/$oldId/",
-                    "groups/$newId/",
-                    $path['dir']
-                );
-                $command = "mv {$path['dir']} $newPath ";
-                system($command);
-            }
-        }
-
-        $sql = "SELECT * FROM group_rel_user";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']])) {
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-
-                    $userId = $data['user_id'];
-
-                    $sql = "SELECT id FROM user WHERE user_id = $userId";
-                    $userResult = $connection->executeQuery($sql);
-                    $userInfo = $userResult->fetch();
-                    if (empty($userInfo)) {
-                        continue;
-                    }
-
-                    $sql = "INSERT INTO usergroup_rel_user (usergroup_id, user_id, relation_type)
-                            VALUES ('{$data['group_id']}', '{$userId}', '{$data['relation_type']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-
-        $sql = "SELECT * FROM group_rel_group";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']]) && isset($oldGroups[$data['subgroup_id']])) {
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $data['subgroup_id'] = $oldGroups[$data['subgroup_id']];
-                    $sql = "INSERT INTO usergroup_rel_usergroup (group_id, subgroup_id, relation_type)
-                            VALUES ('{$data['group_id']}', '{$data['subgroup_id']}', '{$data['relation_type']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-
-        $sql = "SELECT * FROM announcement_rel_group";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']])) {
-                    // Deleting relation
-                    $sql = "DELETE FROM announcement_rel_group WHERE group_id = {$data['group_id']}";
-                    $connection->executeQuery($sql);
-
-                    // Add new relation
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $sql = "INSERT INTO announcement_rel_group(group_id, announcement_id)
-                            VALUES ('{$data['group_id']}', '{$data['announcement_id']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-
-        $sql = "SELECT * FROM group_rel_tag";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']])) {
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $sql = "INSERT INTO usergroup_rel_tag (tag_id, usergroup_id)
-                            VALUES ('{$data['tag_id']}', '{$data['group_id']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('update extra fields');
-    }
-
-    // Extra fields
-    $extraFieldTables = [
-        ExtraField::USER_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_USER_FIELD),
-        ExtraField::COURSE_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
-        //ExtraField::LP_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_LP_FIELD),
-        ExtraField::SESSION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
-        //ExtraField::CALENDAR_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
-        //ExtraField::QUESTION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
-        //ExtraField::USER_FIELD_TYPE => //Database::get_main_table(TABLE_MAIN_SPECIFIC_FIELD),
-    ];
-
-    foreach ($extraFieldTables as $type => $table) {
-        //continue;
-        $sql = "SELECT * FROM $table ";
-        if ($debug) {
-            error_log($sql);
-        }
-        $result = $connection->query($sql);
-        $fields = $result->fetchAll();
-
-        foreach ($fields as $field) {
-            if ($debug) {
-                error_log("Loading field: ".$field['field_variable']);
-            }
-            $originalId = $field['id'];
-            $extraField = new ExtraField();
-            $extraField
-                ->setExtraFieldType($type)
-                ->setVariable($field['field_variable'])
-                ->setFieldType($field['field_type'])
-                ->setDisplayText($field['field_display_text'])
-                ->setDefaultValue($field['field_default_value'])
-                ->setFieldOrder($field['field_order'])
-                ->setVisible($field['field_visible'])
-                ->setChangeable($field['field_changeable'])
-                ->setFilter($field['field_filter']);
-
-            $em->persist($extraField);
-            $em->flush();
-
-            $values = array();
-            $handlerId = null;
-            switch ($type) {
-                case ExtraField::USER_FIELD_TYPE:
-                    $optionTable = Database::get_main_table(
-                        TABLE_MAIN_USER_FIELD_OPTIONS
-                    );
-                    $valueTable = Database::get_main_table(
-                        TABLE_MAIN_USER_FIELD_VALUES
-                    );
-                    $handlerId = 'user_id';
-                    break;
-                case ExtraField::COURSE_FIELD_TYPE:
-                    $optionTable = Database::get_main_table(
-                        TABLE_MAIN_COURSE_FIELD_OPTIONS
-                    );
-                    $valueTable = Database::get_main_table(
-                        TABLE_MAIN_COURSE_FIELD_VALUES
-                    );
-                    $handlerId = 'c_id';
-                    break;
-                case ExtraField::SESSION_FIELD_TYPE:
-                    $optionTable = Database::get_main_table(
-                        TABLE_MAIN_SESSION_FIELD_OPTIONS
-                    );
-                    $valueTable = Database::get_main_table(
-                        TABLE_MAIN_SESSION_FIELD_VALUES
-                    );
-                    $handlerId = 'session_id';
-                    break;
-            }
-
-            if (!empty($optionTable)) {
-                $sql = "SELECT * FROM $optionTable WHERE field_id = $originalId ";
-                $result = $connection->query($sql);
-                $options = $result->fetchAll();
-
-                foreach ($options as $option) {
-                    $extraFieldOption = new ExtraFieldOptions();
-                    $extraFieldOption
-                        ->setDisplayText($option['option_display_text'])
-                        ->setField($extraField)
-                        ->setOptionOrder($option['option_order'])
-                        ->setValue($option['option_value']);
-                    $em->persist($extraFieldOption);
-                    $em->flush();
-                }
-
-                $sql = "SELECT * FROM $valueTable WHERE field_id = $originalId ";
-                $result = $connection->query($sql);
-                $values = $result->fetchAll();
-                if ($debug) {
-                    error_log("Fetch all values for field");
-                }
-            }
-
-            if (!empty($values)) {
-                if ($debug) {
-                    error_log("Saving field value in new table");
-                }
-                $k = 0;
-                foreach ($values as $value) {
-                    if (isset($value[$handlerId])) {
-                        /*
-                        $extraFieldValue = new ExtraFieldValues();
-                        $extraFieldValue
-                            ->setValue($value['field_value'])
-                            ->setField($extraField)
-                            ->setItemId($value[$handlerId]);
-                        $em->persist($extraFieldValue);
-                        $em->flush();
-                        */
-                        // Insert without the use of the entity as it reduces
-                        // speed to 2 records per second (much too slow)
-                        $params = [
-                            'field_id' => $extraField->getId(),
-                            'value' => $value['field_value'],
-                            'item_id' => $value[$handlerId]
-                        ];
-                        $connection->insert('extra_field_values', $params);
-                        if ($debug && ($k % 10000 == 0)) {
-                            error_log("Saving field $k");
-                        }
-                        $k++;
-                    }
-                }
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('Remove index');
-    }
-
-    // Drop temporary indexes added to increase speed of this function's queries
-    $sql = "ALTER TABLE c_document DROP INDEX tmpidx_doc";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_student_publication DROP INDEX tmpidx_stud";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_quiz DROP INDEX tmpidx_quiz";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_item_property DROP INDEX tmpidx_ip";
-    $connection->executeQuery($sql);
-
     if ($debug) {
         error_log('Finish fixId function');
     }

+ 5 - 5
main/social/invitations.php

@@ -23,7 +23,7 @@ if (is_array($_GET) && count($_GET) > 0) {
     foreach ($_GET as $key => $value) {
         switch ($key) {
             case 'accept':
-                $useRole = GroupPortalManager::get_user_group_role(api_get_user_id(), $value);
+                $useRole = UserGroup::get_user_group_role(api_get_user_id(), $value);
 
                 if (in_array(
                     $useRole,
@@ -32,13 +32,13 @@ if (is_array($_GET) && count($_GET) > 0) {
                         GROUP_USER_PERMISSION_PENDING_INVITATION
                     )
                 )) {
-                    GroupPortalManager::update_user_role(api_get_user_id(), $value, GROUP_USER_PERMISSION_READER);
+                    UserGroup::update_user_role(api_get_user_id(), $value, GROUP_USER_PERMISSION_READER);
 
                     Display::addFlash(
                         Display::return_message(get_lang('UserIsSubscribedToThisGroup'), 'success')
                     );
 
-                    header('Location: ' . api_get_path(WEB_CODE_PATH) . 'social/invitations.php');
+                    header('Location: '.api_get_path(WEB_CODE_PATH).'social/invitations.php');
                     exit;
                 }
 
@@ -54,7 +54,7 @@ if (is_array($_GET) && count($_GET) > 0) {
                         Display::return_message(get_lang('UserIsAlreadySubscribedToThisGroup'), 'warning')
                     );
 
-                    header('Location: ' . api_get_path(WEB_CODE_PATH) . 'social/invitations.php');
+                    header('Location: '.api_get_path(WEB_CODE_PATH).'social/invitations.php');
                     exit;
                 }
 
@@ -66,7 +66,7 @@ if (is_array($_GET) && count($_GET) > 0) {
                 exit;
                 break;
             case 'deny':
-                GroupPortalManager::delete_user_rel_group(api_get_user_id(), $value);
+                UserGroup::delete_user_rel_group(api_get_user_id(), $value);
 
                 Display::addFlash(
                     Display::return_message(get_lang('GroupInvitationWasDeny'))

+ 1 - 15
main/webservices/registration.soap.php

@@ -6461,7 +6461,6 @@ function WSCreateGroup($params)
         'name' => $params['name']
     ];
     return $userGroup->save($params);
-    //return GroupPortalManager::add($params['name'], null, null, 1);
 }
 
 /* Create group Web Service end */
@@ -6508,17 +6507,8 @@ function WSUpdateGroup($params)
     $params['allow_member_group_to_leave'] = null;
 
     $userGroup = new UserGroup();
-    return $userGroup->update($params);
 
-    /*return GroupPortalManager::update(
-        $params['id'],
-        $params['name'],
-        $params['description'],
-        $params['url'],
-        $params['visibility'],
-        $params['picture_uri'],
-        $params['allow_member_group_to_leave']
-    );*/
+    return $userGroup->update($params);
 }
 
 /* Update group Web Service end */
@@ -6559,8 +6549,6 @@ function WSDeleteGroup($params)
     $userGroup = new UserGroup();
 
     return $userGroup->delete($params['id']);
-
-    //return GroupPortalManager::delete($params['id']);
 }
 
 /* Delete group Web Service end */
@@ -6602,8 +6590,6 @@ function GroupBindToParent($params)
     $userGroup = new UserGroup();
 
     return $userGroup->set_parent_group($params['id'], $params['parent_id']);
-
-    //return GroupPortalManager::set_parent_group($params['id'], $params['parent_id']);
 }
 
 /* Bind group Web Service end */

+ 2 - 2
plugin/advanced_subscription/ajax/advanced_subscription.ajax.php

@@ -109,7 +109,7 @@ if ($verified) {
                 $studentArray['picture'] = $studentArray['avatar'];
 
                 // Get superior data if exist
-                $superiorId = UserManager::getStudentBoss($data['studentUserId']);
+                $superiorId = UserManager::getFirstStudentBoss($data['studentUserId']);
                 if (!empty($superiorId)) {
                     $superiorArray = api_get_user_info($superiorId);
                 } else {
@@ -265,7 +265,7 @@ if ($verified) {
                     $studentArray = api_get_user_info($data['studentUserId']);
                     $studentArray['picture'] = $studentArray['avatar'];
                     // Prepare superior data
-                    $superiorId = UserManager::getStudentBoss($data['studentUserId']);
+                    $superiorId = UserManager::getFirstStudentBoss($data['studentUserId']);
                     if (!empty($superiorId)) {
                         $superiorArray = api_get_user_info($superiorId);
                     } else {

+ 1 - 1
plugin/advanced_subscription/test/mails.php

@@ -67,7 +67,7 @@ $studentArray = api_get_user_info($data['studentUserId']);
 $studentArray['picture'] = $studentArray['avatar'];
 
 // Get superior data if exist
-$superiorId = UserManager::getStudentBoss($data['studentUserId']);
+$superiorId = UserManager::getFirstStudentBoss($data['studentUserId']);
 if (!empty($superiorId)) {
     $superiorArray = api_get_user_info($superiorId);
 } else {

+ 1 - 0
plugin/bbb/lib/bbb.lib.php

@@ -63,6 +63,7 @@ class bbb
                 }
             }
         }
+
         if ($bbbPlugin === 'true') {
             $userInfo = api_get_user_info();
             $this->userCompleteName = $userInfo['complete_name'];

+ 9 - 1
src/Chamilo/CoreBundle/Composer/ScriptHandler.php

@@ -28,6 +28,10 @@ class ScriptHandler
     {
         $paths = [
             __DIR__.'/../../../../archive/',
+            __DIR__.'/../../../../main/admin/add_users_to_group.php',
+            __DIR__.'/../../../../main/admin/group_add.php',
+            __DIR__.'/../../../../main/admin/group_edit.php',
+            __DIR__.'/../../../../main/admin/group_list.php',
             __DIR__.'/../../../../main/conference/',
             __DIR__.'/../../../../main/course_notice/',
             __DIR__.'/../../../../main/metadata/',
@@ -38,7 +42,7 @@ class ScriptHandler
             __DIR__.'/../../../../main/reservation/',
             __DIR__.'/../../../../main/inc/lib/symfony/',
             __DIR__.'/../../../../main/inc/entity/',
-            //__DIR__.'/../../../../main/inc/lib/phpdocx/',
+            __DIR__.'/../../../../main/inc/lib/phpdocx/',
             __DIR__.'/../../../../main/inc/lib/phpqrcode/',
             __DIR__.'/../../../../main/inc/lib/ezpdf',
             __DIR__.'/../../../../main/inc/lib/javascript/bootstrap',
@@ -57,6 +61,10 @@ class ScriptHandler
             __DIR__.'/../../../../main/inc/lib/pchart/',
             __DIR__.'/../../../../main/inc/lib/htmlpurifier',
             __DIR__.'/../../../../main/announcements/resources',
+            __DIR__.'/../../../../src/Chamilo/CoreBundle/Entity/GroupRelGroup.php',
+            __DIR__.'/../../../../src/Chamilo/CoreBundle/Entity/GroupRelTag.php',
+            __DIR__.'/../../../../src/Chamilo/CoreBundle/Entity/GroupRelUser.php',
+            __DIR__.'/../../../../src/Chamilo/CoreBundle/Entity/Groups.php'
         ];
 
         $files = [

+ 0 - 125
src/Chamilo/CoreBundle/Entity/GroupRelGroup.php

@@ -1,125 +0,0 @@
-<?php
-
-namespace Chamilo\CoreBundle\Entity;
-
-use Doctrine\ORM\Mapping as ORM;
-
-/**
- * GroupRelGroup
- *
- * @ORM\Table(name="group_rel_group", indexes={@ORM\Index(name="group_id", columns={"group_id"}), @ORM\Index(name="subgroup_id", columns={"subgroup_id"}), @ORM\Index(name="relation_type", columns={"relation_type"})})
- * @ORM\Entity
- */
-class GroupRelGroup
-{
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="group_id", type="integer", nullable=false)
-     */
-    private $groupId;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="subgroup_id", type="integer", nullable=false)
-     */
-    private $subgroupId;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="relation_type", type="integer", nullable=false)
-     */
-    private $relationType;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="id", type="integer")
-     * @ORM\Id
-     * @ORM\GeneratedValue(strategy="IDENTITY")
-     */
-    private $id;
-
-
-
-    /**
-     * Set groupId
-     *
-     * @param integer $groupId
-     * @return GroupRelGroup
-     */
-    public function setGroupId($groupId)
-    {
-        $this->groupId = $groupId;
-
-        return $this;
-    }
-
-    /**
-     * Get groupId
-     *
-     * @return integer
-     */
-    public function getGroupId()
-    {
-        return $this->groupId;
-    }
-
-    /**
-     * Set subgroupId
-     *
-     * @param integer $subgroupId
-     * @return GroupRelGroup
-     */
-    public function setSubgroupId($subgroupId)
-    {
-        $this->subgroupId = $subgroupId;
-
-        return $this;
-    }
-
-    /**
-     * Get subgroupId
-     *
-     * @return integer
-     */
-    public function getSubgroupId()
-    {
-        return $this->subgroupId;
-    }
-
-    /**
-     * Set relationType
-     *
-     * @param integer $relationType
-     * @return GroupRelGroup
-     */
-    public function setRelationType($relationType)
-    {
-        $this->relationType = $relationType;
-
-        return $this;
-    }
-
-    /**
-     * Get relationType
-     *
-     * @return integer
-     */
-    public function getRelationType()
-    {
-        return $this->relationType;
-    }
-
-    /**
-     * Get id
-     *
-     * @return integer
-     */
-    public function getId()
-    {
-        return $this->id;
-    }
-}

+ 0 - 95
src/Chamilo/CoreBundle/Entity/GroupRelTag.php

@@ -1,95 +0,0 @@
-<?php
-
-namespace Chamilo\CoreBundle\Entity;
-
-use Doctrine\ORM\Mapping as ORM;
-
-/**
- * GroupRelTag
- *
- * @ORM\Table(name="group_rel_tag", indexes={@ORM\Index(name="group_id", columns={"group_id"}), @ORM\Index(name="tag_id", columns={"tag_id"})})
- * @ORM\Entity
- */
-class GroupRelTag
-{
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="tag_id", type="integer", nullable=false)
-     */
-    private $tagId;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="group_id", type="integer", nullable=false)
-     */
-    private $groupId;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="id", type="integer")
-     * @ORM\Id
-     * @ORM\GeneratedValue(strategy="IDENTITY")
-     */
-    private $id;
-
-
-
-    /**
-     * Set tagId
-     *
-     * @param integer $tagId
-     * @return GroupRelTag
-     */
-    public function setTagId($tagId)
-    {
-        $this->tagId = $tagId;
-
-        return $this;
-    }
-
-    /**
-     * Get tagId
-     *
-     * @return integer
-     */
-    public function getTagId()
-    {
-        return $this->tagId;
-    }
-
-    /**
-     * Set groupId
-     *
-     * @param integer $groupId
-     * @return GroupRelTag
-     */
-    public function setGroupId($groupId)
-    {
-        $this->groupId = $groupId;
-
-        return $this;
-    }
-
-    /**
-     * Get groupId
-     *
-     * @return integer
-     */
-    public function getGroupId()
-    {
-        return $this->groupId;
-    }
-
-    /**
-     * Get id
-     *
-     * @return integer
-     */
-    public function getId()
-    {
-        return $this->id;
-    }
-}

+ 0 - 125
src/Chamilo/CoreBundle/Entity/GroupRelUser.php

@@ -1,125 +0,0 @@
-<?php
-
-namespace Chamilo\CoreBundle\Entity;
-
-use Doctrine\ORM\Mapping as ORM;
-
-/**
- * GroupRelUser
- *
- * @ORM\Table(name="group_rel_user", indexes={@ORM\Index(name="group_id", columns={"group_id"}), @ORM\Index(name="user_id", columns={"user_id"}), @ORM\Index(name="relation_type", columns={"relation_type"})})
- * @ORM\Entity
- */
-class GroupRelUser
-{
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="group_id", type="integer", nullable=false)
-     */
-    private $groupId;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="user_id", type="integer", nullable=false)
-     */
-    private $userId;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="relation_type", type="integer", nullable=false)
-     */
-    private $relationType;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="id", type="integer")
-     * @ORM\Id
-     * @ORM\GeneratedValue(strategy="IDENTITY")
-     */
-    private $id;
-
-
-
-    /**
-     * Set groupId
-     *
-     * @param integer $groupId
-     * @return GroupRelUser
-     */
-    public function setGroupId($groupId)
-    {
-        $this->groupId = $groupId;
-
-        return $this;
-    }
-
-    /**
-     * Get groupId
-     *
-     * @return integer
-     */
-    public function getGroupId()
-    {
-        return $this->groupId;
-    }
-
-    /**
-     * Set userId
-     *
-     * @param integer $userId
-     * @return GroupRelUser
-     */
-    public function setUserId($userId)
-    {
-        $this->userId = $userId;
-
-        return $this;
-    }
-
-    /**
-     * Get userId
-     *
-     * @return integer
-     */
-    public function getUserId()
-    {
-        return $this->userId;
-    }
-
-    /**
-     * Set relationType
-     *
-     * @param integer $relationType
-     * @return GroupRelUser
-     */
-    public function setRelationType($relationType)
-    {
-        $this->relationType = $relationType;
-
-        return $this;
-    }
-
-    /**
-     * Get relationType
-     *
-     * @return integer
-     */
-    public function getRelationType()
-    {
-        return $this->relationType;
-    }
-
-    /**
-     * Get id
-     *
-     * @return integer
-     */
-    public function getId()
-    {
-        return $this->id;
-    }
-}

+ 0 - 245
src/Chamilo/CoreBundle/Entity/Groups.php

@@ -1,245 +0,0 @@
-<?php
-
-namespace Chamilo\CoreBundle\Entity;
-
-use Doctrine\ORM\Mapping as ORM;
-
-/**
- * Groups
- *
- * @ORM\Table(name="groups")
- * @ORM\Entity
- */
-class Groups
-{
-    /**
-     * @var string
-     *
-     * @ORM\Column(name="name", type="string", length=255, nullable=false)
-     */
-    private $name;
-
-    /**
-     * @var string
-     *
-     * @ORM\Column(name="description", type="string", length=255, nullable=false)
-     */
-    private $description;
-
-    /**
-     * @var string
-     *
-     * @ORM\Column(name="picture_uri", type="string", length=255, nullable=false)
-     */
-    private $pictureUri;
-
-    /**
-     * @var string
-     *
-     * @ORM\Column(name="url", type="string", length=255, nullable=false)
-     */
-    private $url;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="visibility", type="integer", nullable=false)
-     */
-    private $visibility;
-
-    /**
-     * @var string
-     *
-     * @ORM\Column(name="updated_on", type="string", length=255, nullable=false)
-     */
-    private $updatedOn;
-
-    /**
-     * @var string
-     *
-     * @ORM\Column(name="created_on", type="string", length=255, nullable=false)
-     */
-    private $createdOn;
-
-    /**
-     * @var integer
-     *
-     * @ORM\Column(name="id", type="integer")
-     * @ORM\Id
-     * @ORM\GeneratedValue(strategy="IDENTITY")
-     */
-    private $id;
-
-
-
-    /**
-     * Set name
-     *
-     * @param string $name
-     * @return Groups
-     */
-    public function setName($name)
-    {
-        $this->name = $name;
-
-        return $this;
-    }
-
-    /**
-     * Get name
-     *
-     * @return string
-     */
-    public function getName()
-    {
-        return $this->name;
-    }
-
-    /**
-     * Set description
-     *
-     * @param string $description
-     * @return Groups
-     */
-    public function setDescription($description)
-    {
-        $this->description = $description;
-
-        return $this;
-    }
-
-    /**
-     * Get description
-     *
-     * @return string
-     */
-    public function getDescription()
-    {
-        return $this->description;
-    }
-
-    /**
-     * Set pictureUri
-     *
-     * @param string $pictureUri
-     * @return Groups
-     */
-    public function setPictureUri($pictureUri)
-    {
-        $this->pictureUri = $pictureUri;
-
-        return $this;
-    }
-
-    /**
-     * Get pictureUri
-     *
-     * @return string
-     */
-    public function getPictureUri()
-    {
-        return $this->pictureUri;
-    }
-
-    /**
-     * Set url
-     *
-     * @param string $url
-     * @return Groups
-     */
-    public function setUrl($url)
-    {
-        $this->url = $url;
-
-        return $this;
-    }
-
-    /**
-     * Get url
-     *
-     * @return string
-     */
-    public function getUrl()
-    {
-        return $this->url;
-    }
-
-    /**
-     * Set visibility
-     *
-     * @param integer $visibility
-     * @return Groups
-     */
-    public function setVisibility($visibility)
-    {
-        $this->visibility = $visibility;
-
-        return $this;
-    }
-
-    /**
-     * Get visibility
-     *
-     * @return integer
-     */
-    public function getVisibility()
-    {
-        return $this->visibility;
-    }
-
-    /**
-     * Set updatedOn
-     *
-     * @param string $updatedOn
-     * @return Groups
-     */
-    public function setUpdatedOn($updatedOn)
-    {
-        $this->updatedOn = $updatedOn;
-
-        return $this;
-    }
-
-    /**
-     * Get updatedOn
-     *
-     * @return string
-     */
-    public function getUpdatedOn()
-    {
-        return $this->updatedOn;
-    }
-
-    /**
-     * Set createdOn
-     *
-     * @param string $createdOn
-     * @return Groups
-     */
-    public function setCreatedOn($createdOn)
-    {
-        $this->createdOn = $createdOn;
-
-        return $this;
-    }
-
-    /**
-     * Get createdOn
-     *
-     * @return string
-     */
-    public function getCreatedOn()
-    {
-        return $this->createdOn;
-    }
-
-    /**
-     * Get id
-     *
-     * @return integer
-     */
-    public function getId()
-    {
-        return $this->id;
-    }
-}

+ 2 - 4
tests/scripts/userfields_to_groups.php

@@ -16,8 +16,6 @@ $tUserField = Database::get_main_table(TABLE_EXTRA_FIELD);
 $tUserFieldValue = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
 
 $tUser = Database::get_main_table(TABLE_MAIN_USER);
-$tGroup = Database::get_main_table(TABLE_MAIN_GROUP);
-$tGroupUser = Database::get_main_table(TABLE_MAIN_USER_REL_GROUP);
 
 // First get the IDs of the selected fields
 $sql = "SELECT id, field_type, variable FROM $tUserField";
@@ -57,7 +55,7 @@ foreach ($usersData as $userId => $value) {
 
 // Third, we create groups based on the combined strings by user and insert
 // users in them (as reader)
-foreach ($distinctGroups as $name => $usersList) {
+/*foreach ($distinctGroups as $name => $usersList) {
     $now = api_get_utc_datetime();
     $sql = "INSERT INTO $tGroup (name, visibility, updated_on, created_on) VALUES ('$name', 1, '$now', '$now')";
     echo $sql . PHP_EOL;
@@ -69,4 +67,4 @@ foreach ($distinctGroups as $name => $usersList) {
         echo $sql . PHP_EOL;
         $result = Database::query($sql);
     }
-}
+}*/