function referentiel_print_liste_certificats($initiale, $userids, $mode, $referentiel_instance, $userid_filtre = 0, $gusers, $select_acc = 0, $data_f = NULL, $sql_f_where = '', $sql_f_order = '')
{
    global $DB;
    global $CFG;
    global $USER;
    static $istutor = false;
    static $isteacher = false;
    static $isadmin = false;
    static $isstudent = false;
    static $iseditor = false;
    static $isauthor = false;
    $protocole_link = '';
    //MODIF JF 2012/02/18
    // contexte
    $cm = get_coursemodule_from_instance('referentiel', $referentiel_instance->id);
    $course = $DB->get_record('course', array('id' => $cm->course));
    if (empty($cm) or empty($course)) {
        print_print_error('REFERENTIEL_ERROR 5 :: print_lib-certificat.php :: You cannot call this script in that way');
    }
    $context = context_module::instance($cm->id);
    $roles = referentiel_roles_in_instance($referentiel_instance->id);
    $iseditor = $roles->is_editor;
    $isadmin = $roles->is_admin;
    $isteacher = $roles->is_teacher;
    $istutor = $roles->is_tutor;
    $isstudent = $roles->is_student;
    $isguest = $roles->is_guest;
    if (!empty($referentiel_instance->ref_referentiel)) {
        $referentiel_referentiel = referentiel_get_referentiel_referentiel($referentiel_instance->ref_referentiel);
        if (!$referentiel_referentiel) {
            if ($isadmin || $isteacher) {
                print_error(get_string('creer_referentiel', 'referentiel'), "edit.php?d={$referentiel_instance->id}&mode=editreferentiel&sesskey=" . sesskey());
            } else {
                print_error(get_string('creer_referentiel', 'referentiel'), "../../course/view.php?id={$course->id}&sesskey=" . sesskey());
            }
        }
        $isreferentielauteur = referentiel_is_author($USER->id, $referentiel_referentiel, !$isstudent);
        // MODIF JF 2012/02/18
        $seuil_certification = $referentiel_referentiel->seuil_certificat;
        $nb_items = referentiel_get_nb_items($referentiel_referentiel->id);
        // empreintes
        $liste_empreintes = referentiel_purge_dernier_separateur(referentiel_get_liste_empreintes_competence($referentiel_referentiel->id), '/');
        if ($isadmin || $isreferentielauteur) {
            $protocole_link = "{$CFG->wwwroot}/mod/referentiel/edit_protocole.php?d={$referentiel_instance->id}&mode=protocole&sesskey=" . sesskey();
        } else {
            $protocole_link = "{$CFG->wwwroot}/mod/referentiel/protocole.php?d={$referentiel_instance->id}&mode=protocole&sesskey=" . sesskey();
        }
        // REGENERER LES CERTIFICATS
        // MODIF JF 2009/10/23
        // referentiel_regenere_certificats($referentiel_instance); // INUTILE DESORMAIS
        // boite pour selectionner les utilisateurs ?
        if ($iseditor || $isteacher || $isadmin || $istutor) {
            if (!empty($select_acc)) {
                // eleves accompagnes
                $record_id_users = referentiel_get_accompagnements_teacher($referentiel_instance->id, $course->id, $USER->id);
            } else {
                // tous les users possibles (pour la boite de selection)
                // Get your userids the normal way
                $record_id_users = referentiel_get_students_course($course->id, 0, 0);
                //seulement les stagiaires
            }
            if ($gusers && $record_id_users) {
                // liste des utilisateurs du groupe courant
                // echo "<br />DEBUG :: print_lib_certificat.php :: 740 :: GUSERS<br />\n";
                // print_object($gusers);
                // echo "<br />\n";
                $record_users = array_intersect($gusers, array_keys($record_id_users));
                // $record_users  = array_intersect_assoc($record_id_users, array_keys($gusers));
                // echo "<br />DEBUG :: print_lib_certificat.php :: 745 :: RECORD_USERS<br />\n";
                // print_r($record_users  );
                // echo "<br />\n";
                // recopier
                $record_id_users = array();
                foreach ($record_users as $record_id) {
                    $a_obj = new stdClass();
                    $a_obj->userid = $record_id;
                    $record_id_users[] = $a_obj;
                }
            }
            echo referentiel_select_users_accompagnes("certificat.php", $mode, $userid_filtre, $select_acc);
            echo referentiel_select_users_certificat($record_id_users, "certificat.php", $initiale, $mode, $userid_filtre, $select_acc);
        } else {
            $userid_filtre = $USER->id;
            // les étudiants ne peuvent voir que leur fiche
        }
        // recuperer les utilisateurs filtres
        // si $userid_filtre ==0 on retourne tous les utilisateurs du cours et du groupe
        if (!empty($userid_filtre)) {
            $record_id_users = referentiel_get_students_course($course->id, $userid_filtre, 0);
        } else {
            if (!empty($select_acc)) {
                // eleves accompagnes
                $record_id_users = referentiel_get_accompagnements_teacher($referentiel_instance->id, $course->id, $USER->id);
            } else {
                $record_id_users = referentiel_get_students_course($course->id, $userid_filtre, 0);
            }
        }
        // groupes ?
        if ($gusers && $record_id_users) {
            $record_users = array_intersect($gusers, array_keys($record_id_users));
            // recopier
            $record_id_users = array();
            foreach ($record_users as $record_id) {
                $a_obj = new stdClass();
                $a_obj->userid = $record_id;
                $record_id_users[] = $a_obj;
            }
        }
        // ALPHABETIQUE
        if (!empty($userids)) {
            $t_users_select = explode('_', $userids);
            $record_id_users = array();
            foreach ($t_users_select as $userid) {
                $a_obj = new stdClass();
                $a_obj->userid = $userid;
                $record_id_users[] = $a_obj;
            }
            // DEBUG
            /*
            echo "<br />DEBUG :: print_lib_certificat.php :: 2386<br />USERIDS : $userids<br />\n";
            print_r($t_users_select);
            echo "<br />\n";
            print_r($record_id_users);
            exit;
            */
        }
        if ($record_id_users) {
            // Afficher
            // Filtres de selection
            echo referentiel_entete_filtre($CFG->wwwroot . '/mod/referentiel/certificat.php?d=' . $referentiel_referentiel->id . '&amp;mode=' . $mode . '&amp;sesskey=' . sesskey(), $data_f, false);
            if (isset($mode) && $mode == 'listcertifsingle') {
            } else {
                echo referentiel_print_entete_certificat();
            }
            // MODIF JF 2012/09/20
            // ordre d'affichage utilisateurs
            if (isset($data_f) && isset($data_f->f_auteur) && $data_f->f_auteur == '-1') {
                $deb = -count($record_id_users) + 1;
                $fin = 1;
            } else {
                $deb = 0;
                $fin = count($record_id_users);
            }
            // Parcours des utilisateurs
            for ($j = $deb; $j < $fin; $j++) {
                $i = abs($j);
                // recupere les enregistrements
                // recuperation des certificats
                // ATTENTION
                // il faut introduire les filtres SQL
                $records[] = referentiel_certificat_user_select($record_id_users[$i]->userid, $referentiel_instance->ref_referentiel, $sql_f_where, $sql_f_order);
            }
            if ($records) {
                foreach ($records as $record_id) {
                    // afficher la liste d'users
                    // recupere les enregistrements de certificats ou les cree si necessaire
                    $record = referentiel_certificat_user($record_id->userid, $referentiel_instance->ref_referentiel);
                    if ($record) {
                        // MODIF JF 2010/10/07
                        $isauthor = referentiel_certificat_isowner($record->id);
                        if ($isauthor || $iseditor || $istutor || $isteacher || $isadmin) {
                            if (isset($mode) && $mode == 'listcertifsingle') {
                                referentiel_print_certificat_detail($record, $seuil_certification, $protocole_link);
                                referentiel_menu_certificat_detail($context, $record->id, $referentiel_instance->id, $record->verrou && $isstudent, $record_id->userid, $select_acc, $record->valide);
                            } else {
                                referentiel_print_certificat($record, $nb_items, $liste_empreintes, $seuil_certification, $protocole_link);
                                echo referentiel_menu_certificat($context, $record->id, $referentiel_instance->id, $record->verrou && $isstudent, $record_id->userid, $select_acc, 0, $record->valide);
                            }
                        }
                    }
                }
            }
        }
        // Afficher
        if (isset($mode) && $mode == 'listcertifsingle') {
            // prints ratings options
            // referentiel_print_ratings($referentiel, $record);
            // prints ratings options
            // referentiel_print_comments($referentiel, $record);
        } else {
            echo referentiel_print_enqueue_certificat();
        }
        echo '<br /><br />' . "\n";
    }
}
function referentiel_get_liste_users_pagination($course, $referentiel_instance, $not_student, $userids = '', $userid_filtre = 0, $gusers = NULL, $select_acc = 0)
{
    // retourne la liste des utilisateurs a afficher
    global $USER;
    $record_id_users = array();
    // DEBUG
    // echo "<br />print_lib_activite.php :: 374:: SELECT_ACC: $select_acc, USERID: ".$USER->id.", USER_FILTRE: $userid_filtre\n";
    //exit;
    if ($not_student) {
        // liste des etudiants
        // recuperer les utilisateurs filtres
        if (!empty($select_acc) && $userid_filtre == 0) {
            // eleves accompagnes
            $record_id_users = referentiel_get_accompagnements_teacher($referentiel_instance->id, $course->id, $USER->id);
        } else {
            // retourne les etudiants du cours ou userid_filtre si != 0
            $record_id_users = referentiel_get_students_course($course->id, $userid_filtre, 0);
        }
        // afficher le groupe courant
        if ($record_id_users && $gusers) {
            // liste des utilisateurs du groupe courant
            $record_users = array_intersect($gusers, array_keys($record_id_users));
            // recopier
            $record_id_users = array();
            foreach ($record_users as $record_id) {
                $a = new stdClass();
                $a->userid = $record_id;
                $record_id_users[] = $a;
            }
        }
        // SELECTION ALPHABETIQUE
        if (!empty($userids)) {
            $t_users_select = explode('_', $userids);
            $record_id_users = array();
            foreach ($t_users_select as $userid) {
                $a = new stdClass();
                $a->userid = $userid;
                $record_id_users[] = $a;
            }
        } else {
            if (empty($record_id_users) && $userid_filtre != 0 && $userid_filtre == $USER->id) {
                // Ajouter l'utilisateur courant pour qu'il puisse voir ses propres activites
                $a = new stdClass();
                $a->userid = $USER->id;
                $record_id_users[] = $a;
            }
        }
    } else {
        // seulement l'utilisateur courant
        if ($userid_filtre == $USER->id || $userid_filtre == 0) {
            // Ajouter l'utilisateur courant pour qu'il puisse voir ses propres activites
            $a = new stdClass();
            $a->userid = $USER->id;
            $record_id_users[] = $a;
        }
    }
    return $record_id_users;
}
Example #3
0
function referentiel_cron_taches()
{
    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
    $tasks = array();
    $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("DEBUT CRON REFERENTIEL TACHES");
    $taches = referentiel_get_unmailed_tasks($starttime, $endtime);
    if ($taches) {
        if (REFERENTIEL_DEBUG) {
            mtrace("\nlib_cron.php :: 1675 :: TACHES\n");
            print_r($taches);
            mtrace("\n");
        }
        // 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_tasks_as_mailed($endtime)) {
            mtrace('Errors occurred while trying to mark some referentiel tasks as being mailed.');
            return false;
            // Don't continue trying to mail them, in case we are in a cron loop
        }
        // checking task validity, and adding users to loop through later
        foreach ($taches as $tid => $task) {
            // DEBUG : cron_lib.php :
            // mtrace('task '.$task->id.' '.$tid);
            if (REFERENTIEL_DEBUG) {
                mtrace("\nlib_cron.php :: 1694 :: TASK\n");
                print_r($task);
                mtrace("\n");
            }
            if (!isset($tasks[$tid])) {
                $tasks[$tid] = $task;
            }
            // cours
            $courseid = $tasks[$tid]->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($tasks[$tid]);
                    continue;
                }
            }
            // modules
            $instanceid = $task->ref_instance;
            if (!isset($coursemodules[$instanceid])) {
                if ($cm = get_coursemodule_from_instance('referentiel', $instanceid, $courseid)) {
                    $coursemodules[$instanceid] = $cm;
                } else {
                    mtrace('./mod/referentiel/lib.php : 1355 :  Could not load course module for referentiel instance ' . $instanceid);
                    unset($tasks[$tid]);
                    continue;
                }
            }
            // caching subscribed students of each task
            $students = array();
            $teachers = referentiel_get_teachers_course($courseid);
            // DEBUG : cron_lib.php :
            if (!isset($subscribedusers[$tid])) {
                // notifier tous les etudiants
                // ICI MODIFIER LA COLLECTE
                // NE PRENDRE QUE LES ETUDIANTS ACCOMPAGNES
                // $students=referentiel_get_students_accompagne($courseid,$task->auteurid);
                $students = referentiel_get_accompagnements_teacher($task->ref_instance, $task->ref_course, $task->auteurid);
                if (empty($students)) {
                    $students = referentiel_get_students_course($courseid, 0, 0, false);
                }
                if ($students) {
                    foreach ($students as $student) {
                        $user = referentiel_get_user($student->userid);
                        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[$tid][$student->userid] = $student->userid;
                            // this user is a user we have to process later
                            $users[$student->userid] = $user;
                            if (REFERENTIEL_DEBUG) {
                                mtrace("\nDEBUG :: lib_cron:: 1758 :: \nDESTINATAIRE ETUDIANT ID: " . $user->id . "\n");
                                //print_r($user);
                            }
                        }
                    }
                }
                unset($students);
                // release memory
                if (NOTIFICATION_TACHES_AUX_REFERENTS) {
                    //
                    if ($teachers) {
                        foreach ($teachers as $teacher) {
                            $user = referentiel_get_user($teacher->userid);
                            if ($user->emailstop) {
                                if (!empty($CFG->forum_logblocked)) {
                                    // add_to_log(SITEID, 'referentiel', 'mail blocked', '', '', 0, $teacher->userid);
                                }
                            } else {
                                // this user is subscribed to this notification
                                $subscribedusers[$tid][$user->id] = $user->id;
                                // this user is a user we have to process later
                                $users[$user->id] = $user;
                                // DEBUG : cron_lib.php :
                                if (REFERENTIEL_DEBUG) {
                                    mtrace("\nDEBUG :: lib_cron:: 1782 :: \nDESTINATAIRE TEACHER: " . $user->id . " \n");
                                    //print_r($user);
                                }
                            }
                        }
                    }
                }
                unset($teachers);
                // release memory
                $mailcount[$tid] = 0;
                $errorcount[$tid] = 0;
            }
        }
    }
    if ($users && $tasks) {
        // DEBUG : cron_lib.php :
        if (REFERENTIEL_DEBUG) {
            mtrace("TRAITEMENT DES MESSAGES TACHES\n");
        }
        $urlinfo = parse_url($CFG->wwwroot);
        $hostname = $urlinfo['host'];
        foreach ($users as $userto) {
            @set_time_limit(TIME_LIMIT);
            // terminate if processing of any account takes longer than 2 minutes
            // set this so that the capabilities are cached, and environment matches receiving user
            $USER = $userto;
            // mtrace('./mod/referentiel/lib.php :: Line 253 : Processing user '.$userto->id);
            // init caches
            $userto->viewfullnames = array();
            // $userto->canpost       = array();
            // $userto->markposts     = 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 ($tasks as $tid => $task) {
                // Set up the environment for activity, course
                $course = $courses[$task->ref_course];
                $cm =& $coursemodules[$task->ref_instance];
                // Do some checks  to see if we can mail out now
                if (!isset($subscribedusers[$tid][$userto->id])) {
                    continue;
                    // user does not subscribe to this activity
                }
                // Get info about the author user
                if (array_key_exists($task->auteurid, $users)) {
                    // we might know him/her already but we need a really complete user object, so.. get it again!
                    if ($userfrom = $DB->get_record("user", array("id" => "{$task->auteurid}"))) {
                        $users[$task->auteurid] = $userfrom;
                    } else {
                        // error
                        mtrace('Could not find user ' . $task->auteurid);
                        continue;
                    }
                } else {
                    if ($userfrom = $DB->get_record("user", array("id" => "{$task->auteurid}"))) {
                        $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 ' . $task->auteurid);
                        continue;
                    }
                }
                // setup global $COURSE properly - needed for roles and languages
                // course_setup($course);   // More environment
                // setup global $COURSE properly - needed for roles and languages
                cron_setup_user($userto, $course);
                // Fill caches
                if (!isset($userto->viewfullnames[$tid])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->viewfullnames[$tid] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                if (!isset($userfrom->groups[$tid])) {
                    if (!isset($userfrom->groups)) {
                        $userfrom->groups = array();
                        $users[$userfrom->id]->groups = array();
                    }
                    $userfrom->groups[$tid] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                    $users[$userfrom->id]->groups[$tid] = $userfrom->groups[$tid];
                }
                // OK so we need to send the email.
                // 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 = $task->id;
                    $queue->timemodified = $task->date_modif;
                    $queue->type = TYPE_TACHE;
                    // 1
                    if (!$DB->insert_record('referentiel_notification', $queue)) {
                        mtrace("Error: mod/referentiel/lib.php : Line 1510 : Could not queue for digest mail for id {$task->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($task->ref_instance);
                $cleanactivityname = str_replace('"', "'", strip_tags(format_string($strreferentielname . ' -> ' . $task->type_task)));
                $userfrom->customheaders = array('Precedence: Bulk', 'List-Id: "' . $cleanactivityname . '" <moodle_referentiel_activity_' . $task->id . '@' . $hostname . '>', 'List-Help: ' . $CFG->wwwroot . '/mod/referentiel/task.php?d=' . $task->ref_instance . '&task_id=' . $task->id . '&amp;mode=listtaskall', 'Message-ID: <moodle_referentiel_task_' . $task->id . '@' . $hostname . '>', 'X-Course-Id: ' . $course->id, 'X-Course-Name: ' . format_string($course->fullname, true));
                if (!($cm = get_coursemodule_from_instance('referentiel', $task->ref_instance, $course->id))) {
                    print_error('Course Module ID was incorrect');
                }
                $postsubject = "{$course->shortname}: " . format_string($strreferentielname . ' ' . $task->type_task, true);
                $context = context_module::instance($cm->id);
                $posttext = referentiel_make_mail_text(TYPE_TACHE, $context, $course, $task, $userfrom, $userto);
                $posthtml = referentiel_make_mail_html(TYPE_TACHE, $context, $course, $task, $userfrom, $userto);
                // Send the post now!
                // mtrace('Sending ', '');
                if (!($mailresult = email_to_user($userto, $userfrom, $postsubject, $posttext, $posthtml, '', '', $CFG->forum_replytouser))) {
                    mtrace("Error: Could not send out mail for id {$task->id} to user {$userto->id}" . " ({$userto->email}) .. not trying again.");
                    // add_to_log($course->id, 'referentiel', 'mail error', "task $task->id to $userto->id ($userto->email)","", $cm->id, $userto->id);
                    $errorcount[$tid]++;
                } else {
                    if ($mailresult === 'emailstop') {
                        // should not be reached anymore - see check above
                    } else {
                        $mailcount[$tid]++;
                    }
                }
            }
        }
    }
    if ($tasks) {
        foreach ($tasks as $task) {
            mtrace($mailcount[$task->id] . " users were sent task {$task->id}, {$task->type_task}");
            if ($errorcount[$task->id]) {
                $DB->set_field("referentiel_task", "mailed", "2", array("id" => "{$task->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...');
    @set_time_limit(TIME_LIMIT * 2);
    // terminate if not able to fetch all digests in 5 minutes
    if (!isset($CFG->digesttasktimelast)) {
        // To catch the first time
        set_config('digesttasktimelast', 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_TACHE . "'", NULL);
    mtrace('Cleaned old digest records');
    if ($CFG->digesttasktimelast < $digesttime and $timenow > $digesttime) {
        mtrace("Sending task digests: " . userdate($timenow, '', $sitetimezone));
        $params = array("digesttime" => "{$digesttime}", "type" => TYPE_TACHE);
        $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;
            //caches - reuse the those filled before too
            $userposts = array();
            //             while ($digestpost = rs_fetch_next_record($digestposts_rs)) {
            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
                if (!isset($taches[$digestpost->activiteid])) {
                    if ($tache = $DB->get_record("referentiel_task", array("id" => "{$digestpost->activiteid}"))) {
                        $taches[$digestpost->activiteid] = $tache;
                    } else {
                        continue;
                    }
                }
                $courseid = $taches[$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[$taches[$digestpost->activiteid]->ref_instance]) && $taches[$digestpost->activiteid]) {
                    if ($cm = get_coursemodule_from_instance('referentiel', $taches[$digestpost->activiteid]->ref_instance, $courseid)) {
                        $coursemodules[$taches[$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 ($userdiscussions as $userid => $thesediscussions) {
            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_TACHE . "'", 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();
                // $userto->canpost       = array();
                // $userto->markposts     = 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) {
                    @set_time_limit(TIME_LIMIT);
                    // to be reset for each post
                    $type_notification = TYPE_TACHE;
                    $tache = $taches[$tid];
                    $course = $courses[$taches[$tid]->ref_course];
                    $cm = $coursemodules[$taches[$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[$tache->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->viewfullnames[$tache->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($tache->type_task, 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/tache.php?id={$tache->ref_instance}&activite_id={$tache->id}\">" . format_string($tache->type_task, true) . "</a>";
                    $posthtml .= "</font></p>";
                    $posthtml .= '<p>';
                    //$postsarray = $userposts[$tache->id];
                    $postsarray = $userposts[$userid];
                    sort($postsarray);
                    foreach ($postsarray as $activiteid) {
                        $post = $taches[$activiteid];
                        if (array_key_exists($post->auteurid, $users)) {
                            // we might know him/her already
                            $userfrom = $users[$post->auteurid];
                        } else {
                            if ($userfrom = $DB->get_record("user", array("id" => "{$post->auteurid}"))) {
                                $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->auteurid);
                                continue;
                            }
                        }
                        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];
                        }
                        $userfrom->customheaders = array("Precedence: Bulk");
                        if ($userto->maildigest == 2) {
                            // Subjects only
                            $by = new object();
                            $by->name = fullname($userfrom);
                            $by->date = userdate($post->date_modif);
                            $posttext .= "\n" . format_string($post->type_task, 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/task.php?d=' . $post->ref_instance . '&activite_id=' . $post->id . '">' . format_string($post->type_activite, true) . '</a> ' . get_string("bynameondate", "referentiel", $by) . '</div>';
                        } else {
                            $context = context_module::instance($cm->id);
                            $posttext = referentiel_make_mail_text(TYPE_TACHE, $context, $course, $post, $userfrom, $userto, true);
                            $posthtml = referentiel_make_mail_post(TYPE_TACHE, $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!");
                    mtrace("Error: Could not send out digest mail to user {$userto->id} ({$userto->email})... not trying again.\n");
                    // 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('digesttasktimelast', $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 TACHE.\n");
    return true;
}
function referentiel_print_suivi_user($mode, $referentiel_instance, $userid_filtre = 0, $gusers = NULL, $sql_filtre_where = '', $sql_filtre_order = '', $data_filtre, $select_acc = 0)
{
    // Affiche les repartitions d'affectations
    // pour toutes les competences cette instance de referentiel
    global $DB;
    global $CFG;
    global $USER;
    static $istutor = false;
    static $isteacher = false;
    static $isadmin = false;
    static $iseditor = false;
    static $referentiel_id = NULL;
    // A COMPLETER
    $data = NULL;
    if (!empty($referentiel_instance)) {
        $cm = get_coursemodule_from_instance('referentiel', $referentiel_instance->id);
        $course = $DB->get_record('course', array('id' => $cm->course));
        if (empty($cm) or empty($course)) {
            print_error('REFERENTIEL_ERROR :: print_lib_repartition.php :: 166 :: You cannot call this script in that way');
        }
        // echo "<br />DEBUG :: 220 ::<br />REFERENTIEL_Instance : $referentiel_instance->id <br /> Course_id : $referentiel_instance->course\n";
        $context = context_module::instance($cm->id);
        $refrefid = $referentiel_instance->ref_referentiel;
        $roles = referentiel_roles_in_instance($referentiel_instance->id);
        $iseditor = $roles->is_editor;
        $isadmin = $roles->is_admin;
        $isteacher = $roles->is_teacher;
        $istutor = $roles->is_tutor;
        $isstudent = $roles->is_student;
        /*
                // DEBUG
        if ($isadmin) echo "Admin ";
                if ($isteacher) echo "Teacher ";
        if ($istutor) echo "Tutor ";
        if ($isstudent) echo "Student ";
        */
        if (!empty($refrefid)) {
            $referentiel_referentiel = referentiel_get_referentiel_referentiel($refrefid);
            if (!$referentiel_referentiel) {
                if ($iseditor) {
                    print_error(get_string('creer_referentiel', 'referentiel'), "edit.php?d={$referentiel_instance->id}&amp;mode=editreferentiel&amp;sesskey=" . sesskey());
                } else {
                    print_error(get_string('creer_referentiel', 'referentiel'), "../../course/view.php?id={$course->id}&amp;sesskey=" . sesskey());
                }
            }
            // boite pour selectionner les utilisateurs ?
            if ($isteacher || $iseditor || $istutor) {
                if (!empty($select_acc)) {
                    // eleves accompagnes
                    $record_id_users = referentiel_get_accompagnements_teacher($referentiel_instance->id, $course->id, $USER->id);
                } else {
                    // tous les users possibles (pour la boite de selection)
                    // Get your userids the normal way
                    $record_id_users = referentiel_get_students_course($course->id, 0, 0);
                    //seulement les stagiaires
                }
                if ($gusers && $record_id_users) {
                    // liste des utilisateurs du groupe courant
                    // echo "<br />DEBUG :: print_lib_activite.php :: 740 :: GUSERS<br />\n";
                    // print_object($gusers);
                    // echo "<br />\n";
                    // exit;
                    $record_users = array_intersect($gusers, array_keys($record_id_users));
                    // echo "<br />DEBUG :: print_lib_repartition.php :: 745 :: RECORD_USERS<br />\n";
                    // print_r($record_users  );
                    // echo "<br />\n";
                    // recopier
                    $record_id_users = array();
                    foreach ($record_users as $record_id) {
                        $a_obj = new stdClass();
                        $a_obj->userid = $record_id;
                        $record_id_users[] = $a_obj;
                    }
                }
                // echo referentiel_select_users_activite($record_id_users, $userid_filtre, $mode, $select_acc);
                echo referentiel_select_users_accompagnes($userid_filtre, $select_acc, $mode);
                echo referentiel_select_users_2($record_id_users, $userid_filtre, $select_acc, $mode);
            } else {
                $userid_filtre = $USER->id;
                // les étudiants ne peuvent voir que leur fiche
            }
            // recuperer les utilisateurs filtres
            // $userid_filtre est l'id de l'utilisateur dont on affiche les activites
            // si $userid_filtre ==0 on retourne tous les utilisateurs du cours et du groupe
            if (!empty($userid_filtre)) {
                $record_id_users = referentiel_get_students_course($course->id, $userid_filtre, 0);
            } else {
                if (!empty($select_acc)) {
                    // eleves accompagnes
                    $record_id_users = referentiel_get_accompagnements_teacher($referentiel_instance->id, $course->id, $USER->id);
                } else {
                    $record_id_users = referentiel_get_students_course($course->id, $userid_filtre, 0);
                    // echo "<br />DEBUG :: print_lib_repartition.php :: 1850 :: RECORD_USERS<br />\n";
                    // print_r($record_users  );
                    // echo "<br />\n";
                }
            }
            if ($record_id_users && $gusers) {
                // liste des utilisateurs du groupe courant
                $record_users = array_intersect($gusers, array_keys($record_id_users));
                // recopier
                $record_id_users = array();
                foreach ($record_users as $record_id) {
                    $a_obj = new stdClass();
                    $a_obj->userid = $record_id;
                    $record_id_users[] = $a_obj;
                }
            }
            if (($userid_filtre == $USER->id || $userid_filtre == 0) && ($isteacher || $iseditor || $istutor)) {
                // Ajouter l'utilisateur courant pour qu'il puisse voir ses activites
                $a_obj = new stdClass();
                $a_obj->userid = $USER->id;
                $record_id_users[] = $a_obj;
            }
            // echo "<br />DEBUG :: print_lib_repartition.php :: 1870 :: RECORD_USERS<br />\n";
            // print_r($record_users  );
            // echo "<br />\n";
            if ($userid_filtre) {
                // Afficher
                // codes item
                $records_teacher = referentiel_get_teachers_course($course->id);
                $t_codes_competence = explode('/', referentiel_purge_dernier_separateur($referentiel_referentiel->liste_codes_competence, '/'));
                echo referentiel_print_notification_user($referentiel_instance->id, $course->id, $context, $t_codes_competence, $userid_filtre, $records_teacher);
            }
        }
    }
}
/**
 * This function returns records of users ids
 *
 * If select_all == 1 all certificates users are displayed
 * Else only course's users are displayed
 * @param object referentiel_instance instance of referentiel
 * @param userid_filtre int
 * @param guser Object
 * @param mode string
 * @param select_all : int
 * @param select_acc : int
 * @param affiche : boolean
 * @return objects
 * @todo Finish documenting this function
 **/
function referentiel_get_liste_users($referentiel_instance, $course, $context, $list_userids = '', $userid_filtre = 0, $gusers, $select_acc = 0, $select_all = 0)
{
    global $debug_special;
    global $USER;
    static $referentiel_id = NULL;
    $records = array();
    if ($referentiel_instance) {
        $roles = referentiel_roles_in_instance($referentiel_instance->id);
        $iseditor = $roles->is_editor;
        $isadmin = $roles->is_admin;
        $isteacher = $roles->is_teacher;
        $istutor = $roles->is_tutor;
        $isstudent = $roles->is_student;
        // recuperer les certificats
        if (!empty($list_userids)) {
            // liste d'utilisateurs obtenus par les pedagogies
            $tuserids = explode(',', $list_userids);
            foreach ($tuserids as $userid) {
                // forcer la generation
                if ($userid) {
                    $records[] = $userid;
                }
            }
        } else {
            if ($isadmin && $select_all) {
                // tous les utilisateurs ayant un certificat
                // tous les utilisateurs ayant un certificat
                if ($record_id_users = referentiel_get_certificats_id_users($referentiel_instance->ref_referentiel)) {
                    foreach ($record_id_users as $record_id) {
                        $records[] = $record_id->userid;
                    }
                }
            } else {
                // recuperer les utilisateurs filtres
                if (!empty($userid_filtre)) {
                    // un seul certificat
                    $records[] = $userid_filtre;
                } else {
                    // teachers    :: les certificats du cours seulement
                    if (!empty($select_acc)) {
                        // eleves accompagnes
                        $record_id_users = referentiel_get_accompagnements_teacher($referentiel_instance->id, $course->id, $USER->id);
                    } else {
                        $record_id_users = referentiel_get_students_course($course->id, $userid_filtre, 0);
                    }
                    // groupes ?
                    if ($gusers && $record_id_users) {
                        $record_users = array_intersect($gusers, array_keys($record_id_users));
                        // recopier
                        $record_id_users = array();
                        foreach ($record_users as $record_id) {
                            $a_obj = new stdClass();
                            $a_obj->userid = $record_id;
                            $record_id_users[] = $a_obj;
                        }
                    }
                    if ($record_id_users) {
                        foreach ($record_id_users as $record_id) {
                            // afficher la liste d'users
                            $records[] = $record_id->userid;
                        }
                    }
                }
            }
        }
    }
    //  if referentiel
    return $records;
}