From 1d4eefbfb5640fca76993b2f6ed4cdd1e187ed09 Mon Sep 17 00:00:00 2001
From: patrickpollet <pp@patrickpollet.net>
Date: Wed, 29 Feb 2012 13:18:11 +0100
Subject: [PATCH] implemented patch described in MDL-22927

final cleanup before rebasing
---
 enrol/cohort/lang/en/enrol_cohort.php |   11 ++++
 enrol/cohort/locallib.php             |   87 +++++++++++++++++++++++++++++---
 enrol/cohort/settings.php             |    2 +-
 enrol/cohort/version.php              |    6 ++-
 4 files changed, 94 insertions(+), 12 deletions(-)

diff --git a/enrol/cohort/lang/en/enrol_cohort.php b/enrol/cohort/lang/en/enrol_cohort.php
index a2dcbf4..4540415 100644
--- a/enrol/cohort/lang/en/enrol_cohort.php
+++ b/enrol/cohort/lang/en/enrol_cohort.php
@@ -29,3 +29,14 @@ $string['cohortsearch'] = 'Search';
 $string['cohort:config'] = 'Configure cohort instances';
 $string['pluginname'] = 'Cohort sync';
 $string['pluginname_desc'] = 'Cohort enrolment plugin synchronises cohort members with course participants.';
+
+//PATCH PP
+$string['create_group']='Create local group';
+$string['config_create_group']='Automatically create a group with the same name/idnumber of the cohort';
+$string['create_grouping']='Create local grouping';
+$string['config_create_grouping']='Automatically create a group with the same name/idnumber of the cohort';
+$string['use_cohort_field']='Use this field for naming';
+$string['config_use_cohort_field']='Name the group/grouping as';
+$string['group_auto_cohort']='group autocreated from cohort {$a}';
+$string['grouping_auto_cohort']='grouping autocreated from cohort {$a}';
+//END PATCH PP 
diff --git a/enrol/cohort/locallib.php b/enrol/cohort/locallib.php
index 16ecdef..e533c86 100644
--- a/enrol/cohort/locallib.php
+++ b/enrol/cohort/locallib.php
@@ -53,8 +53,13 @@ class enrol_cohort_handler {
         foreach ($enrols as $enrol) {
             // no problem if already enrolled
             $plugin->enrol_user($enrol, $ca->userid, $enrol->roleid);
-        }
+            //PATCH PP  automatically add user to the group associated to the cohort (eventually created)          
+            if ($enrol->courseid) {
+                  enrol_cohort_sync_group_grouping ($enrol, $ca->userid, $ca->cohortid);
+            }      
+            //END PATCH PP
 
+        }
         return true;
     }
 
@@ -68,7 +73,7 @@ class enrol_cohort_handler {
 
         $plugin = enrol_get_plugin('cohort');
         foreach ($enrols as $enrol) {
-            // no problem if already enrolled
+            // no problem if already unenrolled
             $plugin->unenrol_user($enrol, $ca->userid);
         }
 
@@ -102,11 +107,10 @@ function enrol_cohort_sync($courseid = NULL) {
 
     // unfortunately this may take a long time
     @set_time_limit(0); //if this fails during upgrade we can continue from cron, no big deal
-
+    
     $cohort = enrol_get_plugin('cohort');
-
     $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
-
+    
     // iterate through all not enrolled yet users
     if (enrol_is_enabled('cohort')) {
         $params = array();
@@ -115,23 +119,35 @@ function enrol_cohort_sync($courseid = NULL) {
             $params['courseid'] = $courseid;
             $onecourse = "AND e.courseid = :courseid";
         }
-        $sql = "SELECT cm.userid, e.id AS enrolid
+        //PATCH PP we must retrieve also the cohortid 
+        //$sql = "SELECT cm.userid, e.id AS enrolid
+        $sql = "SELECT cm.userid, e.id AS enrolid, e.customint1 as cohortid
                   FROM {cohort_members} cm
                   JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.status = :statusenabled AND e.enrol = 'cohort' $onecourse)
              LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cm.userid)
-                 WHERE ue.id IS NULL";
+                 WHERE ue.id IS NULL";    
         $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
         $params['courseid'] = $courseid;
         $rs = $DB->get_recordset_sql($sql, $params);
         $instances = array(); //cache
+        $cohorts =array(); //cache
         foreach($rs as $ue) {
             if (!isset($instances[$ue->enrolid])) {
                 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
             }
             $cohort->enrol_user($instances[$ue->enrolid], $ue->userid);
+             //PATCH PP  automatically add user to the group associated to the cohort (eventually created)          
+            if ($courseid) {
+                 if (!isset($cohorts[$ue->cohortid])) {
+                        $cohorts[$ue->cohortid]=$DB->get_record('cohort', array('id'=>$ue->cohortid));
+                  }
+                  enrol_cohort_sync_group_grouping ($instances[$ue->enrolid], $ue->userid, $cohorts[$ue->cohortid]);
+            }      
+            //END PATCH PP
         }
         $rs->close();
         unset($instances);
+        unset($cohorts);
     }
 
     // unenrol as necessary - ignore enabled flag, we want to get rid of all
