function referentiel_get_repartition_notification($instanceid, $courseid, $t_codes_competence, $t_teacherids_accompagnement, $t_teacherids)
{
    // affiche une liste de cases cochées
    //
    global $CFG;
    // DEBUG
    /*
    echo("print_lib_repartition.php :: 34 ::<br />TEACHERS ACCOMPAGNANTS<br />\n");
    print_object($t_teacherids_accompagnement);
    echo("<br /><br />TEACHERS du COURS : TEACHERIDS <br />\n");
    print_object($t_teacherids);
    echo("<br />\n");
    */
    $nb_teachers = 0;
    $t_repartition_teachers = array(array());
    foreach ($t_codes_competence as $code_item) {
        if (!empty($instanceid) && !empty($courseid) && !empty($code_item)) {
            $teachers_repartition = referentiel_get_repartitions_teacher_by_competence($instanceid, $courseid, $code_item);
            // DEBUG
            /*
            echo("print_lib_repartition.php :: 49 ::<br />TEACHERS REPARTITION pour la COMPETENCE $code_item<br />\n");
            print_object($teachers_repartition);
            echo("<br />\n");
            */
            // verifier si intersection au sens large
            // a savoir si l'un des deux est vide l'autre est retourne
            $t_teacherids_intersect = referentiel_intersection_teachers($teachers_repartition, $t_teacherids_accompagnement);
            // DEBUG
            /*
            echo("print_lib_repartition.php :: 57 ::<br />INTERSECTION<br />\n");
            print_object($t_teacherids_intersect);
            echo("<br />\n");
            */
            foreach ($t_teacherids as $a_teacher) {
                if (!empty($t_teacherids_intersect)) {
                    // COLLECTER
                    if (array_key_exists($a_teacher->userid, $t_teacherids_intersect) == true) {
                        $t_repartition_teachers[$code_item][] = 'X';
                    } else {
                        $t_repartition_teachers[$code_item][] = '&nbsp;';
                    }
                } else {
                    $t_repartition_teachers[$code_item][] = '+';
                }
            }
        }
    }
    /*
    echo("<br />\n");
    print_object($t_repartition_teachers);
    echo("<br />EXIT\n");
    exit;
    */
    return $t_repartition_teachers;
}
/**
 * Given an activite record this function returns a list of teachers
 * that may be sent a notification.
 *
 * @param activite object
 * @return string
 * @todo Finish documenting this function
 **/
