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