"MDL-14120, fix print_error"
[moodle.git] / mod / glossary / lib.php
CommitLineData
41905731 1<?php // $Id$
07842023 2
3/// Library of functions and constants for module glossary
4/// (replace glossary with the name of your module and delete this line)
5
f1e0649c 6require_once($CFG->libdir.'/filelib.php');
07842023 7
7dd88447 8define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
9define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
c76e673a 10
1ac87c73 11define("GLOSSARY_NO_VIEW", -1);
7dd88447 12define("GLOSSARY_STANDARD_VIEW", 0);
13define("GLOSSARY_CATEGORY_VIEW", 1);
c197e607 14define("GLOSSARY_DATE_VIEW", 2);
1ac87c73 15define("GLOSSARY_AUTHOR_VIEW", 3);
16define("GLOSSARY_ADDENTRY_VIEW", 4);
17define("GLOSSARY_IMPORT_VIEW", 5);
18define("GLOSSARY_EXPORT_VIEW", 6);
19define("GLOSSARY_APPROVAL_VIEW", 7);
fb443f1a 20
da9c60ec 21/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
22
07842023 23function glossary_add_instance($glossary) {
c18269c7 24 global $DB;
07842023 25/// Given an object containing all the necessary data,
7cac0c4b 26/// (defined by the form in mod_form.php) this function
07842023 27/// will create a new instance and return the id number
28/// of the new instance.
29
63e21b9b 30 if (empty($glossary->userating)) {
63dd5fb2 31 $glossary->assessed = 0;
32 }
33
e6d45048 34 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 35 $glossary->assesstimestart = 0;
36 $glossary->assesstimefinish = 0;
37 }
38
63e21b9b 39 if (empty($glossary->globalglossary) ) {
0de786f7 40 $glossary->globalglossary = 0;
63e21b9b 41 }
42
957f6fc9 43 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
0de786f7 44 $glossary->globalglossary = 0;
45 }
46
e6d45048 47 $glossary->timecreated = time();
07842023 48 $glossary->timemodified = $glossary->timecreated;
49
ff424012 50 //Check displayformat is a valid one
51 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
52 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 53 print_error('unknowformat', '', '', $glossary->displayformat);
a02c77dc 54 }
24c1be88 55
c18269c7 56 if ($returnid = $DB->insert_record("glossary", $glossary)) {
e6d45048 57 $glossary->id = $returnid;
612607bd 58 glossary_grade_item_update($glossary);
e6d45048 59 }
60
61 return $returnid;
07842023 62}
63
64
65function glossary_update_instance($glossary) {
66/// Given an object containing all the necessary data,
7cac0c4b 67/// (defined by the form in mod_form.php) this function
07842023 68/// will update an existing instance with new data.
c18269c7 69 global $CFG, $DB;
a02c77dc 70
da5754f8 71 if (empty($glossary->globalglossary)) {
72 $glossary->globalglossary = 0;
73 }
0de786f7 74
957f6fc9 75 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
63e21b9b 76 // keep previous
77 unset($glossary->globalglossary);
78 }
79
07842023 80 $glossary->timemodified = time();
e6d45048 81 $glossary->id = $glossary->instance;
07842023 82
63e21b9b 83 if (empty($glossary->userating)) {
63dd5fb2 84 $glossary->assessed = 0;
85 }
86
e6d45048 87 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 88 $glossary->assesstimestart = 0;
89 $glossary->assesstimefinish = 0;
90 }
91
ff424012 92 //Check displayformat is a valid one
93 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
94 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 95 print_error('unknowformat', '', '', $glossary->displayformat);
ff424012 96 }
97
c18269c7 98 if ($return = $DB->update_record("glossary", $glossary)) {
e6d45048 99 if ($glossary->defaultapproval) {
c18269c7 100 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
e6d45048 101 }
102 glossary_grade_item_update($glossary);
5eaa2d34 103 }
07842023 104
5eaa2d34 105 return $return;
07842023 106}
107
108
109function glossary_delete_instance($id) {
c18269c7 110 global $DB;
07842023 111/// Given an ID of an instance of this module,
112/// this function will permanently delete the instance
113/// and any data that depends on it.
114
c18269c7 115 if (! $glossary = $DB->get_record("glossary", array("id"=>"$id"))) {
07842023 116 return false;
117 }
118
119 $result = true;
120
121 # Delete any dependent records here #
122
c18269c7 123 if (! $DB->delete_records("glossary", array("id"=>$glossary->id))) {
07842023 124 $result = false;
49210b90 125 } else {
c18269c7 126 if ($categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id))) {
49210b90 127 $cats = "";
4070cddf 128 foreach ( $categories as $cat ) {
49210b90 129 $cats .= "$cat->id,";
130 }
131 $cats = substr($cats,0,-1);
132 if ($cats) {
c18269c7 133 $DB->delete_records_select("glossary_entries_categories", "categoryid in ($cats)");
134 $DB->delete_records("glossary_categories", array("glossaryid"=>$glossary->id));
49210b90 135 }
136 }
c18269c7 137 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
49210b90 138 $ents = "";
139 foreach ( $entries as $entry ) {
072f7533 140 if ( $entry->sourceglossaryid ) {
141 $entry->glossaryid = $entry->sourceglossaryid;
142 $entry->sourceglossaryid = 0;
c18269c7 143 $DB->update_record("glossary_entries",$entry);
072f7533 144 } else {
145 $ents .= "$entry->id,";
146 }
49210b90 147 }
148 $ents = substr($ents,0,-1);
149 if ($ents) {
c18269c7 150 $DB->delete_records_select("glossary_comments", "entryid in ($ents)");
151 $DB->delete_records_select("glossary_alias", "entryid in ($ents)");
152 $DB->delete_records_select("glossary_ratings", "entryid in ($ents)");
49210b90 153 }
154 }
072f7533 155 glossary_delete_attachments($glossary);
c18269c7 156 $DB->delete_records("glossary_entries", array("glossaryid"=>$glossary->id));
07842023 157 }
e6d45048 158 glossary_grade_item_delete($glossary);
07842023 159
160 return $result;
161}
162
163function glossary_user_outline($course, $user, $mod, $glossary) {
164/// Return a small object with summary information about what a
165/// user has done with a given particular instance of this module
166/// Used for user activity reports.
167/// $return->time = the time they did it
168/// $return->info = a short text description
169
1ac87c73 170 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
e6d45048 171 $result = new object();
1ac87c73 172 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
173
63dd5fb2 174 $lastentry = array_pop($entries);
175 $result->time = $lastentry->timemodified;
1ac87c73 176 return $result;
177 }
178 return NULL;
179}
180
181function glossary_get_user_entries($glossaryid, $userid) {
182/// Get all the entries for a user in a glossary
183 global $CFG;
184
185 return get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
a02c77dc 186 FROM {$CFG->prefix}glossary g,
187 {$CFG->prefix}glossary_entries e,
188 {$CFG->prefix}user u
189 WHERE g.id = '$glossaryid'
190 AND e.glossaryid = g.id
191 AND e.userid = '$userid'
1ac87c73 192 AND e.userid = u.id
193 ORDER BY e.timemodified ASC");
07842023 194}
195
196function glossary_user_complete($course, $user, $mod, $glossary) {
197/// Print a detailed representation of what a user has done with
198/// a given particular instance of this module, for user activity reports.
1ac87c73 199 global $CFG;
07842023 200
1ac87c73 201 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
a359c29b 202 echo '<table width="95%" border="0"><tr><td>';
1ac87c73 203 foreach ($entries as $entry) {
204 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
205 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
206 echo '<p>';
207 }
a359c29b 208 echo '</td></tr></table>';
1ac87c73 209 }
07842023 210}
211
dd97c328 212function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
07842023 213/// Given a course and a time, this module should find recent activity
214/// that has occurred in glossary activities and print it out.
215/// Return true if there was output, or false is there was none.
216
dd97c328 217 global $CFG, $USER;
218
219 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
220
221 $modinfo = get_fast_modinfo($course);
222 $ids = array();
223 foreach ($modinfo->cms as $cm) {
224 if ($cm->modname != 'glossary') {
225 continue;
226 }
227 if (!$cm->uservisible) {
228 continue;
229 }
230 $ids[$cm->instance] = $cm->instance;
231 }
232
233 if (!$ids) {
234 return false;
235 }
236
237 $glist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
07842023 238
dd97c328 239 if (!$entries = get_records_sql("SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
240 ge.userid, u.firstname, u.lastname, u.email, u.picture
241 FROM {$CFG->prefix}glossary_entries ge
242 JOIN {$CFG->prefix}user u ON u.id = ge.userid
243 WHERE ge.glossaryid IN ($glist) AND ge.timemodified > $timestart
244 ORDER BY ge.timemodified ASC")) {
07842023 245 return false;
246 }
247
dd97c328 248 $editor = array();
a359c29b 249
dd97c328 250 foreach ($entries as $entryid=>$entry) {
251 if ($entry->approved) {
cf8eaebb 252 continue;
253 }
dd97c328 254
255 if (!isset($editor[$entry->glossaryid])) {
256 $editor[$entry->glossaryid] = has_capability('mod/glossary:approve', get_context_instance(CONTEXT_MODULE, $modinfo->instances['glossary'][$entry->glossaryid]->id));
07842023 257 }
07842023 258
dd97c328 259 if (!$editor[$entry->glossaryid]) {
260 unset($entries[$entryid]);
261 }
262 }
8f7dc7f1 263
dd97c328 264 if (!$entries) {
265 return false;
266 }
267 print_headline(get_string('newentries', 'glossary').':');
268
269 $strftimerecent = get_string('strftimerecent');
270 foreach ($entries as $entry) {
271 $link = $CFG->wwwroot.'/mod/glossary/view.php?g='.$entry->glossaryid.'&amp;mode=entry&amp;hook='.$entry->id;
272 if ($entry->approved) {
273 $dimmed = '';
274 } else {
275 $dimmed = ' dimmed_text';
07842023 276 }
dd97c328 277 echo '<div class="head'.$dimmed.'">';
278 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
279 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
280 echo '</div>';
281 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
07842023 282 }
283
dd97c328 284 return true;
07842023 285}
286
8f7dc7f1 287
1ac87c73 288function glossary_log_info($log) {
289 global $CFG;
290
291 return get_record_sql("SELECT e.*, u.firstname, u.lastname
292 FROM {$CFG->prefix}glossary_entries e,
293 {$CFG->prefix}user u
294 WHERE e.id = '$log->info'
295 AND u.id = '$log->userid'");
296}
297
07842023 298function glossary_cron () {
299/// Function to be run periodically according to the moodle cron
300/// This function searches for things that need to be done, such
301/// as sending out mail, toggling flags etc ...
302
303 global $CFG;
304
305 return true;
306}
307
d31bae70 308/**
309 * Return grade for given user or all users.
310 *
311 * @param int $glossaryid id of glossary
312 * @param int $userid optional user id, 0 means all users
313 * @return array array of grades, false if none
314 */
612607bd 315function glossary_get_user_grades($glossary, $userid=0) {
e6d45048 316 global $CFG;
63dd5fb2 317
e6d45048 318 $user = $userid ? "AND u.id = $userid" : "";
63dd5fb2 319
ac9b0805 320 $sql = "SELECT u.id, u.id AS userid, avg(gr.rating) AS rawgrade
e6d45048 321 FROM {$CFG->prefix}user u, {$CFG->prefix}glossary_entries ge,
322 {$CFG->prefix}glossary_ratings gr
323 WHERE u.id = ge.userid AND ge.id = gr.entryid
612607bd 324 AND gr.userid != u.id AND ge.glossaryid = $glossary->id
e6d45048 325 $user
326 GROUP BY u.id";
327
328 return get_records_sql($sql);
329}
330
d31bae70 331/**
332 * Update grades by firing grade_updated event
333 *
612607bd 334 * @param object $glossary null means all glossaries
d31bae70 335 * @param int $userid specific user only, 0 mean all
336 */
612607bd 337function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
e6d45048 338 global $CFG;
adcbb43a 339 require_once($CFG->libdir.'/gradelib.php');
e6d45048 340
612607bd 341 if ($glossary != null) {
342 if ($grades = glossary_get_user_grades($glossary, $userid)) {
eafb9d9e 343 glossary_grade_item_update($glossary, $grades);
3e6303b7 344
1970d243 345 } else if ($userid and $nullifnone) {
612607bd 346 $grade = new object();
3bfabe6e 347 $grade->userid = $userid;
ac9b0805 348 $grade->rawgrade = NULL;
eafb9d9e 349 glossary_grade_item_update($glossary, $grade);
350
351 } else {
352 glossary_grade_item_update($glossary);
63dd5fb2 353 }
a02c77dc 354
e6d45048 355 } else {
dd232d01 356 $sql = "SELECT g.*, cm.idnumber as cmidnumber
e8586b5f 357 FROM {$CFG->prefix}glossary g, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
358 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
e6d45048 359 if ($rs = get_recordset_sql($sql)) {
03cedd62 360 while ($glossary = rs_fetch_next_record($rs)) {
03cedd62 361 if ($glossary->assessed) {
362 glossary_update_grades($glossary, 0, false);
eafb9d9e 363 } else {
364 glossary_grade_item_update($glossary);
37d543b5 365 }
63dd5fb2 366 }
e6d45048 367 rs_close($rs);
368 }
369 }
370}
371
d31bae70 372/**
612607bd 373 * Create/update grade item for given glossary
d31bae70 374 *
dd232d01 375 * @param object $glossary object with extra cmidnumber
0b5a80a1 376 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 377 * @return int, 0 if ok, error code otherwise
d31bae70 378 */
0b5a80a1 379function glossary_grade_item_update($glossary, $grades=NULL) {
612607bd 380 global $CFG;
381 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
382 require_once($CFG->libdir.'/gradelib.php');
63dd5fb2 383 }
3f32807d 384 if(!empty($glossary->cmidnumber)){
385 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
386 }else{
387 // MDL-14303
388 $cm = get_coursemodule_from_instance('glossary', $glossary->id);
389 $params = array('itemname'=>$glossary->name, 'idnumber'=>$cm->id);
390 }
e6d45048 391
5980d52f 392 if (!$glossary->assessed or $glossary->scale == 0) {
612607bd 393 $params['gradetype'] = GRADE_TYPE_NONE;
34601114 394
395 } else if ($glossary->scale > 0) {
e8586b5f 396 $params['gradetype'] = GRADE_TYPE_VALUE;
e6d45048 397 $params['grademax'] = $glossary->scale;
398 $params['grademin'] = 0;
399
400 } else if ($glossary->scale < 0) {
e8586b5f 401 $params['gradetype'] = GRADE_TYPE_SCALE;
e6d45048 402 $params['scaleid'] = -$glossary->scale;
e6d45048 403 }
404
0b5a80a1 405 if ($grades === 'reset') {
406 $params['reset'] = true;
407 $grades = NULL;
408 }
409
410 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
e6d45048 411}
412
d31bae70 413/**
414 * Delete grade item for given glossary
415 *
dd232d01 416 * @param object $glossary object
d31bae70 417 */
e6d45048 418function glossary_grade_item_delete($glossary) {
612607bd 419 global $CFG;
420 require_once($CFG->libdir.'/gradelib.php');
421
b67ec72f 422 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
07842023 423}
424
05855091 425function glossary_get_participants($glossaryid) {
426//Returns the users with data in one glossary
427//(users with records in glossary_entries, students)
428
429 global $CFG;
430
431 //Get students
95e72c12 432 $students = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 433 FROM {$CFG->prefix}user u,
434 {$CFG->prefix}glossary_entries g
435 WHERE g.glossaryid = '$glossaryid' and
436 u.id = g.userid");
437
438 //Return students array (it contains an array of unique users)
439 return ($students);
440}
07842023 441
0f1a97c2 442function glossary_scale_used ($glossaryid,$scaleid) {
443//This function returns if a scale is being used by one glossary
a02c77dc 444
0f1a97c2 445 $return = false;
446
447 $rec = get_record("glossary","id","$glossaryid","scale","-$scaleid");
448
2127fedd 449 if (!empty($rec) && !empty($scaleid)) {
a02c77dc 450 $return = true;
451 }
452
0f1a97c2 453 return $return;
454}
455
85c9ebb9 456/**
457 * Checks if scale is being used by any instance of glossary
458 *
459 * This is used to find out if scale used anywhere
460 * @param $scaleid int
461 * @return boolean True if the scale is used by any glossary
462 */
463function glossary_scale_used_anywhere($scaleid) {
464 if ($scaleid and record_exists('glossary', 'scale', -$scaleid)) {
465 return true;
466 } else {
467 return false;
468 }
469}
470
07842023 471//////////////////////////////////////////////////////////////////////////////////////
472/// Any other glossary functions go here. Each of them must have a name that
473/// starts with glossary_
474
a359c29b 475//This function return an array of valid glossary_formats records
476//Everytime it's called, every existing format is checked, new formats
477//are included if detected and old formats are deleted and any glossary
478//using an invalid format is updated to the default (dictionary).
479function glossary_get_available_formats() {
480
481 global $CFG;
482
483 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
77495793 484 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
485 $pluginformats = array();
a359c29b 486 foreach ($formats as $format) {
487 //If the format file exists
488 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
489 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
490 //If the function exists
491 if (function_exists('glossary_show_entry_'.$format)) {
77495793 492 //Acummulate it as a valid format
493 $pluginformats[] = $format;
a359c29b 494 //If the format doesn't exist in the table
495 if (!$rec = get_record('glossary_formats','name',$format)) {
496 //Insert the record in glossary_formats
e6d45048 497 $gf = new object();
a359c29b 498 $gf->name = $format;
499 $gf->popupformatname = $format;
500 $gf->visible = 1;
501 insert_record("glossary_formats",$gf);
502 }
503 }
504 }
505 }
506
507 //Delete non_existent formats from glossary_formats table
508 $formats = get_records("glossary_formats");
509 foreach ($formats as $format) {
510 $todelete = false;
77495793 511 //If the format in DB isn't a valid previously detected format then delete the record
512 if (!in_array($format->name,$pluginformats)) {
a359c29b 513 $todelete = true;
a359c29b 514 }
515
516 if ($todelete) {
517 //Delete the format
518 delete_records('glossary_formats','name',$format->name);
519 //Reasign existing glossaries to default (dictionary) format
520 if ($glossaries = get_records('glossary','displayformat',$format->name)) {
521 foreach($glossaries as $glossary) {
522 set_field('glossary','displayformat','dictionary','id',$glossary->id);
523 }
524 }
525 }
526 }
527
528 //Now everything is ready in glossary_formats table
529 $formats = get_records("glossary_formats");
530
531 return $formats;
532}
533
1ac87c73 534function glossary_debug($debug,$text,$br=1) {
535 if ( $debug ) {
41905731 536 echo '<font color="red">' . $text . '</font>';
1ac87c73 537 if ( $br ) {
a9ef4a63 538 echo '<br />';
1ac87c73 539 }
540 }
07842023 541}
542
ea14e783 543function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
07842023 544 global $CFG;
ea14e783 545 if ($pivot) {
546 $pivot .= ",";
547 }
07842023 548
ea14e783 549 return get_records_sql("SELECT $pivot id,userid,concept,definition,format
07842023 550 FROM {$CFG->prefix}glossary_entries
551 WHERE glossaryid = '$glossaryid'
552 AND id IN ($entrylist)");
553}
359f2758 554
555function glossary_get_entries_search($concept, $courseid) {
6c351232 556
359f2758 557 global $CFG;
558
a02c77dc 559 //Check if the user is an admin
6c351232 560 $bypassadmin = 1; //This means NO (by default)
957f6fc9 561 if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM))) {
6c351232 562 $bypassadmin = 0; //This means YES
a02c77dc 563 }
6c351232 564
a02c77dc 565 //Check if the user is a teacher
6c351232 566 $bypassteacher = 1; //This means NO (by default)
81e956b9 567 if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
6c351232 568 $bypassteacher = 0; //This means YES
a02c77dc 569 }
6c351232 570
95d56829 571 $conceptlower = moodle_strtolower(trim($concept));
359f2758 572
a736e963 573 return get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
a02c77dc 574 FROM {$CFG->prefix}glossary_entries e,
6c351232 575 {$CFG->prefix}glossary g,
576 {$CFG->prefix}course_modules cm,
577 {$CFG->prefix}modules m
578 WHERE m.name = 'glossary' AND
579 cm.module = m.id AND
580 (cm.visible = 1 OR cm.visible = $bypassadmin OR
581 (cm.course = '$courseid' AND cm.visible = $bypassteacher)) AND
582 g.id = cm.instance AND
583 e.glossaryid = g.id AND
95d56829 584 ( (e.casesensitive != 0 AND LOWER(concept) = '$conceptlower') OR
6c351232 585 (e.casesensitive = 0 and concept = '$concept')) AND
586 (g.course = '$courseid' OR g.globalglossary = 1) AND
587 e.usedynalink != 0 AND
588 g.usedynalink != 0");
359f2758 589}
590
ea14e783 591function glossary_get_entries_sorted($glossary, $where="", $orderby="", $pivot = "") {
c76e673a 592global $CFG;
593 if ($where) {
594 $where = " and $where";
595 }
596 if ($orderby) {
597 $orderby = " ORDER BY $orderby";
598 }
ea14e783 599 if ($pivot) {
600 $pivot .= ",";
601 }
602 return get_records_sql("SELECT $pivot *
a02c77dc 603 FROM {$CFG->prefix}glossary_entries
c76e673a 604 WHERE (glossaryid = $glossary->id or sourceglossaryid = $glossary->id) $where $orderby");
605}
606
1ac87c73 607function glossary_get_entries_by_category($glossary, $hook, $where="", $orderby="", $pivot = "") {
c76e673a 608global $CFG;
609 if ($where) {
610 $where = " and $where";
611 }
612 if ($orderby) {
613 $orderby = " ORDER BY $orderby";
614 }
ea14e783 615 if ($pivot) {
616 $pivot .= ",";
617 }
618 return get_records_sql("SELECT $pivot ge.*
c76e673a 619 FROM {$CFG->prefix}glossary_entries ge, {$CFG->prefix}glossary_entries_categories c
63dd5fb2 620 WHERE (ge.id = c.entryidid and c.categoryid = $hook) and
c76e673a 621 (ge.glossaryid = $glossary->id or ge.sourceglossaryid = $glossary->id) $where $orderby");
622}
07842023 623
b8340d19 624function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $ratings = NULL, $printview = false) {
625 global $USER, $CFG;
37d543b5 626 $return = false;
b1918034 627 if ( $displayformat < 0 ) {
628 $displayformat = $glossary->displayformat;
629 }
b620a995 630 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
a359c29b 631 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
ae06e00e 632 if ($printview) {
633 $functionname = 'glossary_print_entry_'.$displayformat;
634 } else {
635 $functionname = 'glossary_show_entry_'.$displayformat;
636 }
a359c29b 637
638 if (file_exists($formatfile)) {
639 include_once($formatfile);
640 if (function_exists($functionname)) {
641 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons,$ratings);
ae06e00e 642 } else if ($printview) {
643 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
644 $return = glossary_print_entry_default($entry);
c76e673a 645 }
767a31c3 646 }
07842023 647 }
a359c29b 648 return $return;
07842023 649}
b8340d19 650
ae06e00e 651 //Default (old) print format used if custom function doesn't exist in format
652function glossary_print_entry_default ($entry) {
097d705e 653 echo '<h3>'. strip_tags($entry->concept) . ': </h3>';
7d8a3cb0 654
655 $definition = $entry->definition;
656
657 // always detect and strip TRUSTTEXT marker before processing and add+strip it afterwards!
658 if (trusttext_present($definition)) {
659 $ttpresent = true;
660 $definition = trusttext_strip($definition);
661 } else {
662 $ttpresent = false;
663 }
664
665 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
666
667 // reconstruct the TRUSTTEXT properly after processing
668 if ($ttpresent) {
669 $definition = trusttext_mark($definition);
670 } else {
671 $definition = trusttext_strip($definition); //make 100% sure TRUSTTEXT marker was not created
672 }
673
674 $options = new object();
ae06e00e 675 $options->para = false;
7d8a3cb0 676 $options->trusttext = true;
677 $definition = format_text($definition, $entry->format, $options);
ae06e00e 678 echo ($definition);
679 echo '<br /><br />';
680}
a359c29b 681
120a18f0 682/**
683 * Print glossary concept/term as a heading &lt;h3>
684 */
81bdc9e9 685function glossary_print_entry_concept($entry) {
7d8a3cb0 686 $options = new object();
d34b9c5f 687 $options->para = false;
2d1e0971 688 $text = format_text(print_heading($entry->concept, '', 3, 'nolink', true), FORMAT_MOODLE, $options);
ff8352de 689 if (!empty($entry->highlight)) {
690 $text = highlight($entry->highlight, $text);
691 }
692 echo $text;
81bdc9e9 693}
1d9ddaaf 694
695function glossary_print_entry_definition($entry) {
701fff21 696
f287e69c 697 $definition = $entry->definition;
698
7d8a3cb0 699 // always detect and strip TRUSTTEXT marker before processing and add+strip it afterwards!
700 if (trusttext_present($definition)) {
701 $ttpresent = true;
702 $definition = trusttext_strip($definition);
703 } else {
704 $ttpresent = false;
705 }
706
0f9a668f 707 $links = array();
701fff21 708 $tags = array();
b5937aac 709 $urls = array();
710 $addrs = array();
f287e69c 711
701fff21 712 //Calculate all the strings to be no-linked
713 //First, the concept
b8340d19 714 $term = preg_quote(trim($entry->concept),'/');
701fff21 715 $pat = '/('.$term.')/is';
716 $doNolinks[] = $pat;
717 //Now the aliases
b8340d19 718 if ( $aliases = get_records('glossary_alias','entryid',$entry->id) ) {
701fff21 719 foreach ($aliases as $alias) {
b8340d19 720 $term = preg_quote(trim($alias->alias),'/');
701fff21 721 $pat = '/('.$term.')/is';
722 $doNolinks[] = $pat;
723 }
f287e69c 724 }
725
a02c77dc 726
0f9a668f 727 //Extract <a>..><a> tags from definition
728 preg_match_all('/<a[^>]+?>(.*?)<\/a>/is',$definition,$list_of_a);
a02c77dc 729
0f9a668f 730 //Save them into links array to use them later
731 foreach (array_unique($list_of_a[0]) as $key=>$value) {
732 $links['<#'.$key.'#>'] = $value;
733 }
734 //Take off every link from definition
735 if ( $links ) {
736 $definition = str_replace($links,array_keys($links),$definition);
737 }
738
739
701fff21 740 //Extract all tags from definition
741 preg_match_all('/(<.*?>)/is',$definition,$list_of_tags);
f287e69c 742
701fff21 743 //Save them into tags array to use them later
744 foreach (array_unique($list_of_tags[0]) as $key=>$value) {
745 $tags['<@'.$key.'@>'] = $value;
f287e69c 746 }
701fff21 747 //Take off every tag from definition
748 if ( $tags ) {
749 $definition = str_replace($tags,array_keys($tags),$definition);
f287e69c 750 }
7275671a 751
0f9a668f 752
7275671a 753 //Extract all URLS with protocol (http://domain.com) from definition
754 preg_match_all('/([[:space:]]|^|\(|\[)([[:alnum:]]+):\/\/([^[:space:]]*)([[:alnum:]#?\/&=])/is',$definition,$list_of_urls);
755
756 //Save them into urls array to use them later
757 foreach (array_unique($list_of_urls[0]) as $key=>$value) {
758 $urls['<*'.$key.'*>'] = $value;
759 }
7275671a 760 //Take off every url from definition
761 if ( $urls ) {
762 $definition = str_replace($urls,array_keys($urls),$definition);
763 }
764
0f9a668f 765
7275671a 766 //Extract all WEB ADDRESSES (www.domain.com) from definition
767 preg_match_all('/([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?\/&=])/is',$definition,$list_of_addresses);
768
769 //Save them into addrs array to use them later
770 foreach (array_unique($list_of_addresses[0]) as $key=>$value) {
771 $addrs['<+'.$key.'+>'] = $value;
772 }
7275671a 773 //Take off every addr from definition
774 if ( $addrs ) {
775 $definition = str_replace($addrs,array_keys($addrs),$definition);
776 }
777
0f9a668f 778
701fff21 779 //Put doNolinks (concept + aliases) enclosed by <nolink> tag
e19a635c 780 $definition= preg_replace($doNolinks,'<span class="nolink">$1</span>',$definition);
781
7275671a 782 //Restore addrs
783 if ( $addrs ) {
784 $definition = str_replace(array_keys($addrs),$addrs,$definition);
785 }
786
787 //Restore urls
788 if ( $urls ) {
789 $definition = str_replace(array_keys($urls),$urls,$definition);
790 }
791
701fff21 792 //Restore tags
793 if ( $tags ) {
794 $definition = str_replace(array_keys($tags),$tags,$definition);
584dcac9 795 }
ff8352de 796
0f9a668f 797 //Restore links
798 if ( $links ) {
799 $definition = str_replace(array_keys($links),$links,$definition);
800 }
801
7d8a3cb0 802 $options = new object();
3eb2f7ec 803 $options->para = false;
7d8a3cb0 804 $options->trusttext = true;
805
806 // reconstruct the TRUSTTEXT properly after processing
807 if ($ttpresent) {
808 $definition = trusttext_mark($definition);
809 } else {
810 $definition = trusttext_strip($definition); //make 100% sure TRUSTTEXT marker was not created
811 }
0f9a668f 812
7d8a3cb0 813 $text = format_text($definition, $entry->format, $options);
ff8352de 814 if (!empty($entry->highlight)) {
815 $text = highlight($entry->highlight, $text);
816 }
359f2758 817 if (isset($entry->footer)) { // Unparsed footer info
818 $text .= $entry->footer;
819 }
ff8352de 820 echo $text;
1d9ddaaf 821}
822
b8340d19 823function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
81bdc9e9 824 $return = '';
b8340d19 825 if ( $aliases = get_records('glossary_alias','entryid',$entry->id) ) {
81bdc9e9 826 foreach ($aliases as $alias) {
33cc423e 827 if (trim($alias->alias)) {
81bdc9e9 828 if ($return == '') {
829 $return = '<select style="font-size:8pt">';
830 }
831 $return .= "<option>$alias->alias</option>";
832 }
833 }
834 if ($return != '') {
835 $return .= '</select>';
81bdc9e9 836 }
a02c77dc 837 }
1ac87c73 838 if ($type == 'print') {
81bdc9e9 839 echo $return;
840 } else {
841 return $return;
842 }
843}
844
b8340d19 845function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
846 global $USER, $CFG;
a02c77dc 847
dabfd0ed 848 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
81bdc9e9 849
36ce6ea2 850 $output = false; //To decide if we must really return text in "return". Activate when needed only!
81bdc9e9 851 $importedentry = ($entry->sourceglossaryid == $glossary->id);
81bdc9e9 852 $ismainglossary = $glossary->mainglossary;
b8340d19 853
854
9362b9b6 855 $return = '<span class="commands">';
097d705e 856 // Differentiate links for each entry.
2d1e0971 857 $altsuffix = ': '.strip_tags(format_text($entry->concept));
858
81bdc9e9 859 if (!$entry->approved) {
36ce6ea2 860 $output = true;
b8340d19 861 $return .= get_string('entryishidden','glossary');
81bdc9e9 862 }
66d7ae88 863 $return .= glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook,'html');
a02c77dc 864
ea16f9b2 865 if (has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
dabfd0ed 866 $output = true;
097d705e 867 $return .= ' <a title="' . get_string('addcomment','glossary') . '" href="comment.php?action=add&amp;eid='.$entry->id.'"><img src="comment.gif" class="iconsmall" alt="'.get_string('addcomment','glossary').$altsuffix.'" /></a>';
81bdc9e9 868 }
869
b8340d19 870
6cb34d44 871 if (has_capability('mod/glossary:manageentries', $context) or (!empty($USER->id) and has_capability('mod/glossary:write', $context) and $entry->userid == $USER->id)) {
81bdc9e9 872 // only teachers can export entries so check it out
0468976c 873 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
dabfd0ed 874 $mainglossary = get_record('glossary','mainglossary',1,'course',$course->id);
81bdc9e9 875 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
36ce6ea2 876 $output = true;
097d705e 877 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$cm->id.'&amp;entry='.$entry->id.'&amp;mode='.$mode.'&amp;hook='.$hook.'"><img src="export.gif" class="iconsmall" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
81bdc9e9 878 }
879 }
880
881 if ( $entry->sourceglossaryid ) {
882 $icon = "minus.gif"; // graphical metaphor (minus) for deleting an imported entry
883 } else {
096b5432 884 $icon = "$CFG->pixpath/t/delete.gif";
81bdc9e9 885 }
886
ff1e2621 887 //Decide if an entry is editable:
888 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
889 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
516c7276 890 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
6cb34d44 891 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
36ce6ea2 892 $output = true;
839f2456 893 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=$hook\"><img src=\"";
81bdc9e9 894 $return .= $icon;
097d705e 895 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
a02c77dc 896
097d705e 897 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?id=$cm->id&amp;e=$entry->id&amp;mode=$mode&amp;hook=$hook\"><img src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
81bdc9e9 898 } elseif ( $importedentry ) {
41905731 899 $return .= " <font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
81bdc9e9 900 }
901 }
902 $return .= "&nbsp;&nbsp;"; // just to make up a little the output in Mozilla ;)
36ce6ea2 903
9362b9b6 904 $return .= '</span>';
a02c77dc 905
36ce6ea2 906 //If we haven't calculated any REAL thing, delete result ($return)
907 if (!$output) {
908 $return = '';
909 }
910 //Print or get
1ac87c73 911 if ($type == 'print') {
81bdc9e9 912 echo $return;
913 } else {
914 return $return;
a0d1e2bb 915 }
916}
917
918function glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook, $type = 'print') {
919 $return = '';
920
b8340d19 921 $count = count_records('glossary_comments','entryid',$entry->id);
a0d1e2bb 922 if ($count) {
b8340d19 923 $return = '';
839f2456 924 $return .= "<a href=\"comments.php?id=$cm->id&amp;eid=$entry->id\">$count ";
a0d1e2bb 925 if ($count == 1) {
b8340d19 926 $return .= get_string('comment', 'glossary');
a0d1e2bb 927 } else {
b8340d19 928 $return .= get_string('comments', 'glossary');
a0d1e2bb 929 }
b8340d19 930 $return .= '</a>';
a0d1e2bb 931 }
932
933 if ($type == 'print') {
934 echo $return;
935 } else {
936 return $return;
81bdc9e9 937 }
938}
939
26983d03 940function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook,$printicons,$ratings,$aliases=true) {
81bdc9e9 941
26983d03 942 if ($aliases) {
9362b9b6 943 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
26983d03 944 }
9362b9b6 945 $icons = '';
946 $return = '';
1ac87c73 947 if ( $printicons ) {
9362b9b6 948 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1ac87c73 949 }
36ce6ea2 950 if ($aliases || $icons || $ratings) {
9362b9b6 951 echo '<table>';
a359c29b 952 if ( $aliases ) {
9362b9b6 953 echo '<tr valign="top"><td class="aliases">' .
954 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
a359c29b 955 }
956 if ($icons) {
9362b9b6 957 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
a359c29b 958 }
959 if ($ratings) {
9362b9b6 960 echo '<tr valign="top"><td class="ratings">';
a359c29b 961 $return = glossary_print_entry_ratings($course, $entry, $ratings);
962 echo '</td></tr>';
963 }
964 echo '</table>';
81bdc9e9 965 }
a359c29b 966 return $return;
81bdc9e9 967}
968
77495793 969function glossary_print_entry_attachment($entry,$format=NULL,$align="right",$insidetable=true) {
1d9ddaaf 970/// valid format values: html : Return the HTML link for the attachment as an icon
971/// text : Return the HTML link for tha attachment as text
972/// blank : Print the output to the screen
973 if ($entry->attachment) {
894ff63f 974 $glossary = get_record("glossary","id",$entry->glossaryid);
1d9ddaaf 975 $entry->course = $glossary->course; //used inside print_attachment
77495793 976 if ($insidetable) {
41905731 977 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
77495793 978 }
1d9ddaaf 979 echo glossary_print_attachments($entry,$format,$align);
77495793 980 if ($insidetable) {
981 echo "</td></tr></table>\n";
982 }
1d9ddaaf 983 }
984}
985
77495793 986function glossary_print_entry_approval($cm, $entry, $mode,$align="right",$insidetable=true) {
cff611fc 987 global $CFG;
988
1ac87c73 989 if ( $mode == 'approval' and !$entry->approved ) {
77495793 990 if ($insidetable) {
a8466100 991 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
77495793 992 }
e32d5506 993 echo '<a title="'.get_string('approve','glossary').'" href="approve.php?id='.$cm->id.'&amp;eid='.$entry->id.'&amp;mode='.$mode.'"><img align="'.$align.'" src="'.$CFG->pixpath.'/i/approve.gif" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
77495793 994 if ($insidetable) {
a8466100 995 echo '</td></tr></table>';
77495793 996 }
1d9ddaaf 997 }
998}
07842023 999
c80828fe 1000function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
a02c77dc 1001// It returns all entries from all glossaries that matches the specified criteria
c80828fe 1002// within a given $course. It performs an $extended search if necessary.
1003// It restrict the search to only one $glossary if the $glossary parameter is set.
07842023 1004
1005 global $CFG;
c80828fe 1006 if ( !$glossary ) {
1007 if ( $glossaries = get_records("glossary", "course", $course->id) ) {
1008 $glos = "";
1009 foreach ( $glossaries as $glossary ) {
1010 $glos .= "$glossary->id,";
1011 }
9cae3799 1012 $glos = substr($glos,0,-1);
c80828fe 1013 }
1014 } else {
1015 $glos = $glossary->id;
1016 }
a02c77dc 1017
81e956b9 1018 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $glossary->course))) {
07842023 1019 $glossarymodule = get_record("modules", "name", "glossary");
6a22879b 1020 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
07842023 1021 $onlyvisibletable = ", {$CFG->prefix}course_modules cm";
1022 } else {
1023
1024 $onlyvisible = "";
1025 $onlyvisibletable = "";
1026 }
1027
63dd5fb2 1028 /// Some differences in syntax for entrygreSQL
a4bad45c 1029 switch ($CFG->dbfamily) {
1030 case 'postgres':
07842023 1031 $LIKE = "ILIKE"; // case-insensitive
1032 $NOTLIKE = "NOT ILIKE"; // case-insensitive
1033 $REGEXP = "~*";
1034 $NOTREGEXP = "!~*";
a5e48d96 1035 break;
1036 case 'mysql':
1037 default:
07842023 1038 $LIKE = "LIKE";
1039 $NOTLIKE = "NOT LIKE";
1040 $REGEXP = "REGEXP";
1041 $NOTREGEXP = "NOT REGEXP";
a5e48d96 1042 break;
a02c77dc 1043 }
07842023 1044
1045 $conceptsearch = "";
1046 $definitionsearch = "";
1047
1048
1049 foreach ($searchterms as $searchterm) {
07842023 1050 if ($conceptsearch) {
1051 $conceptsearch.= " OR ";
1052 }
1053 if ($definitionsearch) {
1054 $definitionsearch.= " OR ";
1055 }
1056
6f4bdb9c 1057 /// Under Oracle and MSSQL, trim the + and - operators and perform
1058 /// simpler LIKE search
a4bad45c 1059 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
6f4bdb9c 1060 $searchterm = trim($searchterm, '+-');
1061 }
1062
07842023 1063 if (substr($searchterm,0,1) == "+") {
1064 $searchterm = substr($searchterm,1);
1065 $conceptsearch.= " e.concept $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1066 $definitionsearch .= " e.definition $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1067 } else if (substr($searchterm,0,1) == "-") {
1068 $searchterm = substr($searchterm,1);
1069 $conceptsearch .= " e.concept $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1070 $definitionsearch .= " e.definition $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1071 } else {
1072 $conceptsearch .= " e.concept $LIKE '%$searchterm%' ";
1073 $definitionsearch .= " e.definition $LIKE '%$searchterm%' ";
1074 }
1075 }
1076
4d272b48 1077 $definitionsearch = !empty($extended) ? "OR $definitionsearch" : '';
07842023 1078
1079 $selectsql = "{$CFG->prefix}glossary_entries e,
1080 {$CFG->prefix}glossary g $onlyvisibletable
4d272b48 1081 WHERE ($conceptsearch $definitionsearch)
ad58adac 1082 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
c80828fe 1083 AND g.id IN ($glos) AND e.approved != 0";
07842023 1084
a02c77dc 1085 return get_records_sql("SELECT e.*
4d4c38f3 1086 FROM $selectsql ORDER BY e.concept ASC");
07842023 1087}
1088
c80828fe 1089function glossary_search_entries($searchterms, $glossary, $extended) {
1090 $course = get_record("course","id",$glossary->course);
1091 return glossary_search($course,$searchterms,$extended,$glossary);
1092}
1093
e179048e 1094function glossary_file_area_name($entry) {
e179048e 1095 global $CFG;
e29ad7eb 1096// Creates a directory file name, suitable for make_upload_directory()
e179048e 1097
a02c77dc 1098 // I'm doing this workaround for make it works for delete_instance also
e29ad7eb 1099 // (when called from delete_instance, glossary is already deleted so
1100 // getting the course from mdl_glossary does not work)
1101 $module = get_record("modules","name","glossary");
1102 $cm = get_record("course_modules","module",$module->id,"instance",$entry->glossaryid);
1103 return "$cm->course/$CFG->moddata/glossary/$entry->glossaryid/$entry->id";
e179048e 1104}
1105
1106function glossary_file_area($entry) {
1107 return make_upload_directory( glossary_file_area_name($entry) );
1108}
1109
e29ad7eb 1110function glossary_main_file_area($glossary) {
1111 $modarea = glossary_mod_file_area($glossary);
1112 return "$modarea/$glossary->id";
1113}
1114
1115function glossary_mod_file_area($glossary) {
1116 global $CFG;
a02c77dc 1117
e29ad7eb 1118 return make_upload_directory( "$glossary->course/$CFG->moddata/glossary" );
1119}
1120
e179048e 1121function glossary_delete_old_attachments($entry, $exception="") {
1122// Deletes all the user files in the attachments area for a entry
1123// EXCEPT for any file named $exception
1124
1125 if ($basedir = glossary_file_area($entry)) {
1126 if ($files = get_directory_list($basedir)) {
1127 foreach ($files as $file) {
1128 if ($file != $exception) {
1129 unlink("$basedir/$file");
1130// notify("Existing file '$file' has been deleted!");
1131 }
1132 }
1133 }
1134 if (!$exception) { // Delete directory as well, if empty
1135 rmdir("$basedir");
1136 }
1137 }
1138}
072f7533 1139function glossary_delete_attachments($glossary) {
e29ad7eb 1140// Deletes all the user files in the attachments area for the glossary
1141 if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
1142 $deleted = 0;
1143 foreach ($entries as $entry) {
1144 if ( $entry->attachment ) {
1145 if ($basedir = glossary_file_area($entry)) {
1146 if ($files = get_directory_list($basedir)) {
1147 foreach ($files as $file) {
1148 unlink("$basedir/$file");
1149 }
1150 }
1151 rmdir("$basedir");
1152 $deleted++;
1153 }
a02c77dc 1154 }
e29ad7eb 1155 }
1156 if ( $deleted ) {
1157 $attachmentdir = glossary_main_file_area($glossary);
1158 $glossarydir = glossary_mod_file_area($glossary);
a02c77dc 1159
e29ad7eb 1160 rmdir("$attachmentdir");
1161 if (!$files = get_directory_list($glossarydir) ) {
1162 rmdir( "$glossarydir" );
1163 }
a02c77dc 1164 }
e29ad7eb 1165 }
1166}
e179048e 1167
1168function glossary_copy_attachments($entry, $newentry) {
1169/// Given a entry object that is being copied to glossaryid,
1170/// this function checks that entry
1171/// for attachments, and if any are found, these are
1172/// copied to the new glossary directory.
1173
1174 global $CFG;
1175
1176 $return = true;
1177
1178 if ($entries = get_records_select("glossary_entries", "id = '$entry->id' AND attachment <> ''")) {
1179 foreach ($entries as $curentry) {
e6d45048 1180 $oldentry = new object();
e179048e 1181 $oldentry->id = $entry->id;
1182 $oldentry->course = $entry->course;
1183 $oldentry->glossaryid = $curentry->glossaryid;
1184 $oldentrydir = "$CFG->dataroot/".glossary_file_area_name($oldentry);
1185 if (is_dir($oldentrydir)) {
1186
1187 $newentrydir = glossary_file_area($newentry);
1188 if (! copy("$oldentrydir/$newentry->attachment", "$newentrydir/$newentry->attachment")) {
1189 $return = false;
1190 }
1191 }
1192 }
1193 }
1194 return $return;
1195}
1196
1197function glossary_move_attachments($entry, $glossaryid) {
1198/// Given a entry object that is being moved to glossaryid,
1199/// this function checks that entry
1200/// for attachments, and if any are found, these are
1201/// moved to the new glossary directory.
1202
1203 global $CFG;
1204
18b8fbfa 1205 require_once($CFG->dirroot.'/lib/uploadlib.php');
1206
e179048e 1207 $return = true;
1208
1209 if ($entries = get_records_select("glossary_entries", "glossaryid = '$entry->id' AND attachment <> ''")) {
1210 foreach ($entries as $entry) {
e6d45048 1211 $oldentry = new object();
e179048e 1212 $oldentry->course = $entry->course;
1213 $oldentry->glossaryid = $entry->glossaryid;
1214 $oldentrydir = "$CFG->dataroot/".glossary_file_area_name($oldentry);
1215 if (is_dir($oldentrydir)) {
1216 $newentry = $oldentry;
1217 $newentry->glossaryid = $glossaryid;
1218 $newentrydir = "$CFG->dataroot/".glossary_file_area_name($newentry);
18b8fbfa 1219 $files = get_directory_list($oldentrydir); // get it before we rename it.
e179048e 1220 if (! @rename($oldentrydir, $newentrydir)) {
1221 $return = false;
1222 }
18b8fbfa 1223 foreach ($files as $file) {
1224 // this is not tested as I can't find anywhere that calls this function, grepping the source.
a02c77dc 1225 clam_change_log($oldentrydir.'/'.$file,$newentrydir.'/'.$file);
18b8fbfa 1226 }
e179048e 1227 }
1228 }
1229 }
1230 return $return;
1231}
1232
de53b9ac 1233function glossary_print_attachments($entry, $return=NULL, $align="left") {
e179048e 1234// if return=html, then return a html string.
1235// if return=text, then return a text-only string.
1236// otherwise, print HTML for non-images, and return image HTML
b764feaa 1237// if attachment is an image, $align set its aligment.
e179048e 1238 global $CFG;
a02c77dc 1239
b764feaa 1240 $newentry = $entry;
1241 if ( $newentry->sourceglossaryid ) {
1242 $newentry->glossaryid = $newentry->sourceglossaryid;
1243 }
e179048e 1244
b764feaa 1245 $filearea = glossary_file_area_name($newentry);
e179048e 1246
1247 $imagereturn = "";
1248 $output = "";
1249
b764feaa 1250 if ($basedir = glossary_file_area($newentry)) {
e179048e 1251 if ($files = get_directory_list($basedir)) {
1252 $strattachment = get_string("attachment", "glossary");
e179048e 1253 foreach ($files as $file) {
1254 $icon = mimeinfo("icon", $file);
1255 if ($CFG->slasharguments) {
d96624ca 1256 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
e179048e 1257 } else {
d96624ca 1258 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
e179048e 1259 }
0d905d9f 1260 $image = "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"\" />";
e179048e 1261
1262 if ($return == "html") {
d96624ca 1263 $output .= "<a href=\"$ffurl\">$image</a> ";
1264 $output .= "<a href=\"$ffurl\">$file</a><br />";
24fb69e1 1265
e179048e 1266 } else if ($return == "text") {
d96624ca 1267 $output .= "$strattachment $file:\n$ffurl\n";
e179048e 1268
1269 } else {
1270 if ($icon == "image.gif") { // Image attachments don't get printed as links
d96624ca 1271 $imagereturn .= "<img src=\"$ffurl\" align=\"$align\" alt=\"\" />";
e179048e 1272 } else {
24fb69e1 1273 echo "<a href=\"$ffurl\">$image</a> ";
d96624ca 1274 echo "<a href=\"$ffurl\">$file</a><br />";
e179048e 1275 }
1276 }
1277 }
1278 }
1279 }
1280
1281 if ($return) {
1282 return $output;
1283 }
1284
1285 return $imagereturn;
1286}
1287
ad58adac 1288function glossary_print_tabbed_table_end() {
9ca8cc08 1289 echo "</div></div>";
06d94a52 1290}
1291
1ac87c73 1292function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1293 if ($glossary->showalphabet) {
7a3ec1af 1294 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
677038ee 1295 }
1ac87c73 1296 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1297
c4a35419 1298 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
c76e673a 1299
1ac87c73 1300 glossary_print_all_links($cm, $glossary, $mode, $hook);
894ff63f 1301
db87439a 1302 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
c76e673a 1303}
1304
1ac87c73 1305function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1306 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
748b1932 1307}
1308
1ac87c73 1309function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1310 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
748b1932 1311}
1312
1ac87c73 1313function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1314 if ( $mode != 'date' ) {
a359c29b 1315 if ($glossary->showalphabet) {
7a3ec1af 1316 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1317 }
c76e673a 1318
1ac87c73 1319 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1320
c4a35419 1321 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
c197e607 1322
1ac87c73 1323 glossary_print_all_links($cm, $glossary, $mode, $hook);
c197e607 1324 } else {
1ac87c73 1325 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1326 }
1327}
1328
1329function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1330 if ($glossary->showalphabet) {
7a3ec1af 1331 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1332 }
1ac87c73 1333
c4a35419 1334 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1ac87c73 1335 glossary_print_all_links($cm, $glossary, $mode, $hook);
7a3ec1af 1336 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
c76e673a 1337}
1338
1ac87c73 1339function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
a02c77dc 1340
dabfd0ed 1341 global $CFG;
a02c77dc 1342
dabfd0ed 1343 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3a26f0ea 1344
41905731 1345 echo '<table border="0" width="100%">';
c197e607 1346 echo '<tr>';
c76e673a 1347
5bd76d7f 1348 echo '<td align="center" style="width:20%">';
0468976c 1349 if (has_capability('mod/glossary:managecategories', $context)) {
c76e673a 1350 $options['id'] = $cm->id;
1ac87c73 1351 $options['mode'] = 'cat';
1352 $options['hook'] = $hook;
c76e673a 1353 echo print_single_button("editcategories.php", $options, get_string("editcategories","glossary"), "get");
1354 }
c197e607 1355 echo '</td>';
c76e673a 1356
5bd76d7f 1357 echo '<td align="center" style="width:60%">';
c197e607 1358 echo '<b>';
c76e673a 1359
1360 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1361 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
677038ee 1362
c76e673a 1363 $categories = get_records("glossary_categories", "glossaryid", $glossary->id, "name ASC");
c197e607 1364 $selected = '';
c76e673a 1365 if ( $categories ) {
1366 foreach ($categories as $currentcategory) {
1367 $url = $currentcategory->id;
1368 if ( $category ) {
1369 if ($currentcategory->id == $category->id) {
1370 $selected = $url;
1371 }
1372 }
ae06e00e 1373 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
c76e673a 1374 }
1375 }
1376 if ( !$selected ) {
1377 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1378 }
1379
1380 if ( $category ) {
5bd76d7f 1381 echo format_text($category->name, FORMAT_PLAIN);
c76e673a 1382 } else {
1ac87c73 1383 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
c76e673a 1384
1385 echo get_string("entrieswithoutcategory","glossary");
1386 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1387
1ac87c73 1388 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
c76e673a 1389
1390 echo get_string("allcategories","glossary");
1391 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1392
1393 }
1394 }
c197e607 1395 echo '</b></td>';
5bd76d7f 1396 echo '<td align="center" style="width:20%">';
c76e673a 1397
839f2456 1398 echo popup_form("$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=cat&amp;hook=", $menu, "catmenu", $selected, "",
c76e673a 1399 "", "", false);
677038ee 1400
c197e607 1401 echo '</td>';
1402 echo '</tr>';
c76e673a 1403
c197e607 1404 echo '</table>';
c76e673a 1405}
1406
1ac87c73 1407function glossary_print_all_links($cm, $glossary, $mode, $hook) {
a02c77dc 1408global $CFG;
a359c29b 1409 if ( $glossary->showall) {
c76e673a 1410 $strallentries = get_string("allentries", "glossary");
1ac87c73 1411 if ( $hook == 'ALL' ) {
c76e673a 1412 echo "<b>$strallentries</b>";
1413 } else {
1414 $strexplainall = strip_tags(get_string("explainall","glossary"));
839f2456 1415 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
c76e673a 1416 }
1417 }
1418}
1419
1ac87c73 1420function glossary_print_special_links($cm, $glossary, $mode, $hook) {
c76e673a 1421global $CFG;
a359c29b 1422 if ( $glossary->showspecial) {
c76e673a 1423 $strspecial = get_string("special", "glossary");
1ac87c73 1424 if ( $hook == 'SPECIAL' ) {
677038ee 1425 echo "<b>$strspecial</b> | ";
1426 } else {
1427 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
839f2456 1428 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
677038ee 1429 }
914cb260 1430 }
c76e673a 1431}
677038ee 1432
c4a35419 1433function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
c76e673a 1434global $CFG;
a359c29b 1435 if ( $glossary->showalphabet) {
c4274149 1436 $alphabet = explode(",", get_string("alphabet"));
677038ee 1437 $letters_by_line = 14;
1438 for ($i = 0; $i < count($alphabet); $i++) {
1ac87c73 1439 if ( $hook == $alphabet[$i] and $hook) {
677038ee 1440 echo "<b>$alphabet[$i]</b>";
1441 } else {
82015ed2 1442 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=".urlencode($alphabet[$i])."&amp;sortkey=$sortkey&amp;sortorder=$sortorder\">$alphabet[$i]</a>";
677038ee 1443 }
1444 if ((int) ($i % $letters_by_line) != 0 or $i == 0) {
c197e607 1445 echo ' | ';
677038ee 1446 } else {
a9ef4a63 1447 echo '<br />';
677038ee 1448 }
767a31c3 1449 }
677038ee 1450 }
c76e673a 1451}
1452
1ac87c73 1453function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
c76e673a 1454global $CFG;
677038ee 1455
c4a35419 1456 $asc = get_string("ascending","glossary");
1457 $desc = get_string("descending","glossary");
1458 $bopen = '<b>';
1459 $bclose = '</b>';
a02c77dc 1460
c197e607 1461 $neworder = '';
468c120a 1462 $currentorder = '';
1463 $currentsort = '';
677038ee 1464 if ( $sortorder ) {
c197e607 1465 if ( $sortorder == 'asc' ) {
468c120a 1466 $currentorder = $asc;
839f2456 1467 $neworder = '&amp;sortorder=desc';
468c120a 1468 $newordertitle = get_string('changeto', 'glossary', $desc);
677038ee 1469 } else {
468c120a 1470 $currentorder = $desc;
839f2456 1471 $neworder = '&amp;sortorder=asc';
468c120a 1472 $newordertitle = get_string('changeto', 'glossary', $asc);
677038ee 1473 }
468c120a 1474 $icon = " <img src=\"$sortorder.gif\" class=\"icon\" alt=\"$newordertitle\" />";
677038ee 1475 } else {
c4a35419 1476 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1477 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
677038ee 1478 $icon = "";
c4a35419 1479 $newordertitle = $asc;
677038ee 1480 } else {
c4a35419 1481 $newordertitle = $desc;
839f2456 1482 $neworder = '&amp;sortorder=desc';
468c120a 1483 $icon = ' <img src="asc.gif" class="icon" alt="'.$newordertitle.'" />';
677038ee 1484 }
1485 }
c4a35419 1486 $ficon = '';
1487 $fneworder = '';
1488 $fbtag = '';
1489 $fendbtag = '';
1490
1491 $sicon = '';
1492 $sneworder = '';
ae078733 1493
1494 $sbtag = '';
1495 $fbtag = '';
1496 $fendbtag = '';
1497 $sendbtag = '';
1498
c4a35419 1499 $sendbtag = '';
1500
1501 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1502 $ficon = $icon;
1503 $fneworder = $neworder;
1504 $fordertitle = $newordertitle;
1505 $sordertitle = $asc;
1506 $fbtag = $bopen;
1507 $fendbtag = $bclose;
1508 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1509 $sicon = $icon;
1510 $sneworder = $neworder;
1511 $fordertitle = $asc;
1512 $sordertitle = $newordertitle;
1513 $sbtag = $bopen;
1514 $sendbtag = $bclose;
677038ee 1515 } else {
c4a35419 1516 $fordertitle = $asc;
1517 $sordertitle = $asc;
677038ee 1518 }
c4a35419 1519
1520 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1521 $forder = 'CREATION';
1522 $sorder = 'UPDATE';
1523 $fsort = get_string("sortbycreation", "glossary");
1524 $ssort = get_string("sortbylastupdate", "glossary");
1525
468c120a 1526 $currentsort = $fsort;
1527 if ($sortkey == 'UPDATE') {
1528 $currentsort = $ssort;
1529 }
c4a35419 1530 $sort = get_string("sortchronogically", "glossary");
1531 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1532 $forder = 'FIRSTNAME';
1533 $sorder = 'LASTNAME';
1534 $fsort = get_string("firstname");
1535 $ssort = get_string("lastname");
1536
468c120a 1537 $currentsort = $fsort;
1538 if ($sortkey == 'LASTNAME') {
1539 $currentsort = $ssort;
1540 }
c4a35419 1541 $sort = get_string("sortby", "glossary");
1542 }
468c120a 1543 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1544 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$sorder$sneworder&amp;mode=$mode\">$ssort$sicon</a>$sendbtag | ".
839f2456 1545 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$forder$fneworder&amp;mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
fb443f1a 1546}
ad58adac 1547
1548function glossary_sort_entries ( $entry0, $entry1 ) {
a02c77dc 1549
95d56829 1550 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1551 return -1;
95d56829 1552 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1553 return 1;
1554 } else {
1555 return 0;
1556 }
1557}
1558
ed0201dd 1559function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
3a26f0ea 1560 global $CFG, $USER;
a02c77dc 1561
bbbf2d40 1562 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
ed0201dd 1563
3a26f0ea 1564 $user = get_record('user', 'id', $comment->userid);
1565 $strby = get_string('writtenby','glossary');
26663a23 1566 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
ed0201dd 1567
36a2b6bd 1568 echo '<div class="boxaligncenter">';
3a26f0ea 1569 echo '<table class="glossarycomment" cellspacing="0">';
1570 echo '<tr valign="top">';
eee75231 1571 echo '<td class="left picture">';
65bcf17b 1572 print_user_picture($user, $course->id, $user->picture);
3a26f0ea 1573 echo '</td>';
1574 echo '<td class="entryheader">';
c07ca217 1575
26663a23 1576 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
e6d45048 1577 $by = new object();
c07ca217 1578 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1579 $by->date = userdate($comment->timemodified);
1580 echo '<span class="author">'.get_string('bynameondate', 'forum', $by).'</span>';
1581
3a26f0ea 1582 echo '</td></tr>';
ed0201dd 1583
3a26f0ea 1584 echo '<tr valign="top"><td class="left side">';
1585 echo '&nbsp;';
1586 echo '</td><td class="entry">';
072f7533 1587
7d8a3cb0 1588 $options = new object();
1589 $options->trusttext = true;
0703d22e 1590 echo format_text($comment->entrycomment, $comment->format, $options);
072f7533 1591
3a26f0ea 1592 echo '<div class="icons commands">';
1593
3a512f86 1594 $ineditperiod = ((time() - $comment->timemodified < $CFG->maxeditingtime) || $glossary->editalways);
0468976c 1595 if ( ($glossary->allowcomments && $ineditperiod && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context)) {
a02c77dc 1596 echo "<a href=\"comment.php?cid=$comment->id&amp;action=edit\"><img
0d905d9f 1597 alt=\"" . get_string("edit") . "\" src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" /></a> ";
c197e607 1598 }
0468976c 1599 if ( ($glossary->allowcomments && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context) ) {
a02c77dc 1600 echo "<a href=\"comment.php?cid=$comment->id&amp;action=delete\"><img
0d905d9f 1601 alt=\"" . get_string("delete") . "\" src=\"$CFG->pixpath/t/delete.gif\" class=\"iconsmall\" /></a>";
c197e607 1602 }
a02c77dc 1603
3a26f0ea 1604 echo '</div></td></tr>';
36a2b6bd 1605 echo '</table></div>';
ed0201dd 1606
ed0201dd 1607}
1608
63dd5fb2 1609function glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
a02c77dc 1610
bbbf2d40 1611 global $USER, $CFG;
a02c77dc 1612
bbbf2d40 1613 $glossary = get_record('glossary', 'id', $entry->glossaryid);
1614 $glossarymod = get_record('modules','name','glossary');
a02c77dc 1615 $cm = get_record_sql("select * from {$CFG->prefix}course_modules where course = $course->id
dabfd0ed 1616 and module = $glossarymod->id and instance = $glossary->id");
a02c77dc 1617
bbbf2d40 1618 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
a359c29b 1619
63dd5fb2 1620 $ratingsmenuused = false;
1621 if (!empty($ratings) and !empty($USER->id)) {
1622 $useratings = true;
1623 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
1624 if ($entry->timecreated < $ratings->assesstimestart or $entry->timecreated > $ratings->assesstimefinish) {
1625 $useratings = false;
1626 }
1627 }
1628 if ($useratings) {
0468976c 1629 if (has_capability('mod/glossary:viewrating', $context)) {
63dd5fb2 1630 glossary_print_ratings_mean($entry->id, $ratings->scale);
1631 if ($USER->id != $entry->userid) {
1632 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1633 $ratingsmenuused = true;
1634 }
1635 } else if ($USER->id == $entry->userid) {
1636 glossary_print_ratings_mean($entry->id, $ratings->scale);
1637 } else if (!empty($ratings->allow) ) {
1638 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1639 $ratingsmenuused = true;
1640 }
1641 }
1642 }
1643 return $ratingsmenuused;
1644}
1645
b1918034 1646function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
a8466100 1647 global $USER,$CFG;
cca6f7f1 1648
36a2b6bd 1649 echo '<div class="boxaligncenter">';
a8466100 1650 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1651 echo '<td>';
1d9ddaaf 1652 if ( $entries ) {
1653 foreach ( $entries as $entry ) {
a8466100 1654 if (! $glossary = get_record('glossary', 'id', $entry->glossaryid)) {
5973a4c4 1655 print_error('invalidid', 'glossary');
cca6f7f1 1656 }
a8466100 1657 if (! $course = get_record('course', 'id', $glossary->course)) {
5973a4c4 1658 print_error('coursemisconf');
1d9ddaaf 1659 }
a8466100 1660 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
5973a4c4 1661 print_error('invalidid', 'glossary');
1d9ddaaf 1662 }
1f63b7c6 1663
1664 //If displayformat is present, override glossary->displayformat
a359c29b 1665 if ($displayformat < 0) {
1f63b7c6 1666 $dp = $glossary->displayformat;
a359c29b 1667 } else {
1f63b7c6 1668 $dp = $displayformat;
1669 }
1670
a359c29b 1671 //Get popupformatname
1672 $format = get_record('glossary_formats','name',$dp);
1673 $displayformat = $format->popupformatname;
1674
1675 //Check displayformat variable and set to default if necessary
1676 if (!$displayformat) {
1677 $displayformat = 'dictionary';
584dcac9 1678 }
1f63b7c6 1679
a359c29b 1680 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1681 $functionname = 'glossary_show_entry_'.$displayformat;
1682
1683 if (file_exists($formatfile)) {
1684 include_once($formatfile);
1685 if (function_exists($functionname)) {
1686 $functionname($course, $cm, $glossary, $entry,'','','','');
1687 }
1688 }
cca6f7f1 1689 }
cca6f7f1 1690 }
a8466100 1691 echo '</td>';
36a2b6bd 1692 echo '</tr></table></div>';
1d9ddaaf 1693}
4f4ca7b5 1694
1ac87c73 1695function glossary_generate_export_file($glossary, $hook = "", $hook = 0) {
212039c0 1696 global $CFG;
1697
1698 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1699
1700 $co .= glossary_start_tag("GLOSSARY",0,true);
1701 $co .= glossary_start_tag("INFO",1,true);
1702 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
1703 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
212039c0 1704 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
1705 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
1706 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
1707 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
1708 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
1709 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
1710 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
1711 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
1712 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
1713 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
4f4ca7b5 1714
748b1932 1715 if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
212039c0 1716 $co .= glossary_start_tag("ENTRIES",2,true);
748b1932 1717 foreach ($entries as $entry) {
046a797c 1718 $permissiongranted = 1;
1ac87c73 1719 if ( $hook ) {
1720 switch ( $hook ) {
046a797c 1721 case "ALL":
1722 case "SPECIAL":
1723 break;
1724 default:
1ac87c73 1725 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
046a797c 1726 break;
1727 }
1728 }
1ac87c73 1729 if ( $hook ) {
1730 switch ( $hook ) {
046a797c 1731 case GLOSSARY_SHOW_ALL_CATEGORIES:
1732 break;
1733 case GLOSSARY_SHOW_NOT_CATEGORISED:
1734 $permissiongranted = !record_exists("glossary_entries_categories","entryid",$entry->id);
1735 break;
1736 default:
1ac87c73 1737 $permissiongranted = record_exists("glossary_entries_categories","entryid",$entry->id, "categoryid",$hook);
046a797c 1738 break;
1739 }
1740 }
1741 if ( $entry->approved and $permissiongranted ) {
212039c0 1742 $co .= glossary_start_tag("ENTRY",3,true);
1743 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
7d8a3cb0 1744 $co .= glossary_full_tag("DEFINITION",4,false,trusttext_strip($entry->definition));
212039c0 1745 $co .= glossary_full_tag("FORMAT",4,false,$entry->format);
1746 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
1747 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
1748 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
1749 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
748b1932 1750
7965be79 1751 if ( $aliases = get_records("glossary_alias","entryid",$entry->id) ) {
212039c0 1752 $co .= glossary_start_tag("ALIASES",4,true);
7965be79 1753 foreach ($aliases as $alias) {
212039c0 1754 $co .= glossary_start_tag("ALIAS",5,true);
1755 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
1756 $co .= glossary_end_tag("ALIAS",5,true);
7965be79 1757 }
212039c0 1758 $co .= glossary_end_tag("ALIASES",4,true);
7965be79 1759 }
748b1932 1760 if ( $catentries = get_records("glossary_entries_categories","entryid",$entry->id) ) {
212039c0 1761 $co .= glossary_start_tag("CATEGORIES",4,true);
748b1932 1762 foreach ($catentries as $catentry) {
1763 $category = get_record("glossary_categories","id",$catentry->categoryid);
1764
212039c0 1765 $co .= glossary_start_tag("CATEGORY",5,true);
1766 $co .= glossary_full_tag("NAME",6,false,$category->name);
1767 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
1768 $co .= glossary_end_tag("CATEGORY",5,true);
748b1932 1769 }
212039c0 1770 $co .= glossary_end_tag("CATEGORIES",4,true);
748b1932 1771 }
4f4ca7b5 1772
212039c0 1773 $co .= glossary_end_tag("ENTRY",3,true);
4f4ca7b5 1774 }
1775 }
212039c0 1776 $co .= glossary_end_tag("ENTRIES",2,true);
748b1932 1777
4f4ca7b5 1778 }
748b1932 1779
1780
212039c0 1781 $co .= glossary_end_tag("INFO",1,true);
1782 $co .= glossary_end_tag("GLOSSARY",0,true);
4f4ca7b5 1783
212039c0 1784 return $co;
4f4ca7b5 1785}
212039c0 1786/// Functions designed by Eloy Lafuente
1787/// Functions to create, open and write header of the xml file
4f4ca7b5 1788
212039c0 1789// Read import file and convert to current charset
748b1932 1790function glossary_read_imported_file($file) {
9f79b50f 1791 require_once "../../lib/xmlize.php";
1792 global $CFG;
1793
748b1932 1794 $h = fopen($file,"r");
1795 $line = '';
1796 if ($h) {
1797 while ( !feof($h) ) {
b9656030 1798 $char = fread($h,1024);
748b1932 1799 $line .= $char;
1800 }
1801 fclose($h);
894ff63f 1802 }
792a76d8 1803 return xmlize($line, 0);
748b1932 1804}
4f4ca7b5 1805
a02c77dc 1806//Return the xml start tag
4f4ca7b5 1807function glossary_start_tag($tag,$level=0,$endline=false) {
1808 if ($endline) {
1809 $endchar = "\n";
1810 } else {
1811 $endchar = "";
1812 }
1813 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
1814}
a02c77dc 1815
1816//Return the xml end tag
4f4ca7b5 1817function glossary_end_tag($tag,$level=0,$endline=true) {
1818 if ($endline) {
1819 $endchar = "\n";
1820 } else {
1821 $endchar = "";
1822 }
1823 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
1824}
a02c77dc 1825
4f4ca7b5 1826//Return the start tag, the contents and the end tag
212039c0 1827function glossary_full_tag($tag,$level=0,$endline=true,$content) {
9f79b50f 1828 global $CFG;
a02c77dc 1829
4f4ca7b5 1830 $st = glossary_start_tag($tag,$level,$endline);
212039c0 1831 $co = preg_replace("/\r\n|\r/", "\n", s($content));
4f4ca7b5 1832 $et = glossary_end_tag($tag,0,true);
1833 return $st.$co.$et;
1834}
1835
63dd5fb2 1836/*
a02c77dc 1837* Adding grading functions
63dd5fb2 1838*/
1839
1840function glossary_get_ratings($entryid, $sort="u.firstname ASC") {
1841/// Returns a list of ratings for a particular entry - sorted.
1842 global $CFG;
a02c77dc 1843 return get_records_sql("SELECT u.*, r.rating, r.time
1844 FROM {$CFG->prefix}glossary_ratings r,
63dd5fb2 1845 {$CFG->prefix}user u
a02c77dc 1846 WHERE r.entryid = '$entryid'
1847 AND r.userid = u.id
63dd5fb2 1848 ORDER BY $sort");
1849}
1850
63dd5fb2 1851function glossary_count_unrated_entries($glossaryid, $userid) {
1852// How many unrated entries are in the given glossary for a given user?
1853 global $CFG;
1854 if ($entries = get_record_sql("SELECT count(*) as num
1855 FROM {$CFG->prefix}glossary_entries
a02c77dc 1856 WHERE glossaryid = '$glossaryid'
63dd5fb2 1857 AND userid <> '$userid' ")) {
1858
a02c77dc 1859 if ($rated = get_record_sql("SELECT count(*) as num
1860 FROM {$CFG->prefix}glossary_entries e,
63dd5fb2 1861 {$CFG->prefix}glossary_ratings r
1862 WHERE e.glossaryid = '$glossaryid'
a02c77dc 1863 AND e.id = r.entryid
63dd5fb2 1864 AND r.userid = '$userid'")) {
1865 $difference = $entries->num - $rated->num;
1866 if ($difference > 0) {
1867 return $difference;
1868 } else {
1869 return 0; // Just in case there was a counting error
1870 }
1871 } else {
1872 return $entries->num;
1873 }
1874 } else {
1875 return 0;
1876 }
1877}
1878
1879function glossary_print_ratings_mean($entryid, $scale) {
1880/// Print the multiple ratings on a entry given to the current user by others.
1881/// Scale is an array of ratings
1882
1883 static $strrate;
1884
1885 $mean = glossary_get_ratings_mean($entryid, $scale);
a02c77dc 1886
63dd5fb2 1887 if ($mean !== "") {
1888
1889 if (empty($strratings)) {
1890 $strratings = get_string("ratings", "glossary");
1891 }
1892
91b4cb68 1893 echo "$strratings: ";
63dd5fb2 1894 link_to_popup_window ("/mod/glossary/report.php?id=$entryid", "ratings", $mean, 400, 600);
1895 }
1896}
1897
1898
1899function glossary_get_ratings_mean($entryid, $scale, $ratings=NULL) {
1900/// Return the mean rating of a entry given to the current user by others.
1901/// Scale is an array of possible ratings in the scale
1902/// Ratings is an optional simple array of actual ratings (just integers)
1903
1904 if (!$ratings) {
1905 $ratings = array();
1906 if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
1907 foreach ($rates as $rate) {
1908 $ratings[] = $rate->rating;
1909 }
1910 }
1911 }
1912
1913 $count = count($ratings);
1914
1915 if ($count == 0) {
1916 return "";
1917
1918 } else if ($count == 1) {
1919 return $scale[$ratings[0]];
1920
1921 } else {
1922 $total = 0;
1923 foreach ($ratings as $rating) {
1924 $total += $rating;
1925 }
1926 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
a02c77dc 1927
63dd5fb2 1928 if (isset($scale[$mean])) {
1929 return $scale[$mean]." ($count)";
1930 } else {
1931 return "$mean ($count)"; // Should never happen, hopefully
1932 }
1933 }
1934}
1935
1936function glossary_get_ratings_summary($entryid, $scale, $ratings=NULL) {
1937/// Return a summary of entry ratings given to the current user by others.
1938/// Scale is an array of possible ratings in the scale
1939/// Ratings is an optional simple array of actual ratings (just integers)
1940
1941 if (!$ratings) {
1942 $ratings = array();
1943 if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
1944 foreach ($rates as $rate) {
1945 $rating[] = $rate->rating;
1946 }
1947 }
1948 }
1949
1950
1951 if (!$count = count($ratings)) {
1952 return "";
1953 }
1954
1955
1956 foreach ($scale as $key => $scaleitem) {
1957 $sumrating[$key] = 0;
1958 }
1959
1960 foreach ($ratings as $rating) {
1961 $sumrating[$rating]++;
1962 }
1963
1964 $summary = "";
1965 foreach ($scale as $key => $scaleitem) {
1966 $summary = $sumrating[$key].$summary;
1967 if ($key > 1) {
1968 $summary = "/$summary";
1969 }
1970 }
1971 return $summary;
1972}
1973
1974function glossary_print_rating_menu($entryid, $userid, $scale) {
a02c77dc 1975/// Print the menu of ratings as part of a larger form.
63dd5fb2 1976/// If the entry has already been - set that value.
1977/// Scale is an array of ratings
1978
1979 static $strrate;
1980
1981 if (!$rating = get_record("glossary_ratings", "userid", $userid, "entryid", $entryid)) {
92fac4b2 1982 $rating->rating = -999;
63dd5fb2 1983 }
1984
1985 if (empty($strrate)) {
1986 $strrate = get_string("rate", "glossary");
1987 }
1988
92fac4b2 1989 choose_from_menu($scale, $entryid, $rating->rating, "$strrate...",'',-999);
63dd5fb2 1990}
1991
e2cf5316 1992
1993function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
1994// Returns the html code to represent any pagging bar. Paramenters are:
1995//
1996// Mandatory:
1997// $totalcount: total number of records to be displayed
1998// $page: page currently selected (0 based)
1999// $perpage: number of records per page
2000// $baseurl: url to link in each page, the string 'page=XX' will be added automatically.
2001// Optional:
2002// $maxpageallowed: maximum number of page allowed.
2003// $maxdisplay: maximum number of page links to show in the bar
2004// $separator: string to be used between pages in the bar
2005// $specialtext: string to be showed as an special link
2006// $specialvalue: value (page) to be used in the special link
2007// $previousandnext: to decide if we want the previous and next links
2008//
2009// The function dinamically show the first and last pages, and "scroll" over pages.
2010// Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2011// could replace the general one. ;-)
2012
2013 $code = '';
2014
2015 $showspecial = false;
2016 $specialselected = false;
2017
2018 //Check if we have to show the special link
2019 if (!empty($specialtext)) {
2020 $showspecial = true;
2021 }
2022 //Check if we are with the special link selected
2023 if ($showspecial && $page == $specialvalue) {
2024 $specialselected = true;
a02c77dc 2025 }
e2cf5316 2026
2027 //If there are results (more than 1 page)
2028 if ($totalcount > $perpage) {
36a2b6bd 2029 $code .= "<div style=\"text-align:center\">";
e2cf5316 2030 $code .= "<p>".get_string("page").":";
2031
2032 $maxpage = (int)(($totalcount-1)/$perpage);
2033
2034 //Lower and upper limit of page
2035 if ($page < 0) {
2036 $page = 0;
2037 }
2038 if ($page > $maxpageallowed) {
2039 $page = $maxpageallowed;
2040 }
2041 if ($page > $maxpage) {
2042 $page = $maxpage;
2043 }
2044
2045 //Calculate the window of pages
2046 $pagefrom = $page - ((int)($maxdisplay / 2));
2047 if ($pagefrom < 0) {
2048 $pagefrom = 0;
2049 }
2050 $pageto = $pagefrom + $maxdisplay - 1;
2051 if ($pageto > $maxpageallowed) {
2052 $pageto = $maxpageallowed;
2053 }
2054 if ($pageto > $maxpage) {
2055 $pageto = $maxpage;
2056 }
2057
2058 //Some movements can be necessary if don't see enought pages
2059 if ($pageto - $pagefrom < $maxdisplay - 1) {
2060 if ($pageto - $maxdisplay + 1 > 0) {
2061 $pagefrom = $pageto - $maxdisplay + 1;
2062 }
2063 }
2064
2065 //Calculate first and last if necessary
2066 $firstpagecode = '';
2067 $lastpagecode = '';
2068 if ($pagefrom > 0) {
2069 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2070 if ($pagefrom > 1) {
2071 $firstpagecode .= "$separator...";
2072 }
2073 }
2074 if ($pageto < $maxpage) {
2075 if ($pageto < $maxpage -1) {
2076 $lastpagecode = "$separator...";
2077 }
2078 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2079 }
2080
2081 //Previous
2082 if ($page > 0 && $previousandnext) {
2083 $pagenum = $page - 1;
2084 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2085 }
2086
2087 //Add first
2088 $code .= $firstpagecode;
2089
2090 $pagenum = $pagefrom;
2091
2092 //List of maxdisplay pages
2093 while ($pagenum <= $pageto) {
2094 $pagetoshow = $pagenum +1;
2095 if ($pagenum == $page && !$specialselected) {
2096 $code .= "$separator$pagetoshow";
2097 } else {
2098 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2099 }
2100 $pagenum++;
2101 }
2102
2103 //Add last
2104 $code .= $lastpagecode;
2105
2106 //Next
2107 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2108 $pagenum = $page + 1;
2109 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2110 }
2111
2112 //Add special
2113 if ($showspecial) {
2114 $code .= '<br />';
2115 if ($specialselected) {
2116 $code .= $specialtext;
2117 } else {
2118 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2119 }
2120 }
2121
2122 //End html
2123 $code .= "</p>";
36a2b6bd 2124 $code .= "</div>";
e2cf5316 2125 }
2126
2127 return $code;
2128}
2129
f3221af9 2130function glossary_get_view_actions() {
2131 return array('view','view all','view entry');
2132}
2133
2134function glossary_get_post_actions() {
2135 return array('add category','add comment','add entry','approve entry','delete category','delete comment','delete entry','edit category','update comment','update entry');
2136}
2137
0b5a80a1 2138
2139/**
2140 * Implementation of the function for printing the form elements that control
2141 * whether the course reset functionality affects the glossary.
2142 * @param $mform form passed by reference
2143 */
2144function glossary_reset_course_form_definition(&$mform) {
2145 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2146 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2147
2148 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2149 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2150 $mform->setAdvanced('reset_glossary_types');
2151 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2152
2153 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2154 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2155
2156 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2157 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2158
2159 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2160 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2161}
2162
2163/**
2164 * Course reset form defaults.
2165 */
2166function glossary_reset_course_form_defaults($course) {
2167 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2168}
2169
2170/**
2171 * Removes all grades from gradebook
2172 * @param int $courseid
2173 * @param string optional type
2174 */
2175function glossary_reset_gradebook($courseid, $type='') {
2176 global $CFG;
2177
2178 switch ($type) {
2179 case 'main' : $type = "AND g.mainglossary=1"; break;
2180 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2181 default : $type = ""; //all
2182 }
2183
2184 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2185 FROM {$CFG->prefix}glossary g, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2186 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=$courseid $type";
2187
2188 if ($glossarys = get_records_sql($sql)) {
2189 foreach ($glossarys as $glossary) {
2190 glossary_grade_item_update($glossary, 'reset');
2191 }
2192 }
2193}
2194/**
2195 * Actual implementation of the rest coures functionality, delete all the
2196 * glossary responses for course $data->courseid.
2197 * @param $data the data submitted from the reset course.
2198 * @return array status array
2199 */
2200function glossary_reset_userdata($data) {
2201 global $CFG;
2202 require_once($CFG->libdir.'/filelib.php');
2203
2204 $componentstr = get_string('modulenameplural', 'glossary');
2205 $status = array();
2206
2207 $allentriessql = "SELECT e.id
2208 FROM {$CFG->prefix}glossary_entries e
2209 INNER JOIN {$CFG->prefix}glossary g ON e.glossaryid = g.id
2210 WHERE g.course = {$data->courseid}";
2211
2212 $allglossariessql = "SELECT g.id
2213 FROM {$CFG->prefix}glossary g
2214 WHERE g.course={$data->courseid}";
2215
2216 // delete entries if requested
2217 if (!empty($data->reset_glossary_all)
2218 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2219
2220 delete_records_select('glossary_ratings', "entryid IN ($allentriessql)");
2221 delete_records_select('glossary_comments', "entryid IN ($allentriessql)");
2222 delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)");
2223
2224 if ($glossaries = get_records_sql($allglossariessql)) {
2225 foreach ($glossaries as $glossaryid=>$unused) {
2226 fulldelete($CFG->dataroot."/$data->courseid/moddata/glossary/$glossaryid");
2227 }
2228 }
2229
2230 // remove all grades from gradebook
2231 if (empty($data->reset_gradebook_grades)) {
2232 glossary_reset_gradebook($data->courseid);
2233 }
2234
2235 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2236
2237 } else if (!empty($data->reset_glossary_types)) {
2238 $mainentriessql = "$allentries AND g.mainglossary=1";
2239 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2240
2241 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2242 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2243
2244 if (in_array('main', $data->reset_glossary_types)) {
2245 delete_records_select('glossary_ratings', "entryid IN ($mainentriessql)");
2246 delete_records_select('glossary_comments', "entryid IN ($mainentriessql)");
2247 delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)");
2248
2249 if ($glossaries = get_records_sql($mainglossariessql)) {
2250 foreach ($glossaries as $glossaryid=>$unused) {
2251 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$glossaryid");
2252 }
2253 }
2254
2255 // remove all grades from gradebook
2256 if (empty($data->reset_gradebook_grades)) {
2257 glossary_reset_gradebook($data->courseid, 'main');
2258 }
2259
2260 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2261
2262 } else if (in_array('secondary', $data->reset_glossary_types)) {
2263 delete_records_select('glossary_ratings', "entryid IN ($secondaryentriessql)");
2264 delete_records_select('glossary_comments', "entryid IN ($secondaryentriessql)");
2265 delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)");
2266 // remove exported source flag from entries in main glossary
2267 execute_sql("UPDATE {$CFG->prefix}glossary_entries
2268 SET sourceglossaryid=0
2269 WHERE glossaryid IN ($mainglossariessql)", false);
2270
2271 if ($glossaries = get_records_sql($secondaryglossariessql)) {
2272 foreach ($glossaries as $glossaryid=>$unused) {
2273 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$glossaryid");
2274 }
2275 }
2276
2277 // remove all grades from gradebook
2278 if (empty($data->reset_gradebook_grades)) {
2279 glossary_reset_gradebook($data->courseid, 'secondary');
2280 }
2281
2282 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2283 }
2284 }
2285
2286 // remove entries by users not enrolled into course
2287 if (!empty($data->reset_glossary_notenrolled)) {
2288 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2289 FROM {$CFG->prefix}glossary_entries e
2290 INNER JOIN {$CFG->prefix}glossary g ON e.glossaryid = g.id
2291 LEFT OUTER JOIN {$CFG->prefix}user u ON e.userid = u.id
2292 WHERE g.course = {$data->courseid} AND e.userid > 0";
2293
2294 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2295 $notenrolled = array();
2296 if ($rs = get_recordset_sql($entriessql)) {
2297 while ($entry = rs_fetch_next_record($rs)) {
2298 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2299 or !has_capability('moodle/course:view', $course_context , $entry->userid)) {
2300 delete_records('glossary_ratings', 'entryid', $entry->id);
2301 delete_records('glossary_comments', 'entryid', $entry->id);
2302 delete_records('glossary_entries', 'id', $entry->id);
2303 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$entry->glossaryid");
2304 $notenrolled[$entry->userid] = true;
2305 }
2306 }
2307 rs_close($rs);
2308 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2309 }
2310 }
2311
2312 // remove all ratings
2313 if (!empty($data->reset_glossary_ratings)) {
2314 delete_records_select('glossary_ratings', "entryid IN ($allentriessql)");
2315 // remove all grades from gradebook
2316 if (empty($data->reset_gradebook_grades)) {
2317 glossary_reset_gradebook($data->courseid);
2318 }
2319 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2320 }
2321
2322 // remove all comments
2323 if (!empty($data->reset_glossary_comments)) {
2324 delete_records_select('glossary_comments', "entryid IN ($allentriessql)");
2325 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2326 }
2327
2328 /// updating dates - shift may be negative too
2329 if ($data->timeshift) {
2330 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2331 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2332 }
2333
2334 return $status;
2335}
2336
cc41c129 2337?>