function referentiel_get_referents_notification($activite)
{
    // retourne la liste des enseignants et tuteurs qui seront notifies
    // Créé par JF pour la Version 6.xx
    // Decalque du traitement des referents destinataire dans referentiel_cron_activite()
    $destinataires = new stdClass();
    $destinataires->liste_destinataires = '';
    $destinataires->nbdestinataires = 0;
    $teachers = array();
    // liste des enseignants associes à cette activite
    if (!empty($activite->ref_instance) && !empty($activite->ref_course)) {
        if (!empty($activite->teacherid)) {
            // referent de l'activite
            $teachers[] = referentiel_get_user($activite->teacherid);
        } else {
            // on recherche les accompagnateurs
            $teachers_repartition = array();
            $teachers_repartition = referentiel_get_repartition_competences($activite->ref_instance, $activite->ref_course, $activite->competences_activite, $teachers_repartition);
            $teachers = referentiel_get_accompagnements_user($activite->ref_instance, $activite->ref_course, $activite->userid);
            // verifier si intersection
            $teachers = referentiel_intersection_teachers($teachers_repartition, $teachers);
        }
        if (empty($teachers)) {
            // notifier tous les enseignants sauf les administrateurs et createurs de cours
            $teachers = referentiel_get_teachers_course($activite->ref_course);
        }
        if ($teachers) {
            // DEBUG
            //mtrace("\nlib.php :: referentiel_get_destinataires_notification :: 147 :: TEACHERS\n");
            //print_r($teachers);
            //mtrace("\n");
            foreach ($teachers as $teacher) {
                // DEBUG
                //mtrace("\nlib.php :: 154 :: TEACHER\n");
                //print_object($teacher);
                //mtrace("\n");
                if (!empty($teacher->userid)) {
                    if ($user = referentiel_get_user($teacher->userid)) {
                        /*
                        u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest, u.emailstop, u.imagealt,
                        u.email, u.city, u.country, u.lastaccess, u.lastlogin, u.picture, u.timezone, u.theme, u.lang, u.trackforums, u.mnethostid
                        */
                        if (!$user->emailstop) {
                            $email = '';
                            if ($user->maildisplay) {
                                $email = ' ' . $user->email;
                            }
                            $destinataires->nbdestinataires++;
                            $destinataires->liste_destinataires .= ' ' . mb_strtoupper($user->lastname, 'UTF-8') . ' ' . mb_convert_case($user->firstname, MB_CASE_TITLE, 'UTF-8') . $email . ' ::';
                        }
                    }
                }
            }
        }
    }
    if ($destinataires->nbdestinataires) {
        $destinataires->liste_destinataires = '<b>' . $activite->type_activite . '</b><br /> ' . $destinataires->liste_destinataires;
    }
    return $destinataires;
}
Exemplo n.º 3
0
function referentiel_cron_activites()
{
    // traite les declarations d'activite
    global $CFG, $USER;
    global $DB;
    $cronuser = clone $USER;
    $site = get_site();
    // all users that are subscribed to any post that needs sending
    $users = array();
    // status arrays
    $mailcount = array();
    $errorcount = array();
    // caches
    $activites = array();
    // un tableau des activités à envoyer
    $courses = array();
    $coursemodules = array();
    $subscribedusers = array();
    // Posts older than 2 days will not be mailed.  This is to avoid the problem where
    // cron has not been running for a long time, and then suddenly people are flooded
    // with mail from the past few weeks or months
    $timenow = time();
    if (NOTIFICATION_DELAI) {
        $endtime = $timenow - $CFG->maxeditingtime;
    } else {
        $endtime = $timenow;
    }
    $starttime = $endtime - NOTIFICATION_INTERVALLE_JOUR * 24 * 3600;
    // Two days earlier
    // JF
    // DEBUG : cron_lib.php :
    mtrace("\nDEBUT CRON REFERENTIEL ACTIVITES");
    $activities = referentiel_get_unmailed_activities($starttime, $endtime);
    if ($activities) {
        // DEBUG : cron_lib.php :
        // mtrace('ACTIVITES...');
        // Mark them all now as being mailed.  It's unlikely but possible there
        // might be an error later so that a post is NOT actually mailed out,
        // but since mail isn't crucial, we can accept this risk.  Doing it now
        // prevents the risk of duplicated mails, which is a worse problem.
        if (!referentiel_mark_old_activities_as_mailed($endtime)) {
            mtrace('Errors occurred while trying to mark some referentiel activities as being mailed.');
            return false;
            // Don't continue trying to mail them, in case we are in a cron loop
        }
        // checking activity validity, and adding users to loop through later
        foreach ($activities as $aid => $activite) {
            if (REFERENTIEL_DEBUG) {
                // DEBUG : cron_lib.php :
                mtrace("lib_cron.php :: 821 :: ACTIVITE: AID\n");
                print_r($aid);
                mtrace("\n");
                mtrace("ACTIVITE: ACTIVITE\n");
                print_r($activite);
                mtrace("\n");
            }
            $activiteid = $activite->id;
            // DEBUG : cron_lib.php :
            // mtrace("ACTIVITE ID: $activite->id\n");
            if (!isset($activites[$activiteid])) {
                $activites[$activiteid] = $activite;
            }
            // cours
            $courseid = $activites[$activiteid]->ref_course;
            if (!isset($courses[$courseid])) {
                if ($course = $DB->get_record("course", array("id" => "{$courseid}"))) {
                    $courses[$courseid] = $course;
                } else {
                    mtrace('Could not find course ' . $courseid);
                    unset($activities[$aid]);
                    continue;
                }
            }
            // modules
            $instanceid = $activite->ref_instance;
            if (!isset($coursemodules[$instanceid])) {
                if ($cm = get_coursemodule_from_instance('referentiel', $instanceid, $courseid)) {
                    $coursemodules[$instanceid] = $cm;
                } else {
                    mtrace('Could not get course module for referentiel instance ' . $instanceid);
                    unset($activities[$aid]);
                    continue;
                }
            }
            // DEBUG : cron_lib.php :
            // mtrace("DESTINATAIRES...\n");
            if (!isset($subscribedusers[$activiteid])) {
                // MODIF JF 12/12/2010
                // Commencer par déterminer qui a fait quoi
                // Est-ce un etudiant qui a modifié la fiche ou un référent ?
                //
                // Déterminer qui est l'emetteur du message en comparant les dates
                $emetteur = 0;
                // c'est l'etudiant l'emetteur par defaut
                if (!empty($activites[$activiteid]->date_creation) && (empty($activites[$activiteid]->date_modif) || !empty($activites[$activiteid]->date_modif) && !empty($activites[$activiteid]->date_modif_student) && $activites[$activiteid]->date_modif > $activites[$activiteid]->date_modif_student)) {
                    $emetteur = 1;
                    // enseignant est l'emetteur du message
                    // mtrace("\nlib_cron.php :: 697 :: emetteur... TEACHER\n");
                }
                // ENSEIGANTS ASSOCIES A LA DECLARATION
                $teachers = array();
                // liste des enseignants associes à cette activite
                if (!empty($activites[$activiteid]->teacherid)) {
                    // referent de l'activite
                    $teachers[] = referentiel_get_user($activites[$activiteid]->teacherid);
                } else {
                    // on recherche les accompagnateurs
                    $teachers_repartition = array();
                    $teachers_repartition = referentiel_get_repartition_competences($instanceid, $courseid, $activite->competences_activite, $teachers_repartition);
                    $teachers = referentiel_get_accompagnements_user($instanceid, $courseid, $activite->userid);
                    // verifier si intersection
                    $teachers = referentiel_intersection_teachers($teachers_repartition, $teachers);
                }
                if (empty($teachers)) {
                    // on recherche parmi les enseignants du cours
                    // notifier tous les enseignants sauf les administrateurs et createurs de cours
                    $teachers = referentiel_get_teachers_course($courseid);
                }
                if (REFERENTIEL_DEBUG) {
                    if (!empty($teachers)) {
                        // DEBUG : cron_lib.php :
                        mtrace("\nlib_cron.php :: 913 :: TEACHERS\n");
                        print_r($teachers);
                        mtrace("\n");
                    }
                }
                // Liste des destinataires
                // s'il y a un référent et qu'il n'est pas l'emetteur du message
                if ($emetteur == 0) {
                    // etudiant
                    if ($teachers) {
                        foreach ($teachers as $teacher) {
                            // DEBUG
                            if (REFERENTIEL_DEBUG) {
                                if (!empty($teacher)) {
                                    mtrace("\nlib.php :: 867 :: TEACHER\n");
                                    print_r($teacher);
                                    mtrace("\n");
                                }
                            }
                            if (!empty($teacher->id)) {
                                $user = referentiel_get_user($teacher->id);
                            } else {
                                if (!empty($teacher->userid)) {
                                    // car certaines fonctions renvoient userid
                                    $user = referentiel_get_user($teacher->userid);
                                }
                            }
                            if (!empty($user)) {
                                if ($user->emailstop) {
                                    if (!empty($CFG->forum_logblocked)) {
                                        //add_to_log(SITEID, 'referentiel', 'mail blocked', '', '', 0, $user->id);
                                    }
                                } else {
                                    // this user is subscribed to this notification
                                    $subscribedusers[$activiteid][$user->id] = $user->id;
                                    // this user is a user we have to process later
                                    $users[$user->id] = $user;
                                    // DEBUG
                                    if (REFERENTIEL_DEBUG) {
                                        mtrace('DESTINATAIRE ENSEIGNANT ' . $user->id);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // emetteur enseignant
                    // le destinataire est l'étudiant
                    if (!empty($activites[$activiteid]->userid)) {
                        // notifier l'etudiant
                        $userid = $activites[$activiteid]->userid;
                        $user = referentiel_get_user($userid);
                        if ($user) {
                            if ($user->emailstop) {
                                if (!empty($CFG->forum_logblocked)) {
                                    //add_to_log(SITEID, 'referentiel', 'mail blocked', '', '', 0, $user->id);
                                }
                                mtrace("\nMAIL DESTINATAIRE BLOQUE: {$user->id}\n");
                            } else {
                                // this user is subscribed to this notification
                                $subscribedusers[$activiteid][$user->id] = $user->id;
                                // this user is a user we have to process later
                                $users[$user->id] = $user;
                                // DEBUG : cron_lib.php :
                                // mtrace('DESTINATAIRE AUTEUR ACTIVITE '.$userid);
                            }
                        }
                    }
                }
                // Faut-il ajouter l'auteur de l'activité à la liste des destinataires ?
                if (NOTIFICATION_AUTEUR_ACTIVITE) {
                    if ($emetteur == 0) {
                        if ($activites[$activiteid]->userid) {
                            // notifier l'etudiant
                            $userid = $activites[$activiteid]->userid;
                            $user = referentiel_get_user($userid);
                            if ($user) {
                                if ($user->emailstop) {
                                    if (!empty($CFG->forum_logblocked)) {
                                        //add_to_log(SITEID, 'referentiel', 'mail blocked', '', '', 0, $user->id);
                                    }
                                } else {
                                    // this user is subscribed to this notification
                                    $subscribedusers[$activiteid][$user->id] = $user->id;
                                    // this user is a user we have to process later
                                    $users[$user->id] = $user;
                                    // DEBUG : cron_lib.php :
                                    // mtrace('DESTINATAIRE AUTEUR '.$userid);
                                }
                            }
                        }
                    } else {
                        // le referent est l'emetteur
                        if ($activites[$activiteid]->teacherid) {
                            // notifier le referent
                            $teacherid = $activites[$activiteid]->teacherid;
                            $user = referentiel_get_user($teacherid);
                            if ($user) {
                                if ($user->emailstop) {
                                    if (!empty($CFG->forum_logblocked)) {
                                        //add_to_log(SITEID, 'referentiel', 'mail blocked', '', '', 0, $user->id);
                                    }
                                } else {
                                    // this user is subscribed to this notification
                                    $subscribedusers[$activiteid][$user->id] = $user->id;
                                    // this user is a user we have to process later
                                    $users[$user->id] = $user;
                                    // DEBUG : cron_lib.php :
                                    // mtrace('DESTINATAIRE AUTEUR '.$userid);
                                }
                            }
                        }
                    }
                }
                unset($teachers);
                // release memory
            }
            $mailcount[$aid] = 0;
            $errorcount[$aid] = 0;
        }
    }
    // PREPARATION DES MESSAGES
    // La collection des destinataires est maintenant disponible
    // Preparer les messages
    if ($users && $activites) {
        if (REFERENTIEL_DEBUG) {
            if (!empty($users)) {
                // DEBUG : cron_lib.php :
                mtrace("\nlib_cron.php :: 1058 :: USERS DESTINATAIRES\n");
                print_r($users);
                mtrace("\n");
            }
            if (!empty($activites)) {
                mtrace("\nlib_cron.php :: 1063 :: ACTIVITES A POSTER\n");
                print_r($activites);
                mtrace("\n");
            }
            if (!empty($subscribedusers)) {
                mtrace("\nlib_cron.php :: 1068 :: SUBSCRIBED USERS\n");
                print_r($subscribedusers);
                mtrace("\n");
            }
            // mtrace("\nEXIT : lib_cron.php :: 1072 \n");
            // exit;
        }
        $urlinfo = parse_url($CFG->wwwroot);
        $hostname = $urlinfo['host'];
        foreach ($users as $userto) {
            if (REFERENTIEL_DEBUG) {
                mtrace("\nlib_cron.php :: 1056 :: USER DESTINATAIRE (userto)\n");
                print_r($userto);
                mtrace("\n");
                //mtrace("\nEXIT : lib_cron.php :: 1059 \n");
                //exit;
            }
            @set_time_limit(TIME_LIMIT);
            // terminate if processing of any account takes longer than 3 minutes if PHP not in safe_mode
            // set this so that the capabilities are cached, and environment matches receiving user
            $USER = $userto;
            // mtrace('./mod/referentiel/lib.php :: Line 767 : Processing user '.$userto->id);
            // init caches
            $userto->viewfullnames = array();
            $userto->enrolledin = array();
            // reset the caches
            foreach ($coursemodules as $coursemoduleid => $unused) {
                $coursemodules[$coursemoduleid]->cache = new object();
                $coursemodules[$coursemoduleid]->cache->caps = array();
                unset($coursemodules[$coursemoduleid]->uservisible);
            }
            foreach ($activites as $aid => $activite) {
                if (REFERENTIEL_DEBUG) {
                    if (!empty($activite)) {
                        // DEBUG : cron_lib.php :
                        mtrace("\nlib_cron.php :: 1101 :: ACTIVITE POSTEE ({$aid})\n");
                        print_r($activite);
                        mtrace("\n");
                    }
                    if (!empty($courses)) {
                        // DEBUG : cron_lib.php :
                        mtrace("\nlib_cron.php :: 1106 :: COURS IMPLIQUES \n");
                        print_r($courses);
                        mtrace("\n");
                    }
                }
                // Set up the environment for activity, course
                $course = $courses[$activite->ref_course];
                $cm =& $coursemodules[$activite->ref_instance];
                // Do some checks  to see if we can mail out now
                if (!isset($subscribedusers[$activite->id][$userto->id])) {
                    continue;
                    // user does not subscribe to this activity
                }
                /*
                
                // BIG PROBLEM
                                // Verify user is enrolled in course - if not do not send any email
                                if (!isset($userto->enrolledin[$course->id])) {
                                    // Valable pour Moodle 2.1 et Moodle 2.2
                                    //if ($CFG->version < 2011120100) {
                                        $context = context_module::instance($cm->id);
                                    //} else {
                                        // $context = context_module::instance($cm);
                                    //}
                
                                    $userto->enrolledin[$course->id] = has_capability('moodle/course:view', $context);
                                }
                                if (!$userto->enrolledin[$course->id]) {
                                    // oops - this user should not receive anything from this course
                        mtrace("\nDEBUG : cron_lib.php : : lib_cron.php :: 918\n this user should not receive anything from this course");
                        mtrace("\nEXIT : lib_cron.php :: 019 \n");
                        exit;
                
                                    continue;
                                }
                */
                // Get info about the emettor
                if (!empty($activite->teacherid) && !empty($activite->date_modif) && $activite->date_modif > $activite->date_modif_student) {
                    $userfrom = $DB->get_record("user", array("id" => "{$activite->teacherid}"));
                    if (empty($users[$activite->teacherid])) {
                        $users[$activite->teacherid] = $userfrom;
                    }
                    if (REFERENTIEL_DEBUG) {
                        mtrace(" lib.php :: 1167 :: ACTIVITE ENVOYEE PAR TEACHER:\n");
                    }
                } else {
                    if (array_key_exists($activite->userid, $users) && !empty($users[$activite->userid])) {
                        // we might know him/her already
                        if (REFERENTIEL_DEBUG) {
                            mtrace(" lib.php :: 1174 :: ACTIVITE ENVOYEE PAR ETUDIANT : \n ");
                        }
                        $userfrom = $DB->get_record("user", array("id" => "{$activite->userid}"));
                        $users[$activite->userid] = $userfrom;
                    } else {
                        if ($userfrom = $DB->get_record("user", array("id" => "{$activite->userid}"))) {
                            //mtrace(" lib.php :: 945 :: ACTIVITE ENVOYEE PAR ETUDIANT\n");
                            $users[$userfrom->id] = $userfrom;
                            // fetch only once, we can add it to user list, it will be skipped anyway
                            if (REFERENTIEL_DEBUG) {
                                mtrace(" lib.php :: 1182 :: ACTIVITE ENVOYEE PAR ETUDIANT : \n");
                            }
                        } else {
                            mtrace('Could not find user ' . $activite->userid);
                            continue;
                        }
                    }
                }
                // setup global $COURSE properly - needed for roles and languages
                cron_setup_user($userto, $course);
                // Fill caches
                if (!isset($userto->viewfullnames[$activite->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->viewfullnames[$activite->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                // Ajout JF  2011/10/25
                $userfrom->viewfullnames = array();
                // Fill caches
                if (!isset($userfrom->viewfullnames[$activite->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userfrom->viewfullnames[$activite->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                if (!isset($userfrom->groups[$activite->id])) {
                    if (!isset($userfrom->groups)) {
                        $userfrom->groups = array();
                        $users[$userfrom->id]->groups = array();
                    }
                    $userfrom->groups[$activite->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                    $users[$userfrom->id]->groups[$activite->id] = $userfrom->groups[$activite->id];
                }
                $groupname = '';
                if (!empty($userfrom->groups)) {
                    // mtrace("\nDEBUG : lib.php :: 1014 :: \n");
                    // print_r($userfrom->groups);
                    foreach ($userfrom->groups as $un_groupe) {
                        if (!empty($un_groupe)) {
                            // mtrace("\nDEBUG : lib_cron.php :: 288 \n");
                            // print_r($un_groupe);
                            if (!empty($un_groupe)) {
                                foreach ($un_groupe as $groupe) {
                                    //mtrace("\nDEBUG : lib.php :: 1015 \n");
                                    //print_r($groupe);
                                    if (!empty($groupe->name)) {
                                        $groupname .= $groupe->name . ' ';
                                    }
                                }
                            }
                        }
                    }
                    // mtrace("\nDEBUG : lib_cron.php :: 1028 :: $groupname \n");
                }
                // OK so we need to send the email.
                if (REFERENTIEL_DEBUG) {
                    mtrace("\nlib_cron.php :: 1216:: EXPEDITEUR : USERFROM ");
                    print_r($userfrom);
                }
                if (REFERENTIEL_DEBUG) {
                    mtrace(" lib.php :: 1222 :: DESTINATAIRE : USERTO\n");
                    print_r($userto);
                    mtrace("\n");
                }
                // Does the user want this post in a digest?  If so postpone it for now.
                if ($userto->maildigest > 0) {
                    $queue = new object();
                    $queue->userid = $userto->id;
                    $queue->activiteid = $activite->id;
                    // A MODIFIER   pour tenir compte de toutes les combinaisons de dates possibles
                    if ($activite->date_modif && $activite->date_modif_student && $activite->date_modif < $activite->date_modif_student) {
                        $queue->timemodified = $activite->date_modif_student;
                    } else {
                        if ($activite->date_modif && $activite->date_creation && $activite->date_modif > $activite->date_creation) {
                            $queue->timemodified = $activite->date_modif;
                        } else {
                            $queue->timemodified = $activite->date_creation;
                        }
                    }
                    $queue->type = TYPE_ACTIVITE;
                    if (!$DB->insert_record('referentiel_notification', $queue)) {
                        mtrace("Error: mod/referentiel/lib.php : Line 1271 : Could not queue for digest mail for id {$activite->id} to user {$userto->id} ({$userto->email}) .. not trying again.");
                    }
                    continue;
                }
                // Prepare to actually send the post now, and build up the content
                $strreferentielname = get_string('referentiel', 'referentiel') . ': ' . referentiel_get_instance_name($activite->ref_instance);
                $cleanactivityname = str_replace('"', "'", strip_tags(format_string($strreferentielname . ' -> ' . $activite->type_activite)));
                $userfrom->customheaders = array('Precedence: Bulk', 'List-Id: "' . $cleanactivityname . '" <moodle_referentiel_activity_' . $activite->id . '@' . $hostname . '>', 'List-Help: ' . $CFG->wwwroot . '/mod/referentiel/activite.php?d=' . $activite->ref_instance . '&activite_id=' . $activite->id . '&amp;mode=listactivityall', 'Message-ID: <moodle_referentiel_activity_' . $activite->id . '@' . $hostname . '>', 'X-Course-Id: ' . $course->id, 'X-Course-Name: ' . format_string($course->fullname, true), 'X-Group-Name: ' . $groupname);
                if (!empty($groupname)) {
                    $postsubject = "{$course->shortname}: " . format_string($strreferentielname . ' - ' . get_string('groupe', 'referentiel', $groupname) . ' - ' . $activite->type_activite, true);
                } else {
                    $postsubject = "{$course->shortname}: " . format_string($strreferentielname . ' ' . $activite->type_activite, true);
                }
                if (REFERENTIEL_DEBUG) {
                    mtrace(" lib.php :: 1275 :: ACTIVITE ENVOYEE PAR ETUDIANT : USERFROM\n");
                    print_r($userfrom);
                    mtrace("\n");
                }
                $context = context_module::instance($cm->id);
                $posttext = referentiel_make_mail_text(TYPE_ACTIVITE, $context, $course, $activite, $userfrom, $userto);
                $posthtml = referentiel_make_mail_html(TYPE_ACTIVITE, $context, $course, $activite, $userfrom, $userto);
                if (REFERENTIEL_DEBUG) {
                    mtrace(" lib.php :: 1285 :: CONTENU  DU MESSAGE a l'UTILISATEUR :\n");
                    mtrace("TEXT\n" . $posttext);
                    mtrace("\n");
                    mtrace("HTML\n" . $posthtml);
                    mtrace("\n");
                }
                // Send the post now!
                // mtrace('Sending ', '');
                if (!($mailresult = email_to_user($userto, $userfrom, $postsubject, $posttext, $posthtml, '', '', $CFG->forum_replytouser))) {
                    mtrace("\nError: mod/referentiel/lib.php:  Could not send out mail for id {$activite->id} to user {$userto->id}" . " ({$userto->email}) .. not trying again.");
                    //add_to_log($course->id, 'referentiel', 'mail error', "activite $activite->id to user $userto->id ($userto->email)","", $cm->id, $userto->id);
                    $errorcount[$aid]++;
                } else {
                    if ($mailresult === 'emailstop') {
                        // should not be reached anymore - see check above
                    } else {
                        $mailcount[$aid]++;
                    }
                }
            }
            // mtrace('./mod/referentiel/lib.php :: Line 371 : post '.$activite->id. ': '.$activite->type_activite);
        }
    }
    if (REFERENTIEL_DEBUG) {
        if (!empty($mailcount)) {
            mtrace("\nlib_cron.php :: 1314 :: SENT MESSAGES :: MAILCOUNT\n");
            print_r($mailcount);
            mtrace("\n");
        }
        if (!empty($errorcount)) {
            mtrace("\nlib_cron.php :: 1319 :: NOT SENT MESSAGES :: ERRORCOUNT\n");
            print_r($errorcount);
            mtrace("\n");
        }
    }
    if ($activites) {
        foreach ($activites as $activite) {
            mtrace($mailcount[$activite->id] . " users were sent activity {$activite->id}, {$activite->type_activite}");
            if ($errorcount[$activite->id]) {
                $DB->set_field("referentiel_activite", "mailed", "2", array("id" => "{$activite->id}"));
            }
        }
    }
    // release some memory
    unset($subscribedusers);
    unset($mailcount);
    unset($errorcount);
    $USER = clone $cronuser;
    // course_setup(SITEID);
    cron_setup_user();
    $sitetimezone = $CFG->timezone;
    // Now see if there are any digest mails waiting to be sent, and if we should send them
    mtrace("Starting digest processing...\n");
    @set_time_limit(TIME_LIMIT * 2);
    // terminate if not able to fetch all digests in 5 minutes
    if (!isset($CFG->digestactivitytimelast)) {
        // To catch the first time
        set_config('digestactivitytimelast', 0);
    }
    $timenow = time();
    $digesttime = usergetmidnight($timenow, $sitetimezone) + $CFG->digestmailtime * 3600;
    // Delete any really old ones (normally there shouldn't be any)
    $weekago = $timenow - 7 * 24 * 3600;
    $DB->delete_records_select('referentiel_notification', "timemodified < {$weekago} AND type='" . TYPE_ACTIVITE . "'", NULL);
    if ($CFG->digestactivitytimelast < $digesttime and $timenow > $digesttime) {
        mtrace("Sending activity digests: " . userdate($timenow, '', $sitetimezone));
        $params = array("digesttime" => "{$digesttime}", "type" => TYPE_ACTIVITE);
        $sql = " (timemodified < :digesttime) AND (type=:type) ";
        $digestposts_rs = $DB->get_recordset_select('referentiel_notification', $sql, $params);
        // if (!rs_EOF($digestposts_rs)) { // deprecated
        if ($digestposts_rs->valid()) {
            // We have work to do
            $usermailcount = 0;
            $userposts = array();
            foreach ($digestposts_rs as $digestpost) {
                if (!isset($users[$digestpost->userid])) {
                    if ($user = $DB->get_record("user", array("id" => "{$digestpost->userid}"))) {
                        $users[$digestpost->userid] = $user;
                    } else {
                        continue;
                    }
                }
                $postuser = $users[$digestpost->userid];
                if ($postuser->emailstop) {
                    if (!empty($CFG->forum_logblocked)) {
                        //add_to_log(SITEID, 'referentiel', 'mail blocked', '', '', 0, $postuser->id);
                    }
                    continue;
                }
                // contenu activite
                // 0 : ACTIVITE
                if (!isset($activites[$digestpost->activiteid])) {
                    if ($activite = $DB->get_record("referentiel_activite", array("id" => "{$digestpost->activiteid}"))) {
                        $activites[$digestpost->activiteid] = $activite;
                    } else {
                        continue;
                    }
                }
                $courseid = $activites[$digestpost->activiteid]->ref_course;
                if (!isset($courses[$courseid])) {
                    if ($course = $DB->get_record("course", array("id" => "{$courseid}"))) {
                        $courses[$courseid] = $course;
                    } else {
                        continue;
                    }
                }
                if (!isset($coursemodules[$activites[$digestpost->activiteid]->ref_instance]) && $activites[$digestpost->activiteid]) {
                    if ($cm = get_coursemodule_from_instance('referentiel', $activites[$digestpost->activiteid]->ref_instance, $courseid)) {
                        $coursemodules[$activites[$digestpost->activiteid]->ref_instance] = $cm;
                    } else {
                        continue;
                    }
                }
                $userposts[$digestpost->userid][$digestpost->activiteid] = $digestpost->activiteid;
            }
            $digestposts_rs->close();
            /// Finished iteration, let's close the resultset
            // Data collected, start sending out emails to each user
            foreach ($userposts as $userid => $theseactivities) {
                @set_time_limit(TIME_LIMIT);
                // terminate if processing of any account takes longer than 2 minutes
                $USER = $cronuser;
                // course_setup(SITEID); // reset cron user language, theme and timezone settings
                cron_setup_user();
                mtrace(get_string('processingdigest', 'referentiel', $userid), '... ');
                // First of all delete all the queue entries for this user
                $DB->delete_records_select('referentiel_notification', "userid = {$userid} AND (timemodified < {$digesttime}) AND type='" . TYPE_ACTIVITE . "'", NULL);
                $userto = $users[$userid];
                // Override the language and timezone of the "current" user, so that
                // mail is customised for the receiver.
                $USER = $userto;
                // course_setup(SITEID);
                cron_setup_user();
                // init caches
                $userto->viewfullnames = array();
                $postsubject = get_string('digestmailsubject', 'referentiel', format_string($site->shortname, true));
                $headerdata = new object();
                $headerdata->sitename = format_string($site->fullname, true);
                $headerdata->userprefs = $CFG->wwwroot . '/user/edit.php?id=' . $userid . '&amp;course=' . $site->id;
                $posttext = get_string('digestmailheader', 'referentiel', $headerdata) . "\n\n";
                $headerdata->userprefs = '<a target="_blank" href="' . $headerdata->userprefs . '">' . get_string('digestmailprefs', 'referentiel') . '</a>';
                $posthtml = "<head>";
                /*
                                foreach ($CFG->stylesheets as $stylesheet) {
                                    $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
                                }
                */
                $posthtml .= "</head>\n<body id=\"email\">\n";
                $posthtml .= '<p>' . get_string('digestmailheader', 'referentiel', $headerdata) . '</p><br /><hr size="1" noshade="noshade" />';
                foreach ($theseactivities as $tid) {
                    // DEBUG : cron_lib.php :
                    // mtrace("DEBUG : cron_lib.php : :: lib.php 1031 :: TID : $tid");
                    // print_r($theseactivities);
                    @set_time_limit(TIME_LIMIT);
                    // to be reset for each post
                    $type_notification = TYPE_ACTIVITE;
                    $activite = $activites[$tid];
                    $course = $courses[$activites[$tid]->ref_course];
                    $cm = $coursemodules[$activites[$tid]->ref_instance];
                    //override language
                    // course_setup($course);
                    // setup global $COURSE properly - needed for roles and languages
                    cron_setup_user($userto, $course);
                    // Fill caches
                    if (!isset($userto->viewfullnames[$activite->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->viewfullnames[$activite->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                    }
                    $strreferentiels = get_string('referentiels', 'referentiel');
                    $posttext .= "\n \n";
                    $posttext .= '=====================================================================';
                    $posttext .= "\n \n";
                    $posttext .= "{$course->shortname} -> {$strreferentiels} -> " . format_string($activite->type_activite, true);
                    $posttext .= "\n";
                    $posthtml .= "<p><font face=\"sans-serif\">" . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">{$course->shortname}</a> -> " . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/referentiel/index.php?id={$course->id}\">{$strreferentiels}</a> -> " . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/referentiel/activite.php?d={$activite->ref_instance}&activite_id={$activite->id}\">" . format_string($activite->type_activite, true) . "</a>";
                    $posthtml .= "</font></p>";
                    $posthtml .= '<p>';
                    // $postsarray = $discussionposts[$discussionid];
                    // $postsarray = $userposts[$activite->id];
                    // mtrace("DEBUG : cron_lib.php : :: lib.php 1237 :: USERPOST");
                    // print_r($userposts);
                    // mtrace("DEBUG : cron_lib.php : :: lib.php 1240 :: POSTARRAY");
                    $postsarray = $userposts[$userid];
                    // print_r($userposts);
                    if ($postsarray && is_array($postsarray)) {
                        sort($postsarray);
                        foreach ($postsarray as $activiteid) {
                            $post = $activites[$activiteid];
                            if ($post->courseid == $course->id) {
                                // CORRIGE ERREUR affichage activites n'appartenat pas au cours AJOUT JF 07/12/2010
                                if (array_key_exists($post->userid, $users)) {
                                    // we might know him/her already
                                    $userfrom = $users[$post->userid];
                                } else {
                                    if ($userfrom = $DB->get_record("user", array("id" => "{$post_userid}"))) {
                                        $users[$userfrom->id] = $userfrom;
                                        // fetch only once, we can add it to user list, it will be skipped anyway
                                    } else {
                                        mtrace('Could not find user ' . $post->userid);
                                        continue;
                                    }
                                }
                                // JF 2011/10/25
                                if (!isset($userfrom->groups[$post->id])) {
                                    if (!isset($userfrom->groups)) {
                                        $userfrom->groups = array();
                                        $users[$userfrom->id]->groups = array();
                                    }
                                    $userfrom->groups[$post->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                                    $users[$userfrom->id]->groups[$post->id] = $userfrom->groups[$post->id];
                                }
                                $groupname = '';
                                if (!empty($userfrom->groups)) {
                                    // mtrace("\nDEBUG : lib.php :: 285 :: \n");
                                    // print_r($userfrom->groups);
                                    foreach ($userfrom->groups as $un_groupe) {
                                        if (!empty($un_groupe)) {
                                            // mtrace("\nDEBUG : lib_cron.php :: 288 \n");
                                            // print_r($un_groupe);
                                            foreach ($un_groupe as $groupe) {
                                                // mtrace("\nDEBUG : lib_cron.php :: 291 \n");
                                                // print_r($groupe);
                                                if (!empty($groupe->name)) {
                                                    $groupname .= $groupe->name . ' ';
                                                }
                                            }
                                        }
                                    }
                                    // mtrace("\nDEBUG : lib_cron.php :: 299 :: $groupname \n");
                                }
                                $userfrom->customheaders = array("Precedence: Bulk");
                                if ($userto->maildigest == 2) {
                                    // Subjects only
                                    $by = new object();
                                    $by->name = fullname($userfrom);
                                    $by->date = userdate($post->date_modif);
                                    if (!empty($groupname)) {
                                        $posttext .= "\n" . format_string($post->subject, true) . ' ' . get_string("bynameondate", "referentiel", $by) . ' - ' . get_string('groupe', 'referentiel', $groupname);
                                    } else {
                                        $posttext .= "\n" . format_string($post->subject, true) . ' ' . get_string("bynameondate", "referentiel", $by);
                                    }
                                    $posttext .= "\n---------------------------------------------------------------------";
                                    $by->name = "<a target=\"_blank\" href=\"{$CFG->wwwroot}/user/view.php?id={$userfrom->id}&amp;course={$course->id}\">{$by->name}</a>";
                                    $posthtml .= '<div><a target="_blank" href="' . $CFG->wwwroot . '/mod/referentiel/activite.php?d=' . $post->ref_instance . '&activite_id=' . $post->id . '">' . format_string($post->type_activite, true) . '</a> ' . get_string("bynameondate", "referentiel", $by) . '</div>';
                                } else {
                                    // The full treatment
                                    $context = context_module::instance($cm->id);
                                    $posttext = referentiel_make_mail_text(TYPE_ACTIVITE, $context, $course, $post, $userfrom, $userto, true);
                                    $posthtml = referentiel_make_mail_post(TYPE_ACTIVITE, $context, $course, $post, $userfrom, $userto, false, true, false);
                                }
                            }
                        }
                    }
                    $posthtml .= '<hr size="1" noshade="noshade" /></p>';
                }
                $posthtml .= '</body>';
                if ($userto->mailformat != 1) {
                    // This user DOESN'T want to receive HTML
                    $posthtml = '';
                }
                if (!($mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, '', '', $CFG->forum_replytouser))) {
                    mtrace("ERROR!: Could not send out referentiel activity digest mail to user {$userto->id} ({$userto->email})... not trying again.");
                    // add_to_log($course->id, 'referentiel', 'mail digest error', '', '', $cm->id, $userto->id);
                } else {
                    if ($mailresult === 'emailstop') {
                        // should not happen anymore - see check above
                    } else {
                        mtrace("success.");
                        $usermailcount++;
                    }
                }
            }
        }
        /// We have finishied all digest emails activities, update $CFG->digestactivitytimelast
        set_config('digestactivitytimelast', $timenow);
    }
    $USER = $cronuser;
    // course_setup(SITEID); // reset cron user language, theme and timezone settings
    cron_setup_user();
    if (!empty($usermailcount)) {
        mtrace(get_string('digestsentusers', 'referentiel', $usermailcount));
    }
    mtrace("FIN CRON REFERENTIEL ACTIVITE.\n");
    return true;
}