Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / search / documents / chat_document.php
blobacc4ffb479b234468bec8f3c3aa6708eb4dd12f8
1 <?php
2 /**
3 * Global Search Engine for Moodle
5 * @package search
6 * @category core
7 * @subpackage document_wrappers
8 * @author Valery Fremaux [valery.fremaux@club-internet.fr] > 1.8
9 * @date 2008/03/31
10 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
12 * document handling for chat activity module
13 * This file contains the mapping between a chat history and it's indexable counterpart,
15 * Functions for iterating and retrieving the necessary records are now also included
16 * in this file, rather than mod/chat/lib.php
20 /**
21 * includes and requires
23 require_once("$CFG->dirroot/search/documents/document.php");
24 require_once("$CFG->dirroot/mod/chat/lib.php");
26 /**
27 * a class for representing searchable information
30 class ChatTrackSearchDocument extends SearchDocument {
32 /**
33 * constructor
35 public function __construct(&$chatsession, $chat_module_id, $course_id, $group_id, $context_id) {
36 // generic information; required
37 $doc->docid = $chat_module_id.'-'.$chatsession['sessionstart'].'-'.$chatsession['sessionend'];
38 $doc->documenttype = SEARCH_TYPE_CHAT;
39 $doc->itemtype = 'session';
40 $doc->contextid = $context_id;
42 $duration = $chatsession['sessionend'] - $chatsession['sessionstart'];
43 // we cannot call userdate with relevant locale at indexing time.
44 $doc->title = get_string('chatreport', 'chat').' '.get_string('openedon', 'search').' TT_'.$chatsession['sessionstart'].'_TT ('.get_string('duration', 'search').' : '.get_string('numseconds', '', $duration).')';
45 $doc->date = $chatsession['sessionend'];
47 //remove '(ip.ip.ip.ip)' from chat author list
48 $doc->author = preg_replace('/\(.*?\)/', '', $chatsession['authors']);
49 $doc->contents = $chatsession['content'];
50 $doc->url = chat_make_link($chat_module_id, $chatsession['sessionstart'], $chatsession['sessionend']);
52 // module specific information; optional
53 $data->chat = $chat_module_id;
55 // construct the parent class
56 parent::__construct($doc, $data, $course_id, $group_id, 0, PATH_FOR_SEARCH_TYPE_CHAT);
61 /**
62 * constructs a valid link to a chat content
63 * @param cm_id the chat course module
64 * @param start the start time of the session
65 * @param end th end time of the session
66 * @uses CFG
67 * @return a well formed link to session display
69 function chat_make_link($cm_id, $start, $end) {
70 global $CFG;
72 return $CFG->wwwroot.'/mod/chat/report.php?id='.$cm_id.'&amp;start='.$start.'&amp;end='.$end;
75 /**
76 * fetches all the records for a given session and assemble them as a unique track
77 * we revamped here the code of report.php for making sessions, but without any output.
78 * note that we should collect sessions "by groups" if groupmode() is SEPARATEGROUPS.
79 * @param int $chat_id the database
80 * @param int $fromtime
81 * @param int $totime
82 * @uses CFG
83 * @return an array of objects representing the chat sessions.
85 function chat_get_session_tracks($chat_id, $fromtime = 0, $totime = 0) {
86 global $CFG;
88 $chat = get_record('chat', 'id', $chat_id);
89 $course = get_record('course', 'id', $chat->course);
90 $coursemodule = get_field('modules', 'id', 'name', 'data');
91 $cm = get_record('course_modules', 'course', $course->id, 'module', $coursemodule, 'instance', $chat->id);
92 $groupmode = groupmode($course, $cm);
94 $fromtimeclause = ($fromtime) ? "AND timestamp >= {$fromtime}" : '';
95 $totimeclause = ($totime) ? "AND timestamp <= {$totime}" : '';
96 $tracks = array();
97 $messages = get_records_select('chat_messages', "chatid = '{$chat_id}' $fromtimeclause $totimeclause", "timestamp DESC");
98 if ($messages){
99 // splits discussions against groups
100 $groupedMessages = array();
101 if ($groupmode != SEPARATEGROUPS){
102 foreach($messages as $aMessage){
103 $groupedMessages[$aMessage->groupid][] = $aMessage;
105 } else {
106 $groupedMessages[-1] = &$messages;
108 $sessiongap = 5 * 60; // 5 minutes silence means a new session
109 $sessionend = 0;
110 $sessionstart = 0;
111 $sessionusers = array();
112 $lasttime = time();
114 foreach ($groupedMessages as $groupId => $messages) { // We are walking BACKWARDS through the messages
115 $messagesleft = count($messages);
116 foreach ($messages as $message) { // We are walking BACKWARDS through the messages
117 $messagesleft --; // Countdown
119 if ($message->system) {
120 continue;
122 // we are within a session track
123 if ((($lasttime - $message->timestamp) < $sessiongap) and $messagesleft) { // Same session
124 if (count($tracks) > 0){
125 if ($message->userid) { // Remember user and count messages
126 $tracks[count($tracks) - 1]->sessionusers[$message->userid] = $message->userid;
127 // update last track (if exists) record appending content (remember : we go backwards)
129 $tracks[count($tracks) - 1]->content .= ' '.$message->message;
130 $tracks[count($tracks) - 1]->sessionstart = $message->timestamp;
132 } else {
133 // we initiate a new session track (backwards)
134 $track = new Object();
135 $track->sessionend = $message->timestamp;
136 $track->sessionstart = $message->timestamp;
137 $track->content = $message->message;
138 // reset the accumulator of users
139 $track->sessionusers = array();
140 $track->sessionusers[$message->userid] = $message->userid;
141 $track->groupid = $groupId;
142 $tracks[] = $track;
144 $lasttime = $message->timestamp;
148 return $tracks;
152 * part of search engine API
155 function chat_iterator() {
156 $chatrooms = get_records('chat');
157 return $chatrooms;
161 * part of search engine API
164 function chat_get_content_for_index(&$chat) {
165 $documents = array();
166 $course = get_record('course', 'id', $chat->course);
167 $coursemodule = get_field('modules', 'id', 'name', 'chat');
168 $cm = get_record('course_modules', 'course', $chat->course, 'module', $coursemodule, 'instance', $chat->id);
169 if ($cm){
170 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
172 // getting records for indexing
173 $sessionTracks = chat_get_session_tracks($chat->id);
174 if ($sessionTracks){
175 foreach($sessionTracks as $aTrackId => $aTrack) {
176 foreach($aTrack->sessionusers as $aUserId){
177 $user = get_record('user', 'id', $aUserId);
178 $aTrack->authors = ($user) ? fullname($user) : '' ;
179 $documents[] = new ChatTrackSearchDocument(get_object_vars($aTrack), $cm->id, $chat->course, $aTrack->groupid, $context->id);
183 return $documents;
185 return array();
189 * returns a single data search document based on a chat_session id
190 * chat session id is a text composite identifier made of :
191 * - the chat id
192 * - the timestamp when the session starts
193 * - the timestamp when the session ends
194 * @param id the multipart chat session id
195 * @param itemtype the type of information (session is the only type)
197 function chat_single_document($id, $itemtype) {
198 list($chat_id, $sessionstart, $sessionend) = split('-', $id);
199 $chat = get_record('chat', 'id', $chat_id);
200 $course = get_record('course', 'id', $chat->course);
201 $coursemodule = get_field('modules', 'id', 'name', 'chat');
202 $cm = get_record('course_modules', 'course', $course->id, 'module', $coursemodule, 'instance', $chat->id);
203 if ($cm){
204 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
206 // should be only one
207 $tracks = chat_get_session_tracks($chat->id, $sessionstart, $sessionstart);
208 if ($tracks){
209 $aTrack = $tracks[0];
210 $document = new ChatTrackSearchDocument(get_object_vars($aTrack), $cm->id, $chat->course, $aTrack->groupid, $context->id);
211 return $document;
214 return null;
218 * dummy delete function that packs id with itemtype.
219 * this was here for a reason, but I can't remember it at the moment.
222 function chat_delete($info, $itemtype) {
223 $object->id = $info;
224 $object->itemtype = $itemtype;
225 return $object;
229 * returns the var names needed to build a sql query for addition/deletions
230 * // TODO chat indexable records are virtual. Should proceed in a special way
232 function chat_db_names() {
233 //[primary id], [table name], [time created field name], [time modified field name]
234 return null;
238 * this function handles the access policy to contents indexed as searchable documents. If this
239 * function does not exist, the search engine assumes access is allowed.
240 * When this point is reached, we already know that :
241 * - user is legitimate in the surrounding context
242 * - user may be guest and guest access is allowed to the module
243 * - the function may perform local checks within the module information logic
244 * @param path the access path to the module script code
245 * @param itemtype the information subclassing (usefull for complex modules, defaults to 'standard')
246 * @param this_id the item id within the information class denoted by entry_type. In chats, this id
247 * points out a session history which is a close sequence of messages.
248 * @param user the user record denoting the user who searches
249 * @param group_id the current group used by the user when searching
250 * @uses CFG
251 * @return true if access is allowed, false elsewhere
253 function chat_check_text_access($path, $itemtype, $this_id, $user, $group_id, $context_id){
254 global $CFG;
256 include_once("{$CFG->dirroot}/{$path}/lib.php");
258 list($chat_id, $sessionstart, $sessionend) = split('-', $id);
260 // get the chat session and all related stuff
261 $chat = get_record('chat', 'id', $chat_id);
262 $context = get_record('context', 'id', $context_id);
263 $cm = get_record('course_modules', 'id', $context->instanceid);
264 // $cm = get_coursemodule_from_instance('chat', $chat->id, $chat->course);
265 // $context = get_context_instance(CONTEXT_MODULE, $cm->id);
267 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)){
268 if (!empty($CFG->search_access_debug)) echo "search reject : hidden chat ";
269 return false;
272 //group consistency check : checks the following situations about groups
273 // trap if user is not same group and groups are separated
274 $current_group = get_current_group($course->id);
275 $course = get_record('course', 'id', $chat->course);
276 if ((groupmode($course, $cm) == SEPARATEGROUPS) && !ismember($group_id) && !has_capability('moodle/site:accessallgroups', $context)){
277 if (!empty($CFG->search_access_debug)) echo "search reject : chat element is in separated group ";
278 return false;
281 //ownership check : checks the following situations about user
282 // trap if user is not owner and has cannot see other's entries
283 // TODO : typically may be stored into indexing cache
284 if (!has_capability('mod/chat:readlog', $context)){
285 if (!empty($CFG->search_access_debug)) echo "search reject : cannot read past sessions ";
286 return false;
289 return true;
293 * this call back is called when displaying the link for some last post processing
296 function chat_link_post_processing($title){
297 setLocale(LC_TIME, substr(current_language(), 0, 2));
298 $title = preg_replace('/TT_(.*)_TT/e', "userdate(\\1)", $title);
299 return mb_convert_encoding($title, 'UTF-8', 'auto');