@@ -151,7 +167,7 @@ function enrol_cohort_sync($courseid = NULL) {
     }
     $rs->close();
     unset($instances);
-
+    
     // now assign all necessary roles
     if (enrol_is_enabled('cohort')) {
         $sql = "SELECT e.roleid, ue.userid, c.id AS contextid, e.id AS itemid
@@ -233,6 +249,11 @@ function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohort
     foreach ($rs as $user) {
         $count++;
         $plugin->enrol_user($instance, $user->userid, $roleid);
+        //PATCH PP
+        // we must also enforce automatic group/grouping creation here
+        enrol_cohort_sync_group_grouping ($instance, $user->userid, $cohortid);
+        //END PATCH PP
+        
     }
     $rs->close();
     return $count;
@@ -372,4 +393,52 @@ function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset
     }
     $rs->close();
     return array('more' => !(bool)$limit, 'offset' => $offset, 'cohorts' => $cohorts);
-}
\ No newline at end of file
+}
+
+/** PATCH PP
+ * If required by configuration of enrol cohort instance 
+ * add just enroled user to a group (evnetually autocreated if missing from cohoert's name)
+ * @param unknown_type $enrol
+ * @param integer $userid
+ * @param mixed $cohortorcohortid
+ */
+function enrol_cohort_sync_group_grouping ($enrol, $userid, $cohortorcohortid) {
+    global $CFG, $DB;
+    
+    if ($enrol->courseid) { //either the target course or all course during a cron synchronisation
+        if (!empty($CFG->enrolcohortsyncautocreategroup) || !empty($CFG->enrolcohortsyncautocreategrouping)) {
+            require_once ($CFG->dirroot.'/group/lib.php');
+            if (is_numeric($cohortorcohortid))
+                $cohort=$DB->get_record('cohort', array('id'=>$cohortorcohortid));
+            else 
+                $cohort=$cohortorcohortid;
+            // we must create the group evn if create_grouping is true and not create_group ...
+            $namefield=!empty($CFG->enrolcohortsyncuseidnumber)?'idnumber':'name'; // naming attribute for the associated group/grouping (name or idnumber)
+            $groupname= $cohort->$namefield;
+            if (! $groupid=groups_get_group_by_name($enrol->courseid,$groupname)) {
+                $group=new StdClass();
+                $group->name=$groupname;
+                $group->description=get_string('group_auto_cohort','enrol_cohort',$groupname);
+                $group->courseid=$enrol->courseid;
+                $groupid=groups_create_group($group);
+            }
+            if (! groups_is_member($groupid, $userid)) {
+                groups_add_member($groupid,$userid);
+            }
+            if ($CFG->enrolcohortsyncautocreategrouping) {
+                if (! $groupingid=groups_get_grouping_by_name($enrol->courseid,$groupname)) {
+                    $grouping=new StdClass();
+                    $grouping->name=$groupname;
+                    $grouping->description=get_string('grouping_auto_cohort','enrol_cohort',$groupname);
+                    $grouping->courseid=$enrol->courseid;
+                    $groupingid=groups_create_grouping($grouping);
+                    groups_assign_grouping($groupingid, $groupid);
+                }
+            }
+        }
+    }
+
+
+}
+//END PATCH 
+
diff --git a/enrol/cohort/settings.php b/enrol/cohort/settings.php
index 6856d08..0c21427 100644
--- a/enrol/cohort/settings.php
+++ b/enrol/cohort/settings.php
@@ -38,7 +38,7 @@ if ($ADMIN->fulltree) {
         $student = get_archetype_roles('student');
         $student = reset($student);
         $settings->add(new admin_setting_configselect('enrol_cohort/roleid',
-            get_string('defaultrole', 'role'), '', $student->id, $options));
+            get_string('defaultrole', 'role'), '', $student->id, $options));        
     }
 }
 
diff --git a/enrol/cohort/version.php b/enrol/cohort/version.php
index 34200b6..f281966 100644
--- a/enrol/cohort/version.php
+++ b/enrol/cohort/version.php
@@ -24,8 +24,10 @@
  */
 
 defined('MOODLE_INTERNAL') || die();
-
-$plugin->version   = 2011112900;        // The current plugin version (Date: YYYYMMDDXX)
+//PATCH PP
+//$plugin->version   = 2011112900;        // The current plugin version (Date: YYYYMMDDXX)
+$plugin->version   = 2011112901;        // The current plugin version (Date: YYYYMMDDXX)
+//END PATCH PP
 $plugin->requires  = 2011112900;        // Requires this Moodle version
 $plugin->component = 'enrol_cohort';    // Full name of the plugin (used for diagnostics)
 $plugin->cron      = 60;
\ No newline at end of file
-- 
1.7.1

