assignment MDL-24159 made glossary_reset_userdata clear glossary_alias of relevant...
[moodle.git] / mod / glossary / lib.php
CommitLineData
e121db76 1<?php
07842023 2
e121db76 3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Library of functions and constants for module glossary
20 * (replace glossary with the name of your module and delete this line)
21 *
22 * @package mod-glossary
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
427711b1 26require_once($CFG->dirroot . '/rating/lib.php');
214b1cf7 27
7dd88447 28define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
29define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
c76e673a 30
1ac87c73 31define("GLOSSARY_NO_VIEW", -1);
7dd88447 32define("GLOSSARY_STANDARD_VIEW", 0);
33define("GLOSSARY_CATEGORY_VIEW", 1);
c197e607 34define("GLOSSARY_DATE_VIEW", 2);
1ac87c73 35define("GLOSSARY_AUTHOR_VIEW", 3);
36define("GLOSSARY_ADDENTRY_VIEW", 4);
37define("GLOSSARY_IMPORT_VIEW", 5);
38define("GLOSSARY_EXPORT_VIEW", 6);
39define("GLOSSARY_APPROVAL_VIEW", 7);
fb443f1a 40
da9c60ec 41/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
e121db76 42/**
43 * @global object
44 * @param object $glossary
45 * @return int
46 */
07842023 47function glossary_add_instance($glossary) {
c18269c7 48 global $DB;
07842023 49/// Given an object containing all the necessary data,
7cac0c4b 50/// (defined by the form in mod_form.php) this function
07842023 51/// will create a new instance and return the id number
52/// of the new instance.
53
e6d45048 54 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 55 $glossary->assesstimestart = 0;
56 $glossary->assesstimefinish = 0;
57 }
58
63e21b9b 59 if (empty($glossary->globalglossary) ) {
0de786f7 60 $glossary->globalglossary = 0;
63e21b9b 61 }
62
957f6fc9 63 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
0de786f7 64 $glossary->globalglossary = 0;
65 }
66
e6d45048 67 $glossary->timecreated = time();
07842023 68 $glossary->timemodified = $glossary->timecreated;
69
ff424012 70 //Check displayformat is a valid one
71 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
72 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 73 print_error('unknowformat', '', '', $glossary->displayformat);
a02c77dc 74 }
24c1be88 75
2a7eff41 76 $returnid = $DB->insert_record("glossary", $glossary);
77 $glossary->id = $returnid;
78 glossary_grade_item_update($glossary);
e6d45048 79
80 return $returnid;
07842023 81}
82
e121db76 83/**
84 * Given an object containing all the necessary data,
85 * (defined by the form in mod_form.php) this function
86 * will update an existing instance with new data.
87 *
88 * @global object
89 * @global object
90 * @param object $glossary
91 * @return bool
92 */
07842023 93function glossary_update_instance($glossary) {
c18269c7 94 global $CFG, $DB;
a02c77dc 95
da5754f8 96 if (empty($glossary->globalglossary)) {
97 $glossary->globalglossary = 0;
98 }
0de786f7 99
957f6fc9 100 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
63e21b9b 101 // keep previous
102 unset($glossary->globalglossary);
103 }
104
07842023 105 $glossary->timemodified = time();
e6d45048 106 $glossary->id = $glossary->instance;
07842023 107
e6d45048 108 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 109 $glossary->assesstimestart = 0;
110 $glossary->assesstimefinish = 0;
111 }
112
ff424012 113 //Check displayformat is a valid one
114 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
115 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 116 print_error('unknowformat', '', '', $glossary->displayformat);
ff424012 117 }
118
dd88de0e 119 $DB->update_record("glossary", $glossary);
2a7eff41 120 if ($glossary->defaultapproval) {
121 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
5eaa2d34 122 }
2a7eff41 123 glossary_grade_item_update($glossary);
07842023 124
dd88de0e 125 return true;
07842023 126}
127
49bcd737 128/**
129 * Given an ID of an instance of this module,
130 * this function will permanently delete the instance
131 * and any data that depends on it.
e121db76 132 *
133 * @global object
49bcd737 134 * @param int $id glossary id
135 * @return bool success
136 */
07842023 137function glossary_delete_instance($id) {
650a0c0a 138 global $DB, $CFG;
07842023 139
49bcd737 140 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
07842023 141 return false;
142 }
143
49bcd737 144 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
145 return false;
146 }
07842023 147
49bcd737 148 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
149 return false;
150 }
07842023 151
49bcd737 152 $fs = get_file_storage();
153
154 if ($glossary->mainglossary) {
155 // unexport entries
156 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
157 FROM {glossary_entries} ge
158 JOIN {modules} m ON m.name = 'glossary'
159 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
160 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
161
162 if ($exported = $DB->get_records_sql($sql, array($id))) {
163 foreach ($exported as $entry) {
164 $entry->glossaryid = $entry->sourceglossaryid;
165 $entry->sourceglossaryid = 0;
166 $newcontext = get_context_instance(CONTEXT_MODULE, $entry->sourcecmid);
64f93798 167 if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
49bcd737 168 foreach ($oldfiles as $oldfile) {
169 $file_record = new object();
170 $file_record->contextid = $newcontext->id;
171 $fs->create_file_from_storedfile($file_record, $oldfile);
172 }
64f93798 173 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
49bcd737 174 $entry->attachment = '1';
072f7533 175 } else {
49bcd737 176 $entry->attachment = '0';
072f7533 177 }
49bcd737 178 $DB->update_record('glossary_entries', $entry);
49210b90 179 }
180 }
49bcd737 181 } else {
182 // move exported entries to main glossary
183 $sql = "UPDATE {glossary_entries}
184 SET sourceglossaryid = 0
185 WHERE sourceglossaryid = ?";
186 $DB->execute($sql, array($id));
07842023 187 }
49bcd737 188
189 // Delete any dependent records
190 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
d95ed8e3 191 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id));
49bcd737 192 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
49bcd737 193
194 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
195 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
196 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
197
fa686bc4 198 // delete all files
199 $fs->delete_area_files($context->id);
49bcd737 200
2e4b4fc0
AD
201 //delete ratings
202 $rm = new rating_manager();
203 $ratingdeloptions = new stdclass();
204 $ratingdeloptions->contextid = $context->id;
205 $rm->delete_ratings($ratingdeloptions);
206
e6d45048 207 glossary_grade_item_delete($glossary);
07842023 208
49bcd737 209 return $DB->delete_records('glossary', array('id'=>$id));
07842023 210}
211
e121db76 212/**
213 * Return a small object with summary information about what a
214 * user has done with a given particular instance of this module
215 * Used for user activity reports.
216 * $return->time = the time they did it
217 * $return->info = a short text description
218 *
219 * @param object $course
220 * @param object $user
221 * @param object $mod
222 * @param object $glossary
223 * @return object|null
224 */
07842023 225function glossary_user_outline($course, $user, $mod, $glossary) {
1a96363a
NC
226 global $CFG;
227
228 require_once("$CFG->libdir/gradelib.php");
229 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
230 if (empty($grades->items[0]->grades)) {
231 $grade = false;
232 } else {
233 $grade = reset($grades->items[0]->grades);
234 }
07842023 235
1ac87c73 236 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
e6d45048 237 $result = new object();
1ac87c73 238 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
239
63dd5fb2 240 $lastentry = array_pop($entries);
241 $result->time = $lastentry->timemodified;
1a96363a
NC
242
243 if ($grade) {
244 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
245 }
246 return $result;
247 } else if ($grade) {
248 $result = new object();
249 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
250 $result->time = $grade->dategraded;
1ac87c73 251 return $result;
252 }
253 return NULL;
254}
255
e121db76 256/**
257 * @global object
258 * @param int $glossaryid
259 * @param int $userid
260 * @return array
261 */
1ac87c73 262function glossary_get_user_entries($glossaryid, $userid) {
263/// Get all the entries for a user in a glossary
ae8c3566 264 global $DB;
1ac87c73 265
ae8c3566 266 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
267 FROM {glossary} g, {glossary_entries} e, {user} u
268 WHERE g.id = ?
a02c77dc 269 AND e.glossaryid = g.id
ae8c3566 270 AND e.userid = ?
1ac87c73 271 AND e.userid = u.id
ae8c3566 272 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
07842023 273}
274
e121db76 275/**
276 * Print a detailed representation of what a user has done with
277 * a given particular instance of this module, for user activity reports.
278 *
279 * @global object
280 * @param object $course
281 * @param object $user
282 * @param object $mod
283 * @param object $glossary
284 */
07842023 285function glossary_user_complete($course, $user, $mod, $glossary) {
1a96363a
NC
286 global $CFG, $OUTPUT;
287 require_once("$CFG->libdir/gradelib.php");
288
289 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
290 if (!empty($grades->items[0]->grades)) {
291 $grade = reset($grades->items[0]->grades);
292 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
293 if ($grade->str_feedback) {
294 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
295 }
296 }
07842023 297
1ac87c73 298 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
a359c29b 299 echo '<table width="95%" border="0"><tr><td>';
1ac87c73 300 foreach ($entries as $entry) {
301 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
302 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
303 echo '<p>';
304 }
a359c29b 305 echo '</td></tr></table>';
1ac87c73 306 }
07842023 307}
e121db76 308/**
309 * Given a course and a time, this module should find recent activity
310 * that has occurred in glossary activities and print it out.
311 * Return true if there was output, or false is there was none.
312 *
313 * @global object
314 * @global object
315 * @global object
316 * @param object $course
317 * @param object $viewfullnames
318 * @param int $timestart
319 * @return bool
320 */
dd97c328 321function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
3097018f 322 global $CFG, $USER, $DB, $OUTPUT;
dd97c328 323
324 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
325
326 $modinfo = get_fast_modinfo($course);
327 $ids = array();
328 foreach ($modinfo->cms as $cm) {
329 if ($cm->modname != 'glossary') {
330 continue;
331 }
332 if (!$cm->uservisible) {
333 continue;
334 }
335 $ids[$cm->instance] = $cm->instance;
336 }
337
338 if (!$ids) {
339 return false;
340 }
341
342 $glist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
07842023 343
ae8c3566 344 if (!$entries = $DB->get_records_sql("SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
345 ge.userid, u.firstname, u.lastname, u.email, u.picture
346 FROM {glossary_entries} ge
347 JOIN {user} u ON u.id = ge.userid
348 WHERE ge.glossaryid IN ($glist) AND ge.timemodified > ?
349 ORDER BY ge.timemodified ASC", array($timestart))) {
07842023 350 return false;
351 }
352
dd97c328 353 $editor = array();
a359c29b 354
dd97c328 355 foreach ($entries as $entryid=>$entry) {
356 if ($entry->approved) {
cf8eaebb 357 continue;
358 }
dd97c328 359
360 if (!isset($editor[$entry->glossaryid])) {
361 $editor[$entry->glossaryid] = has_capability('mod/glossary:approve', get_context_instance(CONTEXT_MODULE, $modinfo->instances['glossary'][$entry->glossaryid]->id));
07842023 362 }
07842023 363
dd97c328 364 if (!$editor[$entry->glossaryid]) {
365 unset($entries[$entryid]);
366 }
367 }
8f7dc7f1 368
dd97c328 369 if (!$entries) {
370 return false;
371 }
3097018f 372 echo $OUTPUT->heading(get_string('newentries', 'glossary').':');
dd97c328 373
374 $strftimerecent = get_string('strftimerecent');
375 foreach ($entries as $entry) {
376 $link = $CFG->wwwroot.'/mod/glossary/view.php?g='.$entry->glossaryid.'&amp;mode=entry&amp;hook='.$entry->id;
377 if ($entry->approved) {
378 $dimmed = '';
379 } else {
380 $dimmed = ' dimmed_text';
07842023 381 }
dd97c328 382 echo '<div class="head'.$dimmed.'">';
383 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
384 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
385 echo '</div>';
386 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
07842023 387 }
388
dd97c328 389 return true;
07842023 390}
391
e121db76 392/**
393 * @global object
394 * @param object $log
395 */
1ac87c73 396function glossary_log_info($log) {
ae8c3566 397 global $DB;
1ac87c73 398
ae8c3566 399 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
400 FROM {glossary_entries} e, {user} u
401 WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
1ac87c73 402}
403
e121db76 404/**
405 * Function to be run periodically according to the moodle cron
406 * This function searches for things that need to be done, such
407 * as sending out mail, toggling flags etc ...
408 * @return bool
409 */
07842023 410function glossary_cron () {
07842023 411 return true;
412}
413
d31bae70 414/**
415 * Return grade for given user or all users.
416 *
e121db76 417 * @global object
d31bae70 418 * @param int $glossaryid id of glossary
419 * @param int $userid optional user id, 0 means all users
420 * @return array array of grades, false if none
421 */
612607bd 422function glossary_get_user_grades($glossary, $userid=0) {
63e87951 423 /*global $DB;
63dd5fb2 424
ae8c3566 425 $params = array('userid'=>$userid, 'gid'=>$glossary->id);
426
427 $user = $userid ? "AND u.id = :userid" : "";
63dd5fb2 428
ac9b0805 429 $sql = "SELECT u.id, u.id AS userid, avg(gr.rating) AS rawgrade
ae8c3566 430 FROM {user} u, {glossary_entries} ge, {glossary_ratings} gr
e6d45048 431 WHERE u.id = ge.userid AND ge.id = gr.entryid
ae8c3566 432 AND gr.userid != u.id AND ge.glossaryid = :gid
e6d45048 433 $user
434 GROUP BY u.id";
435
63e87951
AD
436 return $DB->get_records_sql($sql, $params);*/
437 global $CFG;
438
439 require_once($CFG->dirroot.'/rating/lib.php');
440 $rm = new rating_manager();
441
442 $ratingoptions = new stdclass();
443
444 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
445 $ratingoptions->modulename = 'glossary';
446 $ratingoptions->moduleid = $glossary->id;
447
448 $ratingoptions->userid = $userid;
449 $ratingoptions->aggregationmethod = $glossary->assessed;
450 $ratingoptions->scaleid = $glossary->scale;
451 $ratingoptions->itemtable = 'glossary_entries';
452 $ratingoptions->itemtableusercolumn = 'userid';
453
454 return $rm->get_user_grades($ratingoptions);
e6d45048 455}
456
d251b259
AD
457/**
458 * Return rating related permissions
459 * @param string $options the context id
460 * @return array an associative array of the user's rating permissions
461 */
462function glossary_rating_permissions($options) {
463 $contextid = $options;
464 $context = get_context_instance_by_id($contextid);
465
466 if (!$context) {
467 print_error('invalidcontext');
468 return null;
469 } else {
470 return array('view'=>has_capability('mod/glossary:viewrating',$context), 'viewany'=>has_capability('mod/glossary:viewanyrating',$context), 'viewall'=>has_capability('mod/glossary:viewallratings',$context), 'rate'=>has_capability('mod/glossary:rate',$context));
471 }
472}
473
aeafd436
AD
474/**
475 * Returns the names of the table and columns necessary to check items for ratings
476 * @return array an array containing the item table, item id and user id columns
477 */
478function glossary_rating_item_check_info() {
479 return array('glossary_entries','id','userid');
480}
481
d31bae70 482/**
775f811a 483 * Update activity grades
d31bae70 484 *
e121db76 485 * @global object
486 * @global object
7f46236f 487 * @param object $glossary null means all glossaries (with extra cmidnumber property)
775f811a 488 * @param int $userid specific user only, 0 means all
d31bae70 489 */
612607bd 490function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
ae8c3566 491 global $CFG, $DB;
adcbb43a 492 require_once($CFG->libdir.'/gradelib.php');
e6d45048 493
775f811a 494 if (!$glossary->assessed) {
495 glossary_grade_item_update($glossary);
3e6303b7 496
775f811a 497 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
498 glossary_grade_item_update($glossary, $grades);
eafb9d9e 499
775f811a 500 } else if ($userid and $nullifnone) {
501 $grade = new object();
502 $grade->userid = $userid;
503 $grade->rawgrade = NULL;
504 glossary_grade_item_update($glossary, $grade);
a02c77dc 505
e6d45048 506 } else {
775f811a 507 glossary_grade_item_update($glossary);
508 }
509}
510
511/**
512 * Update all grades in gradebook.
e121db76 513 *
514 * @global object
775f811a 515 */
516function glossary_upgrade_grades() {
517 global $DB;
518
519 $sql = "SELECT COUNT('x')
520 FROM {glossary} g, {course_modules} cm, {modules} m
521 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
522 $count = $DB->count_records_sql($sql);
523
524 $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
525 FROM {glossary} g, {course_modules} cm, {modules} m
526 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
527 if ($rs = $DB->get_recordset_sql($sql)) {
775f811a 528 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
529 $i=0;
530 foreach ($rs as $glossary) {
531 $i++;
532 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
533 glossary_update_grades($glossary, 0, false);
534 $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
e6d45048 535 }
775f811a 536 $rs->close();
e6d45048 537 }
538}
539
d31bae70 540/**
612607bd 541 * Create/update grade item for given glossary
d31bae70 542 *
e121db76 543 * @global object
dd232d01 544 * @param object $glossary object with extra cmidnumber
0b5a80a1 545 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 546 * @return int, 0 if ok, error code otherwise
d31bae70 547 */
0b5a80a1 548function glossary_grade_item_update($glossary, $grades=NULL) {
612607bd 549 global $CFG;
ae8c3566 550 require_once($CFG->libdir.'/gradelib.php');
551
7f46236f 552 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
e6d45048 553
5980d52f 554 if (!$glossary->assessed or $glossary->scale == 0) {
612607bd 555 $params['gradetype'] = GRADE_TYPE_NONE;
34601114 556
557 } else if ($glossary->scale > 0) {
e8586b5f 558 $params['gradetype'] = GRADE_TYPE_VALUE;
e6d45048 559 $params['grademax'] = $glossary->scale;
560 $params['grademin'] = 0;
561
562 } else if ($glossary->scale < 0) {
e8586b5f 563 $params['gradetype'] = GRADE_TYPE_SCALE;
e6d45048 564 $params['scaleid'] = -$glossary->scale;
e6d45048 565 }
566
0b5a80a1 567 if ($grades === 'reset') {
568 $params['reset'] = true;
569 $grades = NULL;
570 }
571
572 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
e6d45048 573}
574
d31bae70 575/**
576 * Delete grade item for given glossary
1adbd2c3 577 *
e121db76 578 * @global object
dd232d01 579 * @param object $glossary object
d31bae70 580 */
e6d45048 581function glossary_grade_item_delete($glossary) {
612607bd 582 global $CFG;
583 require_once($CFG->libdir.'/gradelib.php');
584
b67ec72f 585 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
07842023 586}
587
e121db76 588/**
589 * Returns the users with data in one glossary
590 * (users with records in glossary_entries, students)
591 *
592 * @global object
593 * @param int $glossaryid
594 * @return array
595 */
05855091 596function glossary_get_participants($glossaryid) {
ae8c3566 597 global $DB;
05855091 598
599 //Get students
ae8c3566 600 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
601 FROM {user} u, {glossary_entries} g
585fb1f4 602 WHERE g.glossaryid = ? AND u.id = g.userid", array($glossaryid));
05855091 603
604 //Return students array (it contains an array of unique users)
ae8c3566 605 return $students;
05855091 606}
07842023 607
e121db76 608/**
609 * @global object
610 * @param int $gloassryid
611 * @param int $scaleid
612 * @return bool
613 */
0f1a97c2 614function glossary_scale_used ($glossaryid,$scaleid) {
615//This function returns if a scale is being used by one glossary
ae8c3566 616 global $DB;
a02c77dc 617
0f1a97c2 618 $return = false;
619
ae8c3566 620 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
0f1a97c2 621
2127fedd 622 if (!empty($rec) && !empty($scaleid)) {
a02c77dc 623 $return = true;
624 }
625
0f1a97c2 626 return $return;
627}
628
85c9ebb9 629/**
630 * Checks if scale is being used by any instance of glossary
631 *
632 * This is used to find out if scale used anywhere
e121db76 633 *
634 * @global object
635 * @param int $scaleid
85c9ebb9 636 * @return boolean True if the scale is used by any glossary
637 */
638function glossary_scale_used_anywhere($scaleid) {
ae8c3566 639 global $DB;
640
641 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
85c9ebb9 642 return true;
643 } else {
644 return false;
645 }
646}
647
07842023 648//////////////////////////////////////////////////////////////////////////////////////
649/// Any other glossary functions go here. Each of them must have a name that
650/// starts with glossary_
651
e121db76 652/**
653 * This function return an array of valid glossary_formats records
654 * Everytime it's called, every existing format is checked, new formats
655 * are included if detected and old formats are deleted and any glossary
656 * using an invalid format is updated to the default (dictionary).
657 *
658 * @global object
659 * @global object
660 * @return array
661 */
a359c29b 662function glossary_get_available_formats() {
ae8c3566 663 global $CFG, $DB;
a359c29b 664
665 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
77495793 666 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
667 $pluginformats = array();
a359c29b 668 foreach ($formats as $format) {
669 //If the format file exists
670 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
671 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
672 //If the function exists
673 if (function_exists('glossary_show_entry_'.$format)) {
77495793 674 //Acummulate it as a valid format
675 $pluginformats[] = $format;
a359c29b 676 //If the format doesn't exist in the table
ae8c3566 677 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
a359c29b 678 //Insert the record in glossary_formats
e6d45048 679 $gf = new object();
a359c29b 680 $gf->name = $format;
681 $gf->popupformatname = $format;
682 $gf->visible = 1;
ae8c3566 683 $DB->insert_record("glossary_formats",$gf);
a359c29b 684 }
685 }
686 }
687 }
688
689 //Delete non_existent formats from glossary_formats table
ae8c3566 690 $formats = $DB->get_records("glossary_formats");
a359c29b 691 foreach ($formats as $format) {
692 $todelete = false;
77495793 693 //If the format in DB isn't a valid previously detected format then delete the record
694 if (!in_array($format->name,$pluginformats)) {
a359c29b 695 $todelete = true;
a359c29b 696 }
697
698 if ($todelete) {
699 //Delete the format
ae8c3566 700 $DB->delete_records('glossary_formats', array('name'=>$format->name));
a359c29b 701 //Reasign existing glossaries to default (dictionary) format
ae8c3566 702 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
a359c29b 703 foreach($glossaries as $glossary) {
ae8c3566 704 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
a359c29b 705 }
706 }
707 }
708 }
709
710 //Now everything is ready in glossary_formats table
ae8c3566 711 $formats = $DB->get_records("glossary_formats");
a359c29b 712
713 return $formats;
714}
715
e121db76 716/**
717 * @param bool $debug
718 * @param string $text
719 * @param int $br
720 */
1ac87c73 721function glossary_debug($debug,$text,$br=1) {
722 if ( $debug ) {
41905731 723 echo '<font color="red">' . $text . '</font>';
1ac87c73 724 if ( $br ) {
a9ef4a63 725 echo '<br />';
1ac87c73 726 }
727 }
07842023 728}
729
e121db76 730/**
731 *
732 * @global object
733 * @param int $glossaryid
734 * @param string $entrylist
735 * @param string $pivot
736 * @return array
737 */
ea14e783 738function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
ae8c3566 739 global $DB;
ea14e783 740 if ($pivot) {
741 $pivot .= ",";
742 }
07842023 743
ae8c3566 744 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
745 FROM {glossary_entries}
746 WHERE glossaryid = ?
747 AND id IN ($entrylist)", array($glossaryid));
07842023 748}
359f2758 749
e121db76 750/**
751 * @global object
752 * @global object
753 * @param object $concept
754 * @param string $courseid
755 * @return array
756 */
359f2758 757function glossary_get_entries_search($concept, $courseid) {
ae8c3566 758 global $CFG, $DB;
359f2758 759
a02c77dc 760 //Check if the user is an admin
6c351232 761 $bypassadmin = 1; //This means NO (by default)
957f6fc9 762 if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM))) {
6c351232 763 $bypassadmin = 0; //This means YES
a02c77dc 764 }
6c351232 765
a02c77dc 766 //Check if the user is a teacher
6c351232 767 $bypassteacher = 1; //This means NO (by default)
81e956b9 768 if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
6c351232 769 $bypassteacher = 0; //This means YES
a02c77dc 770 }
6c351232 771
95d56829 772 $conceptlower = moodle_strtolower(trim($concept));
359f2758 773
ae8c3566 774 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
c76e673a 775
ae8c3566 776 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
777 FROM {glossary_entries} e, {glossary} g,
778 {course_modules} cm, {modules} m
779 WHERE m.name = 'glossary' AND
780 cm.module = m.id AND
781 (cm.visible = 1 OR cm.visible = $bypassadmin OR
782 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
783 g.id = cm.instance AND
784 e.glossaryid = g.id AND
785 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
786 (e.casesensitive = 0 and concept = :concept)) AND
2e300e13 787 (g.course = :courseid2 OR g.globalglossary = 1) AND
ae8c3566 788 e.usedynalink != 0 AND
789 g.usedynalink != 0", $params);
c76e673a 790}
07842023 791
e121db76 792/**
793 * @global object
794 * @global object
795 * @param object $course
796 * @param object $course
797 * @param object $glossary
798 * @param object $entry
799 * @param string $mode
800 * @param string $hook
801 * @param int $printicons
802 * @param int $displayformat
e121db76 803 * @param bool $printview
804 * @return mixed
805 */
63e87951 806function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
b8340d19 807 global $USER, $CFG;
37d543b5 808 $return = false;
b1918034 809 if ( $displayformat < 0 ) {
810 $displayformat = $glossary->displayformat;
811 }
b620a995 812 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
a359c29b 813 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
ae06e00e 814 if ($printview) {
815 $functionname = 'glossary_print_entry_'.$displayformat;
816 } else {
817 $functionname = 'glossary_show_entry_'.$displayformat;
818 }
a359c29b 819
820 if (file_exists($formatfile)) {
821 include_once($formatfile);
822 if (function_exists($functionname)) {
63e87951 823 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
ae06e00e 824 } else if ($printview) {
825 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
ccde17c3 826 $return = glossary_print_entry_default($entry, $glossary, $cm);
c76e673a 827 }
767a31c3 828 }
07842023 829 }
a359c29b 830 return $return;
07842023 831}
b8340d19 832
e121db76 833/**
834 * Default (old) print format used if custom function doesn't exist in format
835 *
836 * @param object $entry
837 * @param object $glossary
838 * @param object $cm
839 * @return void Output is echo'd
840 */
ccde17c3 841function glossary_print_entry_default ($entry, $glossary, $cm) {
097d705e 842 echo '<h3>'. strip_tags($entry->concept) . ': </h3>';
7d8a3cb0 843
844 $definition = $entry->definition;
845
7d8a3cb0 846 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
847
ccde17c3 848 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 849 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
cbc2b5df 850
7d8a3cb0 851 $options = new object();
ae06e00e 852 $options->para = false;
cbc2b5df 853 $options->trusted = $entry->definitiontrust;
854 $definition = format_text($definition, $entry->definitionformat, $options);
ae06e00e 855 echo ($definition);
856 echo '<br /><br />';
857}
a359c29b 858
120a18f0 859/**
860 * Print glossary concept/term as a heading &lt;h3>
e121db76 861 * @param object $entry
120a18f0 862 */
218c0385 863function glossary_print_entry_concept($entry, $return=false) {
2d8e042e 864 global $OUTPUT;
7d8a3cb0 865 $options = new object();
d34b9c5f 866 $options->para = false;
2d8e042e 867 $text = format_text($OUTPUT->heading('<span class="nolink">' . $entry->concept . '</span>', 3, 'nolink'), FORMAT_MOODLE, $options);
ff8352de 868 if (!empty($entry->highlight)) {
869 $text = highlight($entry->highlight, $text);
870 }
218c0385
AD
871
872 if ($return) {
873 return $text;
874 } else {
875 echo $text;
876 }
81bdc9e9 877}
1d9ddaaf 878
e121db76 879/**
880 *
881 * @global object
882 * @global array
883 * @param object $entry
884 * @param object $glossary
885 * @param object $cm
886 */
ccde17c3 887function glossary_print_entry_definition($entry, $glossary, $cm) {
ae8c3566 888 global $DB;
701fff21 889
f287e69c 890 $definition = $entry->definition;
891
4e489ae9 892 global $GLOSSARY_EXCLUDECONCEPTS;
893
701fff21 894 //Calculate all the strings to be no-linked
895 //First, the concept
4e489ae9 896 $GLOSSARY_EXCLUDECONCEPTS=array($entry->concept);
701fff21 897 //Now the aliases
ae8c3566 898 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
701fff21 899 foreach ($aliases as $alias) {
4e489ae9 900 $GLOSSARY_EXCLUDECONCEPTS[]=trim($alias->alias);
701fff21 901 }
f287e69c 902 }
903
7d8a3cb0 904 $options = new object();
3eb2f7ec 905 $options->para = false;
cbc2b5df 906 $options->trusted = $entry->definitiontrust;
0f9a668f 907
ccde17c3 908 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 909 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
cbc2b5df 910
911 $text = format_text($definition, $entry->definitionformat, $options);
912
4e489ae9 913 // Stop excluding concepts from autolinking
914 unset($GLOSSARY_EXCLUDECONCEPTS);
cbc2b5df 915
ff8352de 916 if (!empty($entry->highlight)) {
917 $text = highlight($entry->highlight, $text);
918 }
359f2758 919 if (isset($entry->footer)) { // Unparsed footer info
920 $text .= $entry->footer;
921 }
ff8352de 922 echo $text;
1d9ddaaf 923}
924
e121db76 925/**
926 *
927 * @global object
928 * @param object $course
929 * @param object $cm
930 * @param object $glossary
931 * @param object $entry
932 * @param string $mode
933 * @param string $hook
934 * @param string $type
935 * @return string|void
936 */
b8340d19 937function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
ae8c3566 938 global $DB;
939
81bdc9e9 940 $return = '';
ae8c3566 941 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
81bdc9e9 942 foreach ($aliases as $alias) {
33cc423e 943 if (trim($alias->alias)) {
81bdc9e9 944 if ($return == '') {
945 $return = '<select style="font-size:8pt">';
946 }
947 $return .= "<option>$alias->alias</option>";
948 }
949 }
950 if ($return != '') {
951 $return .= '</select>';
81bdc9e9 952 }
a02c77dc 953 }
1ac87c73 954 if ($type == 'print') {
81bdc9e9 955 echo $return;
956 } else {
957 return $return;
958 }
959}
960
e121db76 961/**
962 *
963 * @global object
964 * @global object
965 * @global object
966 * @param object $course
967 * @param object $cm
968 * @param object $glossary
969 * @param object $entry
970 * @param string $mode
971 * @param string $hook
972 * @param string $type
973 * @return string|void
974 */
b8340d19 975function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
4096752d 976 global $USER, $CFG, $DB, $OUTPUT;
a02c77dc 977
dabfd0ed 978 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
81bdc9e9 979
36ce6ea2 980 $output = false; //To decide if we must really return text in "return". Activate when needed only!
81bdc9e9 981 $importedentry = ($entry->sourceglossaryid == $glossary->id);
81bdc9e9 982 $ismainglossary = $glossary->mainglossary;
b8340d19 983
984
9362b9b6 985 $return = '<span class="commands">';
097d705e 986 // Differentiate links for each entry.
2d1e0971 987 $altsuffix = ': '.strip_tags(format_text($entry->concept));
988
81bdc9e9 989 if (!$entry->approved) {
36ce6ea2 990 $output = true;
b8340d19 991 $return .= get_string('entryishidden','glossary');
81bdc9e9 992 }
b8340d19 993
4f0c2d00 994 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $entry->userid == $USER->id)) {
81bdc9e9 995 // only teachers can export entries so check it out
0468976c 996 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
ae8c3566 997 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id));
81bdc9e9 998 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
36ce6ea2 999 $output = true;
b5d0cafc 1000 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$entry->id.'&amp;prevmode='.$mode.'&amp;hook='.urlencode($hook).'"><img src="'.$OUTPUT->pix_url('export', 'glossary').'" class="iconsmall" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
81bdc9e9 1001 }
1002 }
1003
1004 if ( $entry->sourceglossaryid ) {
b5d0cafc 1005 $icon = $OUTPUT->pix_url('minus', 'glossary'); // graphical metaphor (minus) for deleting an imported entry
81bdc9e9 1006 } else {
b5d0cafc 1007 $icon = $OUTPUT->pix_url('t/delete');
81bdc9e9 1008 }
1009
ff1e2621 1010 //Decide if an entry is editable:
1011 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1012 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
516c7276 1013 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
6cb34d44 1014 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
36ce6ea2 1015 $output = true;
49bcd737 1016 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"";
81bdc9e9 1017 $return .= $icon;
097d705e 1018 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
a02c77dc 1019
b5d0cafc 1020 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?cmid=$cm->id&amp;id=$entry->id&amp;mode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
81bdc9e9 1021 } elseif ( $importedentry ) {
41905731 1022 $return .= " <font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
81bdc9e9 1023 }
1024 }
86a3996d 1025 if (has_capability('mod/glossary:exportentry', $context)
1026 || ($entry->userid == $USER->id
1027 && has_capability('mod/glossary:exportownentry', $context))) {
24ba58ee 1028 require_once($CFG->libdir . '/portfoliolib.php');
0d06b6fd 1029 $button = new portfolio_add_button();
24ba58ee 1030 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id, 'entryid' => $entry->id), '/mod/glossary/locallib.php');
59dd457e
PL
1031
1032 $filecontext = $context;
1033 if ($entry->sourceglossaryid == $cm->instance) {
1034 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1035 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1036 }
1037 }
1038 $fs = get_file_storage();
64f93798 1039 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
59dd457e 1040 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
24ba58ee
PL
1041 } else {
1042 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
59dd457e
PL
1043 }
1044
0d06b6fd 1045 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
49a12552 1046 }
81bdc9e9 1047 $return .= "&nbsp;&nbsp;"; // just to make up a little the output in Mozilla ;)
36ce6ea2 1048
9362b9b6 1049 $return .= '</span>';
a02c77dc 1050
c8092ea5
DC
1051 if (has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
1052 $output = true;
1053 if (!empty($CFG->usecomments)) {
36051c9e 1054 require_once($CFG->dirroot . '/comment/lib.php');
c8092ea5 1055 $cmt = new stdclass;
d846488e 1056 $cmt->component = 'mod_glossary';
866354a9 1057 $cmt->context = $context;
28925062 1058 $cmt->course = $course;
866354a9
DC
1059 $cmt->cm = $cm;
1060 $cmt->area = 'glossary_entry';
1061 $cmt->itemid = $entry->id;
c8092ea5
DC
1062 $cmt->showcount = true;
1063 $comment = new comment($cmt);
866354a9 1064 $return .= '<div>'.$comment->output(true).'</div>';
c8092ea5
DC
1065 }
1066 }
1067
36ce6ea2 1068 //If we haven't calculated any REAL thing, delete result ($return)
1069 if (!$output) {
1070 $return = '';
1071 }
1072 //Print or get
1ac87c73 1073 if ($type == 'print') {
81bdc9e9 1074 echo $return;
1075 } else {
1076 return $return;
a0d1e2bb 1077 }
1078}
1079
e121db76 1080/**
1081 * @param object $course
1082 * @param object $cm
1083 * @param object $glossary
1084 * @param object $entry
1085 * @param string $mode
1086 * @param object $hook
1087 * @param bool $printicons
e121db76 1088 * @param bool $aliases
63e87951 1089 * @return void
e121db76 1090 */
63e87951 1091function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
26983d03 1092 if ($aliases) {
9362b9b6 1093 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
26983d03 1094 }
9362b9b6 1095 $icons = '';
cbc2b5df 1096 if ($printicons) {
9362b9b6 1097 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1ac87c73 1098 }
15dd3edb 1099 if ($aliases || $icons || !empty($entry->rating)) {
9362b9b6 1100 echo '<table>';
a359c29b 1101 if ( $aliases ) {
9362b9b6 1102 echo '<tr valign="top"><td class="aliases">' .
1103 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
a359c29b 1104 }
1105 if ($icons) {
9362b9b6 1106 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
a359c29b 1107 }
198ff498 1108 if (!empty($entry->rating)) {
9362b9b6 1109 echo '<tr valign="top"><td class="ratings">';
63e87951 1110 glossary_print_entry_ratings($course, $entry);
a359c29b 1111 echo '</td></tr>';
1112 }
1113 echo '</table>';
81bdc9e9 1114 }
1115}
1116
e121db76 1117/**
1118 * @todo Document this function
1119 */
49bcd737 1120function glossary_print_entry_attachment($entry, $cm, $format=NULL, $align="right", $insidetable=true) {
1d9ddaaf 1121/// valid format values: html : Return the HTML link for the attachment as an icon
1122/// text : Return the HTML link for tha attachment as text
1123/// blank : Print the output to the screen
1124 if ($entry->attachment) {
77495793 1125 if ($insidetable) {
41905731 1126 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
77495793 1127 }
49bcd737 1128 echo glossary_print_attachments($entry, $cm, $format, $align);
77495793 1129 if ($insidetable) {
1130 echo "</td></tr></table>\n";
1131 }
1d9ddaaf 1132 }
1133}
1134
e121db76 1135/**
1136 * @global object
1137 * @param object $cm
1138 * @param object $entry
1139 * @param string $mode
1140 * @param string $align
1141 * @param bool $insidetable
1142 */
cbc2b5df 1143function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
f2a1963c 1144 global $CFG, $OUTPUT;
cff611fc 1145
cbc2b5df 1146 if ($mode == 'approval' and !$entry->approved) {
77495793 1147 if ($insidetable) {
a8466100 1148 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
77495793 1149 }
b5d0cafc 1150 echo '<a title="'.get_string('approve','glossary').'" href="approve.php?eid='.$entry->id.'&amp;mode='.$mode.'&amp;sesskey='.sesskey().'"><img align="'.$align.'" src="'.$OUTPUT->pix_url('i/approve') . '" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
77495793 1151 if ($insidetable) {
a8466100 1152 echo '</td></tr></table>';
77495793 1153 }
1d9ddaaf 1154 }
1155}
07842023 1156
e121db76 1157/**
1158 * It returns all entries from all glossaries that matches the specified criteria
1159 * within a given $course. It performs an $extended search if necessary.
1160 * It restrict the search to only one $glossary if the $glossary parameter is set.
1161 *
1162 * @global object
1163 * @global object
1164 * @param object $course
1165 * @param array $searchterms
1166 * @param int $extended
1167 * @param object $glossary
1168 * @return array
1169 */
c80828fe 1170function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
ae8c3566 1171 global $CFG, $DB;
07842023 1172
c80828fe 1173 if ( !$glossary ) {
ae8c3566 1174 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
c80828fe 1175 $glos = "";
1176 foreach ( $glossaries as $glossary ) {
1177 $glos .= "$glossary->id,";
1178 }
9cae3799 1179 $glos = substr($glos,0,-1);
c80828fe 1180 }
1181 } else {
1182 $glos = $glossary->id;
1183 }
a02c77dc 1184
81e956b9 1185 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $glossary->course))) {
ae8c3566 1186 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
6a22879b 1187 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
ae8c3566 1188 $onlyvisibletable = ", {course_modules} cm";
07842023 1189 } else {
1190
1191 $onlyvisible = "";
1192 $onlyvisibletable = "";
1193 }
1194
ae8c3566 1195 if ($DB->sql_regex_supported()) {
1196 $REGEXP = $DB->sql_regex(true);
1197 $NOTREGEXP = $DB->sql_regex(false);
a02c77dc 1198 }
07842023 1199
ae8c3566 1200 $searchcond = array();
1201 $params = array();
1202 $i = 0;
1203
1204 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
07842023 1205
1206
1207 foreach ($searchterms as $searchterm) {
ae8c3566 1208 $i++;
1209
e99cfeb8 1210 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
ae8c3566 1211 /// will use it to simulate the "-" operator with LIKE clause
07842023 1212
6f4bdb9c 1213 /// Under Oracle and MSSQL, trim the + and - operators and perform
ae8c3566 1214 /// simpler LIKE (or NOT LIKE) queries
1215 if (!$DB->sql_regex_supported()) {
1216 if (substr($searchterm, 0, 1) == '-') {
e99cfeb8 1217 $NOT = true;
ae8c3566 1218 }
6f4bdb9c 1219 $searchterm = trim($searchterm, '+-');
1220 }
1221
ae8c3566 1222 // TODO: +- may not work for non latin languages
1223
1224 if (substr($searchterm,0,1) == '+') {
1225 $searchterm = trim($searchterm, '+-');
1226 $searchterm = preg_quote($searchterm, '|');
1227 $searchcond[] = "$concat $REGEXP :ss$i";
1228 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1229
07842023 1230 } else if (substr($searchterm,0,1) == "-") {
ae8c3566 1231 $searchterm = trim($searchterm, '+-');
1232 $searchterm = preg_quote($searchterm, '|');
1233 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1234 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1235
07842023 1236 } else {
47586394 1237 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
ae8c3566 1238 $params['ss'.$i] = "%$searchterm%";
07842023 1239 }
1240 }
1241
ae8c3566 1242 if (empty($searchcond)) {
1243 $totalcount = 0;
1244 return array();
1245 }
1246
1247 $searchcond = implode(" AND ", $searchcond);
07842023 1248
ae8c3566 1249 $sql = "SELECT e.*
1250 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1251 WHERE $searchcond
ad58adac 1252 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
ae8c3566 1253 AND g.id IN ($glos) AND e.approved <> 0";
07842023 1254
ae8c3566 1255 return $DB->get_records_sql($sql, $params);
07842023 1256}
1257
e121db76 1258/**
1259 * @global object
1260 * @param array $searchterms
1261 * @param object $glossary
1262 * @param bool $extended
1263 * @return array
1264 */
c80828fe 1265function glossary_search_entries($searchterms, $glossary, $extended) {
ae8c3566 1266 global $DB;
1267
1268 $course = $DB->get_record("course", array("id"=>$glossary->course));
c80828fe 1269 return glossary_search($course,$searchterms,$extended,$glossary);
1270}
1271
49bcd737 1272/**
1273 * if return=html, then return a html string.
1274 * if return=text, then return a text-only string.
1275 * otherwise, print HTML for non-images, and return image HTML
1276 * if attachment is an image, $align set its aligment.
e121db76 1277 *
1278 * @global object
1279 * @global object
49bcd737 1280 * @param object $entry
1281 * @param object $cm
1282 * @param string $type html, txt, empty
1283 * @param string $align left or right
e121db76 1284 * @return string image string or nothing depending on $type param
49bcd737 1285 */
1286function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") {
d436d197 1287 global $CFG, $DB, $OUTPUT;
e179048e 1288
49bcd737 1289 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
1290 return '';
e179048e 1291 }
a02c77dc 1292
ca3d4806
SM
1293 if ($entry->sourceglossaryid == $cm->instance) {
1294 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
49bcd737 1295 return '';
a02c77dc 1296 }
49bcd737 1297 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
e179048e 1298
49bcd737 1299 } else {
1300 $filecontext = $context;
1301 }
e179048e 1302
49bcd737 1303 $strattachment = get_string('attachment', 'glossary');
e179048e 1304
49bcd737 1305 $fs = get_file_storage();
e179048e 1306
49bcd737 1307 $imagereturn = '';
1308 $output = '';
e179048e 1309
64f93798 1310 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
49bcd737 1311 foreach ($files as $file) {
1312 $filename = $file->get_filename();
1313 $mimetype = $file->get_mimetype();
b5d0cafc 1314 $iconimage = '<img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />';
64f93798 1315 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_glossary/attachment/'.$entry->id.'/'.$filename);
e179048e 1316
49bcd737 1317 if ($type == 'html') {
1318 $output .= "<a href=\"$path\">$iconimage</a> ";
1319 $output .= "<a href=\"$path\">".s($filename)."</a>";
1320 $output .= "<br />";
18b8fbfa 1321
49bcd737 1322 } else if ($type == 'text') {
1323 $output .= "$strattachment ".s($filename).":\n$path\n";
e179048e 1324
49bcd737 1325 } else {
1326 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1327 // Image attachments don't get printed as links
1328 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1329 } else {
1330 $output .= "<a href=\"$path\">$iconimage</a> ";
35716b86 1331 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
49bcd737 1332 $output .= '<br />';
18b8fbfa 1333 }
e179048e 1334 }
1335 }
1336 }
49bcd737 1337
1338 if ($type) {
1339 return $output;
1340 } else {
1341 echo $output;
1342 return $imagereturn;
1343 }
e179048e 1344}
1345
aa9bcfcd 1346/**
1347 * Lists all browsable file areas
e121db76 1348 *
1349 * @param object $course
1350 * @param object $cm
1351 * @param object $context
1352 * @return array
aa9bcfcd 1353 */
1354function glossary_get_file_areas($course, $cm, $context) {
1355 $areas = array();
aa9bcfcd 1356 return $areas;
1357}
1358
49bcd737 1359/**
1360 * Serves the glossary attachments. Implements needed access control ;-)
e121db76 1361 *
98edf7b6 1362 * @param object $course
64f93798 1363 * @param object $cm
98edf7b6 1364 * @param object $context
1365 * @param string $filearea
1366 * @param array $args
1367 * @param bool $forcedownload
86900a93 1368 * @return bool false if file not found, does not return if found - justsend the file
49bcd737 1369 */
64f93798 1370function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
49bcd737 1371 global $CFG, $DB;
a02c77dc 1372
64f93798 1373 if ($context->contextlevel != CONTEXT_MODULE) {
49bcd737 1374 return false;
1375 }
e179048e 1376
64f93798 1377 require_course_login($course, true, $cm);
49bcd737 1378
64f93798
PS
1379 if ($filearea === 'attachment' or $filearea === 'entry') {
1380 $entryid = (int)array_shift($args);
0a8a7b6c 1381
1382 require_course_login($course, true, $cm);
1adbd2c3 1383
aa9bcfcd 1384 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1385 return false;
e179048e 1386 }
49bcd737 1387
64f93798 1388 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
aa9bcfcd 1389 return false;
1390 }
e179048e 1391
aa9bcfcd 1392 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1393 return false;
1394 }
1395
64f93798
PS
1396 // this trickery here is because we need to support source glossary access
1397
1398 if ($entry->glossaryid == $cm->instance) {
aa9bcfcd 1399 $filecontext = $context;
1400
64f93798 1401 } else if ($entry->sourceglossaryid == $cm->instance) {
aa9bcfcd 1402 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
64f93798 1403 return false;
aa9bcfcd 1404 }
1405 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1406
1407 } else {
1408 return false;
1409 }
1410
64f93798
PS
1411 $relativepath = implode('/', $args);
1412 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
aa9bcfcd 1413
1414 $fs = get_file_storage();
1415 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1416 return false;
1417 }
1418
1419 // finally send the file
1420 send_stored_file($file, 0, 0, true); // download MUST be forced - security!
1ca1c8f8
PS
1421
1422 } else if ($filearea === 'export') {
1423 require_login($course, false, $cm);
1424 require_capability('mod/glossary:export', $context);
1425
1426 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1427 return false;
1428 }
1429
1430 $cat = array_shift($args);
1431 $cat = clean_param($cat, PARAM_ALPHANUM);
1432
1433 $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
1434 $content = glossary_generate_export_file($glossary, NULL, $cat);
1435
1436 send_file($content, $filename, 0, 0, true, true);
e179048e 1437 }
1438
aa9bcfcd 1439 return false;
e179048e 1440}
1441
e121db76 1442/**
1443 *
1444 */
ad58adac 1445function glossary_print_tabbed_table_end() {
9ca8cc08 1446 echo "</div></div>";
06d94a52 1447}
1448
e121db76 1449/**
1450 * @param object $cm
1451 * @param object $glossary
1452 * @param string $mode
1453 * @param string $hook
1454 * @param string $sortkey
1455 * @param string $sortorder
1456 */
1ac87c73 1457function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1458 if ($glossary->showalphabet) {
7a3ec1af 1459 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
677038ee 1460 }
1ac87c73 1461 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1462
c4a35419 1463 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
c76e673a 1464
1ac87c73 1465 glossary_print_all_links($cm, $glossary, $mode, $hook);
894ff63f 1466
db87439a 1467 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
c76e673a 1468}
e121db76 1469/**
1470 * @param object $cm
1471 * @param object $glossary
1472 * @param string $hook
1473 * @param string $sortkey
1474 * @param string $sortorder
1475 */
1ac87c73 1476function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1477 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
748b1932 1478}
1479
e121db76 1480/**
1481 * @param object $cm
1482 * @param object $glossary
1483 * @param string $hook
1484 * @param string $sortkey
1485 * @param string $sortorder
1486 */
1ac87c73 1487function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1488 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
748b1932 1489}
e121db76 1490/**
1491 * @param object $cm
1492 * @param object $glossary
1493 * @param string $hook
1494 * @param string $sortkey
1495 * @param string $sortorder
1496 */
1ac87c73 1497function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1498 if ( $mode != 'date' ) {
a359c29b 1499 if ($glossary->showalphabet) {
7a3ec1af 1500 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1501 }
c76e673a 1502
1ac87c73 1503 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1504
c4a35419 1505 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
c197e607 1506
1ac87c73 1507 glossary_print_all_links($cm, $glossary, $mode, $hook);
c197e607 1508 } else {
1ac87c73 1509 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1510 }
1511}
1512
e121db76 1513/**
1514 * @param object $cm
1515 * @param object $glossary
1516 * @param string $hook
1517 * @param string $sortkey
1518 * @param string $sortorder
1519 */
1ac87c73 1520function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1521 if ($glossary->showalphabet) {
7a3ec1af 1522 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1523 }
1ac87c73 1524
c4a35419 1525 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1ac87c73 1526 glossary_print_all_links($cm, $glossary, $mode, $hook);
7a3ec1af 1527 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
c76e673a 1528}
1529
e121db76 1530/**
1531 * @global object
1532 * @global object
1533 * @param object $cm
1534 * @param object $glossary
1535 * @param string $hook
1536 * @param object $category
1537 */
1ac87c73 1538function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
c9472f43 1539 global $CFG, $DB, $OUTPUT;
a02c77dc 1540
dabfd0ed 1541 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3a26f0ea 1542
41905731 1543 echo '<table border="0" width="100%">';
c197e607 1544 echo '<tr>';
c76e673a 1545
5bd76d7f 1546 echo '<td align="center" style="width:20%">';
0468976c 1547 if (has_capability('mod/glossary:managecategories', $context)) {
c76e673a 1548 $options['id'] = $cm->id;
1ac87c73 1549 $options['mode'] = 'cat';
1550 $options['hook'] = $hook;
5c2ed7e2 1551 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
c76e673a 1552 }
c197e607 1553 echo '</td>';
c76e673a 1554
5bd76d7f 1555 echo '<td align="center" style="width:60%">';
c197e607 1556 echo '<b>';
c76e673a 1557
f8dab966 1558 $menu = array();
c76e673a 1559 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1560 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
677038ee 1561
ae8c3566 1562 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
c197e607 1563 $selected = '';
c76e673a 1564 if ( $categories ) {
1565 foreach ($categories as $currentcategory) {
1566 $url = $currentcategory->id;
1567 if ( $category ) {
1568 if ($currentcategory->id == $category->id) {
1569 $selected = $url;
1570 }
1571 }
ae06e00e 1572 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
c76e673a 1573 }
1574 }
1575 if ( !$selected ) {
1576 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1577 }
1578
1579 if ( $category ) {
5bd76d7f 1580 echo format_text($category->name, FORMAT_PLAIN);
c76e673a 1581 } else {
1ac87c73 1582 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
c76e673a 1583
1584 echo get_string("entrieswithoutcategory","glossary");
1585 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1586
1ac87c73 1587 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
c76e673a 1588
1589 echo get_string("allcategories","glossary");
1590 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1591
1592 }
1593 }
c197e607 1594 echo '</b></td>';
5bd76d7f 1595 echo '<td align="center" style="width:20%">';
1adbd2c3 1596
f8dab966
PS
1597 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1598 echo $OUTPUT->render($select);
677038ee 1599
c197e607 1600 echo '</td>';
1601 echo '</tr>';
c76e673a 1602
c197e607 1603 echo '</table>';
c76e673a 1604}
1605
e121db76 1606/**
1607 * @global object
1608 * @param object $cm
1609 * @param object $glossary
1610 * @param string $mode
1611 * @param string $hook
1612 */
1ac87c73 1613function glossary_print_all_links($cm, $glossary, $mode, $hook) {
a02c77dc 1614global $CFG;
a359c29b 1615 if ( $glossary->showall) {
c76e673a 1616 $strallentries = get_string("allentries", "glossary");
1ac87c73 1617 if ( $hook == 'ALL' ) {
c76e673a 1618 echo "<b>$strallentries</b>";
1619 } else {
1620 $strexplainall = strip_tags(get_string("explainall","glossary"));
839f2456 1621 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
c76e673a 1622 }
1623 }
1624}
1625
e121db76 1626/**
1627 * @global object
1628 * @param object $cm
1629 * @param object $glossary
1630 * @param string $mode
1631 * @param string $hook
1632 */
1ac87c73 1633function glossary_print_special_links($cm, $glossary, $mode, $hook) {
c76e673a 1634global $CFG;
a359c29b 1635 if ( $glossary->showspecial) {
c76e673a 1636 $strspecial = get_string("special", "glossary");
1ac87c73 1637 if ( $hook == 'SPECIAL' ) {
677038ee 1638 echo "<b>$strspecial</b> | ";
1639 } else {
1640 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
839f2456 1641 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
677038ee 1642 }
914cb260 1643 }
c76e673a 1644}
677038ee 1645
e121db76 1646/**
1647 * @global object
1648 * @param object $glossary
1649 * @param string $mode
1650 * @param string $hook
1651 * @param string $sortkey
1652 * @param string $sortorder
1653 */
c4a35419 1654function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
c76e673a 1655global $CFG;
a359c29b 1656 if ( $glossary->showalphabet) {
9b22ac0a 1657 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
677038ee 1658 for ($i = 0; $i < count($alphabet); $i++) {
1ac87c73 1659 if ( $hook == $alphabet[$i] and $hook) {
677038ee 1660 echo "<b>$alphabet[$i]</b>";
1661 } else {
82015ed2 1662 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 1663 }
4ce27469 1664 echo ' | ';
767a31c3 1665 }
677038ee 1666 }
c76e673a 1667}
1668
e121db76 1669/**
1670 * @global object
1671 * @param object $cm
1672 * @param string $mode
1673 * @param string $sortkey
1674 * @param string $sortorder
1675 */
1ac87c73 1676function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
eaed2fd1 1677 global $CFG, $OUTPUT;
677038ee 1678
c4a35419 1679 $asc = get_string("ascending","glossary");
1680 $desc = get_string("descending","glossary");
1681 $bopen = '<b>';
1682 $bclose = '</b>';
a02c77dc 1683
c197e607 1684 $neworder = '';
468c120a 1685 $currentorder = '';
1686 $currentsort = '';
677038ee 1687 if ( $sortorder ) {
c197e607 1688 if ( $sortorder == 'asc' ) {
468c120a 1689 $currentorder = $asc;
839f2456 1690 $neworder = '&amp;sortorder=desc';
468c120a 1691 $newordertitle = get_string('changeto', 'glossary', $desc);
677038ee 1692 } else {
468c120a 1693 $currentorder = $desc;
839f2456 1694 $neworder = '&amp;sortorder=asc';
468c120a 1695 $newordertitle = get_string('changeto', 'glossary', $asc);
677038ee 1696 }
b5d0cafc 1697 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
677038ee 1698 } else {
c4a35419 1699 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1700 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
677038ee 1701 $icon = "";
c4a35419 1702 $newordertitle = $asc;
677038ee 1703 } else {
c4a35419 1704 $newordertitle = $desc;
839f2456 1705 $neworder = '&amp;sortorder=desc';
b5d0cafc 1706 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
677038ee 1707 }
1708 }
c4a35419 1709 $ficon = '';
1710 $fneworder = '';
1711 $fbtag = '';
1712 $fendbtag = '';
1713
1714 $sicon = '';
1715 $sneworder = '';
ae078733 1716
1717 $sbtag = '';
1718 $fbtag = '';
1719 $fendbtag = '';
1720 $sendbtag = '';
1721
c4a35419 1722 $sendbtag = '';
1723
1724 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1725 $ficon = $icon;
1726 $fneworder = $neworder;
1727 $fordertitle = $newordertitle;
1728 $sordertitle = $asc;
1729 $fbtag = $bopen;
1730 $fendbtag = $bclose;
1731 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1732 $sicon = $icon;
1733 $sneworder = $neworder;
1734 $fordertitle = $asc;
1735 $sordertitle = $newordertitle;
1736 $sbtag = $bopen;
1737 $sendbtag = $bclose;
677038ee 1738 } else {
c4a35419 1739 $fordertitle = $asc;
1740 $sordertitle = $asc;
677038ee 1741 }
c4a35419 1742
1743 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1744 $forder = 'CREATION';
1745 $sorder = 'UPDATE';
1746 $fsort = get_string("sortbycreation", "glossary");
1747 $ssort = get_string("sortbylastupdate", "glossary");
1748
468c120a 1749 $currentsort = $fsort;
1750 if ($sortkey == 'UPDATE') {
1751 $currentsort = $ssort;
1752 }
c4a35419 1753 $sort = get_string("sortchronogically", "glossary");
1754 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1755 $forder = 'FIRSTNAME';
1756 $sorder = 'LASTNAME';
1757 $fsort = get_string("firstname");
1758 $ssort = get_string("lastname");
1759
468c120a 1760 $currentsort = $fsort;
1761 if ($sortkey == 'LASTNAME') {
1762 $currentsort = $ssort;
1763 }
c4a35419 1764 $sort = get_string("sortby", "glossary");
1765 }
468c120a 1766 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1767 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 1768 "$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 1769}
ad58adac 1770
e121db76 1771/**
1772 *
1773 * @param object $entry0
1774 * @param object $entry1
1775 * @return int [-1 | 0 | 1]
1776 */
ad58adac 1777function glossary_sort_entries ( $entry0, $entry1 ) {
a02c77dc 1778
95d56829 1779 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1780 return -1;
95d56829 1781 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
ad58adac 1782 return 1;
1783 } else {
1784 return 0;
1785 }
1786}
1787
ed0201dd 1788
e121db76 1789/**
1790 * @global object
1791 * @global object
1792 * @global object
1793 * @param object $course
1794 * @param object $entry
e121db76 1795 * @return bool
1796 */
63e87951 1797function glossary_print_entry_ratings($course, $entry) {
63e87951
AD
1798 global $OUTPUT;
1799 if( !empty($entry->rating) ){
1800 echo $OUTPUT->render($entry->rating);
1801 }
63dd5fb2 1802}
1803
e121db76 1804/**
1805 *
1806 * @global object
1807 * @global object
1808 * @global object
1809 * @param int $courseid
1810 * @param array $entries
1811 * @param int $displayformat
1812 */
b1918034 1813function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
ae8c3566 1814 global $USER,$CFG, $DB;
cca6f7f1 1815
36a2b6bd 1816 echo '<div class="boxaligncenter">';
a8466100 1817 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1818 echo '<td>';
1d9ddaaf 1819 if ( $entries ) {
1820 foreach ( $entries as $entry ) {
ae8c3566 1821 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
5973a4c4 1822 print_error('invalidid', 'glossary');
cca6f7f1 1823 }
ae8c3566 1824 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
5973a4c4 1825 print_error('coursemisconf');
1d9ddaaf 1826 }
a8466100 1827 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
5973a4c4 1828 print_error('invalidid', 'glossary');
1d9ddaaf 1829 }
1f63b7c6 1830
1831 //If displayformat is present, override glossary->displayformat
a359c29b 1832 if ($displayformat < 0) {
1f63b7c6 1833 $dp = $glossary->displayformat;
a359c29b 1834 } else {
1f63b7c6 1835 $dp = $displayformat;
1836 }
1837
a359c29b 1838 //Get popupformatname
ae8c3566 1839 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
a359c29b 1840 $displayformat = $format->popupformatname;
1841
1842 //Check displayformat variable and set to default if necessary
1843 if (!$displayformat) {
1844 $displayformat = 'dictionary';
584dcac9 1845 }
1f63b7c6 1846
a359c29b 1847 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1848 $functionname = 'glossary_show_entry_'.$displayformat;
1849
1850 if (file_exists($formatfile)) {
1851 include_once($formatfile);
1852 if (function_exists($functionname)) {
1853 $functionname($course, $cm, $glossary, $entry,'','','','');
1854 }
1855 }
cca6f7f1 1856 }
cca6f7f1 1857 }
a8466100 1858 echo '</td>';
36a2b6bd 1859 echo '</tr></table></div>';
1d9ddaaf 1860}
4f4ca7b5 1861
e121db76 1862/**
1863 *
1864 * @global object
1865 * @param array $entries
1866 * @param array $aliases
1867 * @param array $categories
1868 * @return string
1869 */
6c0a9413 1870function glossary_generate_export_csv($entries, $aliases, $categories) {
1871 global $CFG;
1872 $csv = '';
1873 $delimiter = '';
1874 require_once($CFG->libdir . '/csvlib.class.php');
1875 $delimiter = csv_import_reader::get_delimiter('comma');
1876 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
1877 $csvaliases = array(0 => array());
1878 $csvcategories = array(0 => array());
1879 $aliascount = 0;
1880 $categorycount = 0;
1881
1882 foreach ($entries as $entry) {
1883 $thisaliasesentry = array();
1884 $thiscategoriesentry = array();
cbc2b5df 1885 $thiscsventry = array($entry->concept, nl2br($entry->definition));
6c0a9413 1886
1887 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
1888 $thiscount = count($aliases[$entry->id]);
1889 if ($thiscount > $aliascount) {
1890 $aliascount = $thiscount;
1891 }
1892 foreach ($aliases[$entry->id] as $alias) {
1893 $thisaliasesentry[] = trim($alias);
1894 }
1895 }
1896 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
1897 $thiscount = count($categories[$entry->id]);
1898 if ($thiscount > $categorycount) {
1899 $categorycount = $thiscount;
1900 }
1901 foreach ($categories[$entry->id] as $catentry) {
1902 $thiscategoriesentry[] = trim($catentry);
1903 }
1904 }
1905 $csventries[$entry->id] = $thiscsventry;
1906 $csvaliases[$entry->id] = $thisaliasesentry;
1907 $csvcategories[$entry->id] = $thiscategoriesentry;
1908
1909 }
1910 $returnstr = '';
1911 foreach ($csventries as $id => $row) {
1912 $aliasstr = '';
1913 $categorystr = '';
1914 if ($id == 0) {
1915 $aliasstr = get_string('alias', 'glossary');
1916 $categorystr = get_string('category', 'glossary');
1917 }
1918 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
1919 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
1920 }
1921 return $returnstr;
1922}
1923
e121db76 1924/**
1ca1c8f8 1925 *
e121db76 1926 * @param object $glossary
1ca1c8f8
PS
1927 * @param string $ignored invalid parameter
1928 * @param int|string $hook
e121db76 1929 * @return string
1930 */
1ca1c8f8 1931function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
ae8c3566 1932 global $CFG, $DB;
212039c0 1933
1934 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1935
1936 $co .= glossary_start_tag("GLOSSARY",0,true);
1937 $co .= glossary_start_tag("INFO",1,true);
1938 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
1939 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
72c4be39 1940 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
212039c0 1941 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
1942 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
1943 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
1944 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
1945 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
1946 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
1947 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
1948 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
1949 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
1950 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
4f4ca7b5 1951
ae8c3566 1952 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
212039c0 1953 $co .= glossary_start_tag("ENTRIES",2,true);
748b1932 1954 foreach ($entries as $entry) {
046a797c 1955 $permissiongranted = 1;
1ac87c73 1956 if ( $hook ) {
1957 switch ( $hook ) {
046a797c 1958 case "ALL":
1959 case "SPECIAL":
1960 break;
1961 default:
1ac87c73 1962 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
046a797c 1963 break;
1964 }
1965 }
1ac87c73 1966 if ( $hook ) {
1967 switch ( $hook ) {
046a797c 1968 case GLOSSARY_SHOW_ALL_CATEGORIES:
1969 break;
1970 case GLOSSARY_SHOW_NOT_CATEGORISED:
ae8c3566 1971 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
046a797c 1972 break;
1973 default:
ae8c3566 1974 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
046a797c 1975 break;
1976 }
1977 }
1978 if ( $entry->approved and $permissiongranted ) {
212039c0 1979 $co .= glossary_start_tag("ENTRY",3,true);
1980 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
cbc2b5df 1981 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
72c4be39 1982 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
212039c0 1983 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
1984 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
1985 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
1986 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
748b1932 1987
ae8c3566 1988 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
212039c0 1989 $co .= glossary_start_tag("ALIASES",4,true);
7965be79 1990 foreach ($aliases as $alias) {
212039c0 1991 $co .= glossary_start_tag("ALIAS",5,true);
1992 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
1993 $co .= glossary_end_tag("ALIAS",5,true);
7965be79 1994 }
212039c0 1995 $co .= glossary_end_tag("ALIASES",4,true);
7965be79 1996 }
ae8c3566 1997 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
212039c0 1998 $co .= glossary_start_tag("CATEGORIES",4,true);
748b1932 1999 foreach ($catentries as $catentry) {
ae8c3566 2000 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
748b1932 2001
212039c0 2002 $co .= glossary_start_tag("CATEGORY",5,true);
2003 $co .= glossary_full_tag("NAME",6,false,$category->name);
2004 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2005 $co .= glossary_end_tag("CATEGORY",5,true);
748b1932 2006 }
212039c0 2007 $co .= glossary_end_tag("CATEGORIES",4,true);
748b1932 2008 }
4f4ca7b5 2009
212039c0 2010 $co .= glossary_end_tag("ENTRY",3,true);
4f4ca7b5 2011 }
2012 }
212039c0 2013 $co .= glossary_end_tag("ENTRIES",2,true);
748b1932 2014
4f4ca7b5 2015 }
748b1932 2016
2017
212039c0 2018 $co .= glossary_end_tag("INFO",1,true);
2019 $co .= glossary_end_tag("GLOSSARY",0,true);
4f4ca7b5 2020
212039c0 2021 return $co;
4f4ca7b5 2022}
212039c0 2023/// Functions designed by Eloy Lafuente
2024/// Functions to create, open and write header of the xml file
4f4ca7b5 2025
e121db76 2026/**
2027 * Read import file and convert to current charset
2028 *
2029 * @global object
2030 * @param string $file
2031 * @return string
2032 */
b61e3e80 2033function glossary_read_imported_file($file_content) {
9f79b50f 2034 require_once "../../lib/xmlize.php";
2035 global $CFG;
2036
b61e3e80 2037 return xmlize($file_content, 0);
748b1932 2038}
4f4ca7b5 2039
e121db76 2040/**
2041 * Return the xml start tag
2042 *
2043 * @param string $tag
2044 * @param int $level
2045 * @param bool $endline
2046 * @return string
2047 */
4f4ca7b5 2048function glossary_start_tag($tag,$level=0,$endline=false) {
2049 if ($endline) {
2050 $endchar = "\n";
2051 } else {
2052 $endchar = "";
2053 }
2054 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2055}
a02c77dc 2056
e121db76 2057/**
2058 * Return the xml end tag
2059 * @param string $tag
2060 * @param int $level
2061 * @param bool $endline
2062 * @return string
2063 */
4f4ca7b5 2064function glossary_end_tag($tag,$level=0,$endline=true) {
2065 if ($endline) {
2066 $endchar = "\n";
2067 } else {
2068 $endchar = "";
2069 }
2070 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2071}
a02c77dc 2072
e121db76 2073/**
2074 * Return the start tag, the contents and the end tag
2075 *
2076 * @global object
2077 * @param string $tag
2078 * @param int $level
2079 * @param bool $endline
2080 * @param string $content
2081 * @return string
2082 */
212039c0 2083function glossary_full_tag($tag,$level=0,$endline=true,$content) {
9f79b50f 2084 global $CFG;
a02c77dc 2085
4f4ca7b5 2086 $st = glossary_start_tag($tag,$level,$endline);
212039c0 2087 $co = preg_replace("/\r\n|\r/", "\n", s($content));
4f4ca7b5 2088 $et = glossary_end_tag($tag,0,true);
2089 return $st.$co.$et;
2090}
2091
e121db76 2092/**
2093 * How many unrated entries are in the given glossary for a given user?
2094 *
2095 * @global object
2096 * @param int $glossaryid
2097 * @param int $userid
2098 * @return int
2099 */
63dd5fb2 2100function glossary_count_unrated_entries($glossaryid, $userid) {
ae8c3566 2101 global $DB;
2102 if ($entries = $DB->get_record_sql("SELECT count('x') as num
2103 FROM {glossary_entries}
2104 WHERE glossaryid = ? AND userid <> ?", array($glossaryid, $userid))) {
2105
2e4b4fc0
AD
2106 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2107 return 0;
2108 }
2109 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
427711b1 2110
ae8c3566 2111 if ($rated = $DB->get_record_sql("SELECT count(*) as num
2e4b4fc0
AD
2112 FROM {glossary_entries} e, {ratings} r
2113 WHERE e.glossaryid = :glossaryid AND e.id = r.itemid
427711b1 2114 AND r.userid = :userid and r.contextid = :contextid",
2e4b4fc0
AD
2115 array('glossaryid'=>$glossaryid, 'userid'=>$userid, 'contextid'=>$context->id))) {
2116
63dd5fb2 2117 $difference = $entries->num - $rated->num;
2118 if ($difference > 0) {
2119 return $difference;
2120 } else {
2121 return 0; // Just in case there was a counting error
2122 }
2123 } else {
2124 return $entries->num;
2125 }
2126 } else {
2127 return 0;
2128 }
2129}
2130
e121db76 2131/**
2132 *
2133 * Returns the html code to represent any pagging bar. Paramenters are:
2134 *
2135 * The function dinamically show the first and last pages, and "scroll" over pages.
2136 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2137 * could replace the general one. ;-)
2138 *
2139 * @param int $totalcount total number of records to be displayed
2140 * @param int $page page currently selected (0 based)
2141 * @param int $perpage number of records per page
2142 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
1adbd2c3 2143 *
e121db76 2144 * @param int $maxpageallowed Optional maximum number of page allowed.
2145 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2146 * @param string $separator Optional string to be used between pages in the bar
2147 * @param string $specialtext Optional string to be showed as an special link
2148 * @param string $specialvalue Optional value (page) to be used in the special link
2149 * @param bool $previousandnext Optional to decide if we want the previous and next links
2150 * @return string
2151 */
e2cf5316 2152function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
e2cf5316 2153
2154 $code = '';
2155
2156 $showspecial = false;
2157 $specialselected = false;
2158
2159 //Check if we have to show the special link
2160 if (!empty($specialtext)) {
2161 $showspecial = true;
2162 }
2163 //Check if we are with the special link selected
2164 if ($showspecial && $page == $specialvalue) {
2165 $specialselected = true;
a02c77dc 2166 }
e2cf5316 2167
2168 //If there are results (more than 1 page)
2169 if ($totalcount > $perpage) {
36a2b6bd 2170 $code .= "<div style=\"text-align:center\">";
e2cf5316 2171 $code .= "<p>".get_string("page").":";
2172
2173 $maxpage = (int)(($totalcount-1)/$perpage);
2174
2175 //Lower and upper limit of page
2176 if ($page < 0) {
2177 $page = 0;
2178 }
2179 if ($page > $maxpageallowed) {
2180 $page = $maxpageallowed;
2181 }
2182 if ($page > $maxpage) {
2183 $page = $maxpage;
2184 }
2185
2186 //Calculate the window of pages
2187 $pagefrom = $page - ((int)($maxdisplay / 2));
2188 if ($pagefrom < 0) {
2189 $pagefrom = 0;
2190 }
2191 $pageto = $pagefrom + $maxdisplay - 1;
2192 if ($pageto > $maxpageallowed) {
2193 $pageto = $maxpageallowed;
2194 }
2195 if ($pageto > $maxpage) {
2196 $pageto = $maxpage;
2197 }
2198
2199 //Some movements can be necessary if don't see enought pages
2200 if ($pageto - $pagefrom < $maxdisplay - 1) {
2201 if ($pageto - $maxdisplay + 1 > 0) {
2202 $pagefrom = $pageto - $maxdisplay + 1;
2203 }
2204 }
2205
2206 //Calculate first and last if necessary
2207 $firstpagecode = '';
2208 $lastpagecode = '';
2209 if ($pagefrom > 0) {
2210 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2211 if ($pagefrom > 1) {
2212 $firstpagecode .= "$separator...";
2213 }
2214 }
2215 if ($pageto < $maxpage) {
2216 if ($pageto < $maxpage -1) {
2217 $lastpagecode = "$separator...";
2218 }
2219 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2220 }
2221
2222 //Previous
2223 if ($page > 0 && $previousandnext) {
2224 $pagenum = $page - 1;
2225 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2226 }
2227
2228 //Add first
2229 $code .= $firstpagecode;
2230
2231 $pagenum = $pagefrom;
2232
2233 //List of maxdisplay pages
2234 while ($pagenum <= $pageto) {
2235 $pagetoshow = $pagenum +1;
2236 if ($pagenum == $page && !$specialselected) {
08ec7ec6 2237 $code .= "$separator<b>$pagetoshow</b>";
e2cf5316 2238 } else {
2239 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2240 }
2241 $pagenum++;
2242 }
2243
2244 //Add last
2245 $code .= $lastpagecode;
2246
2247 //Next
2248 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2249 $pagenum = $page + 1;
2250 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2251 }
2252
2253 //Add special
2254 if ($showspecial) {
2255 $code .= '<br />';
2256 if ($specialselected) {
08ec7ec6 2257 $code .= "<b>$specialtext</b>";
e2cf5316 2258 } else {
2259 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2260 }
2261 }
2262
2263 //End html
2264 $code .= "</p>";
36a2b6bd 2265 $code .= "</div>";
e2cf5316 2266 }
2267
2268 return $code;
2269}
e121db76 2270/**
2271 * @return array
2272 */
f3221af9 2273function glossary_get_view_actions() {
2274 return array('view','view all','view entry');
2275}
e121db76 2276/**
2277 * @return array
2278 */
f3221af9 2279function glossary_get_post_actions() {
c8092ea5 2280 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
f3221af9 2281}
2282
0b5a80a1 2283
2284/**
2285 * Implementation of the function for printing the form elements that control
2286 * whether the course reset functionality affects the glossary.
e121db76 2287 * @param object $mform form passed by reference
0b5a80a1 2288 */
2289function glossary_reset_course_form_definition(&$mform) {
2290 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2291 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2292
2293 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2294 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2295 $mform->setAdvanced('reset_glossary_types');
2296 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2297
2298 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2299 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2300
2301 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2302 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2303
2304 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2305 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2306}
2307
2308/**
2309 * Course reset form defaults.
e121db76 2310 * @return array
0b5a80a1 2311 */
2312function glossary_reset_course_form_defaults($course) {
2313 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2314}
2315
2316/**
2317 * Removes all grades from gradebook
e121db76 2318 *
2319 * @global object
0b5a80a1 2320 * @param int $courseid
2321 * @param string optional type
2322 */
2323function glossary_reset_gradebook($courseid, $type='') {
ae8c3566 2324 global $DB;
0b5a80a1 2325
2326 switch ($type) {
2327 case 'main' : $type = "AND g.mainglossary=1"; break;
2328 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2329 default : $type = ""; //all
2330 }
2331
2332 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
ae8c3566 2333 FROM {glossary} g, {course_modules} cm, {modules} m
2334 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
0b5a80a1 2335
ae8c3566 2336 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2337 foreach ($glossarys as $glossary) {
2338 glossary_grade_item_update($glossary, 'reset');
2339 }
2340 }
2341}
2342/**
72d2982e 2343 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 2344 * glossary responses for course $data->courseid.
e121db76 2345 *
2346 * @global object
0b5a80a1 2347 * @param $data the data submitted from the reset course.
2348 * @return array status array
2349 */
2350function glossary_reset_userdata($data) {
ae8c3566 2351 global $CFG, $DB;
d251b259 2352 require_once($CFG->dirroot.'/rating/lib.php');
0b5a80a1 2353
2354 $componentstr = get_string('modulenameplural', 'glossary');
2355 $status = array();
2356
2357 $allentriessql = "SELECT e.id
ae8c3566 2358 FROM {glossary_entries} e
2359 JOIN {glossary} g ON e.glossaryid = g.id
2360 WHERE g.course = ?";
0b5a80a1 2361
2362 $allglossariessql = "SELECT g.id
ae8c3566 2363 FROM {glossary} g
2364 WHERE g.course = ?";
2365
2366 $params = array($data->courseid);
0b5a80a1 2367
49bcd737 2368 $fs = get_file_storage();
2369
d251b259
AD
2370 $rm = new rating_manager();
2371 $ratingdeloptions = new stdclass();
2372
0b5a80a1 2373 // delete entries if requested
2374 if (!empty($data->reset_glossary_all)
2375 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2376
4140cf6b
DC
2377 $params[] = 'glossary_entry';
2378 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
d484419c 2379 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
ae8c3566 2380 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
0b5a80a1 2381
49bcd737 2382 // now get rid of all attachments
ae8c3566 2383 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
0b5a80a1 2384 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2385 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2386 continue;
2387 }
2388 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2389 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2390
2391 //delete ratings
2392 $ratingdeloptions->contextid = $context->id;
2393 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2394 }
2395 }
2396
2397 // remove all grades from gradebook
2398 if (empty($data->reset_gradebook_grades)) {
2399 glossary_reset_gradebook($data->courseid);
2400 }
2401
2402 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2403
2404 } else if (!empty($data->reset_glossary_types)) {
2405 $mainentriessql = "$allentries AND g.mainglossary=1";
2406 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2407
2408 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2409 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2410
2411 if (in_array('main', $data->reset_glossary_types)) {
4140cf6b
DC
2412 $params[] = 'glossary_entry';
2413 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
ae8c3566 2414 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2415
ae8c3566 2416 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
0b5a80a1 2417 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2418 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2419 continue;
2420 }
2421 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2422 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2423
2424 //delete ratings
2425 $ratingdeloptions->contextid = $context->id;
2426 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2427 }
2428 }
2429
2430 // remove all grades from gradebook
2431 if (empty($data->reset_gradebook_grades)) {
2432 glossary_reset_gradebook($data->courseid, 'main');
2433 }
2434
2435 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2436
2437 } else if (in_array('secondary', $data->reset_glossary_types)) {
4140cf6b
DC
2438 $params[] = 'glossary_entry';
2439 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
ae8c3566 2440 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
0b5a80a1 2441 // remove exported source flag from entries in main glossary
ae8c3566 2442 $DB->execute("UPDATE {glossary_entries
2443 SET sourceglossaryid=0
2444 WHERE glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2445
ae8c3566 2446 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
0b5a80a1 2447 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2448 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2449 continue;
2450 }
2451 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2452 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2453
2454 //delete ratings
2455 $ratingdeloptions->contextid = $context->id;
2456 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2457 }
2458 }
2459
2460 // remove all grades from gradebook
2461 if (empty($data->reset_gradebook_grades)) {
2462 glossary_reset_gradebook($data->courseid, 'secondary');
2463 }
2464
2465 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2466 }
2467 }
2468
2469 // remove entries by users not enrolled into course
2470 if (!empty($data->reset_glossary_notenrolled)) {
2471 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
ae8c3566 2472 FROM {glossary_entries} e
2473 JOIN {glossary} g ON e.glossaryid = g.id
2474 LEFT JOIN {user} u ON e.userid = u.id
2475 WHERE g.course = ? AND e.userid > 0";
0b5a80a1 2476
2477 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2478 $notenrolled = array();
ae8c3566 2479 if ($rs = $DB->get_recordset_sql($entriessql, $params)) {
2480 foreach ($rs as $entry) {
0b5a80a1 2481 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
4f0c2d00 2482 or !is_enrolled($course_context , $entry->userid)) {
4140cf6b 2483 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
ae8c3566 2484 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
49bcd737 2485
2486 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2487 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2488 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2e4b4fc0
AD
2489
2490 //delete ratings
2491 $ratingdeloptions->contextid = $context->id;
2492 $rm->delete_ratings($ratingdeloptions);
49bcd737 2493 }
0b5a80a1 2494 }
2495 }
ae8c3566 2496 $rs->close();
0b5a80a1 2497 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2498 }
2499 }
2500
2501 // remove all ratings
2502 if (!empty($data->reset_glossary_ratings)) {
2e4b4fc0
AD
2503 //remove ratings
2504 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2505 foreach ($glossaries as $glossaryid=>$unused) {
2506 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2507 continue;
2508 }
2509 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2510
2511 //delete ratings
2512 $ratingdeloptions->contextid = $context->id;
2513 $rm->delete_ratings($ratingdeloptions);
2514 }
2515 }
2516
0b5a80a1 2517 // remove all grades from gradebook
2518 if (empty($data->reset_gradebook_grades)) {
2519 glossary_reset_gradebook($data->courseid);
2520 }
2521 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2522 }
2523
4140cf6b 2524 // remove comments
0b5a80a1 2525 if (!empty($data->reset_glossary_comments)) {
4140cf6b
DC
2526 $params[] = 'glossary_entry';
2527 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
0b5a80a1 2528 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2529 }
2530
2531 /// updating dates - shift may be negative too
2532 if ($data->timeshift) {
2533 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2534 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2535 }
2536
2537 return $status;
2538}
2539
f432bebf 2540/**
2541 * Returns all other caps used in module
e121db76 2542 * @return array
f432bebf 2543 */
2544function glossary_get_extra_capabilities() {
16b86ae4 2545 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
f432bebf 2546}
2547
18a2a0cb 2548/**
2549 * @param string $feature FEATURE_xx constant for requested feature
2550 * @return mixed True if module supports feature, null if doesn't know
2551 */
2552function glossary_supports($feature) {
2553 switch($feature) {
42f103be 2554 case FEATURE_GROUPS: return false;
2555 case FEATURE_GROUPINGS: return false;
2556 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 2557 case FEATURE_MOD_INTRO: return true;
18a2a0cb 2558 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
42f103be 2559 case FEATURE_GRADE_HAS_GRADE: return true;
2560 case FEATURE_GRADE_OUTCOMES: return true;
63e87951 2561 case FEATURE_RATE: return true;
d3ce7c2c 2562 case FEATURE_BACKUP_MOODLE2: return true;
42f103be 2563
18a2a0cb 2564 default: return null;
2565 }
2566}
0961861e 2567
2568function glossary_extend_navigation($navigation, $course, $module, $cm) {
2569 global $CFG;
a6855934
PS
2570 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'letter')));
2571 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'cat')));
2572 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'date')));
2573 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'author')));
0961861e 2574}
2575
0b29477b
SH
2576/**
2577 * Adds module specific settings to the settings block
2578 *
2579 * @param settings_navigation $settings The settings navigation object
2580 * @param navigation_node $glossarynode The node to add module settings to
2581 */
2582function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
9e86f2e7 2583 global $PAGE, $DB, $CFG, $USER;
0961861e 2584
2585 $mode = optional_param('mode', '', PARAM_ALPHA);
2586 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
2587
0961861e 2588 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
0b29477b 2589 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
0961861e 2590 }
2591
2592 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
0b29477b 2593 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
0961861e 2594 }
2595
56115eea 2596 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
0b29477b 2597 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
0961861e 2598 }
2599
2600 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
0b29477b 2601 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
0961861e 2602 }
9e86f2e7
AD
2603
2604 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
2605
274f9840 2606 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles) {
9e86f2e7
AD
2607 require_once("$CFG->libdir/rsslib.php");
2608
2609 $string = get_string('rsstype','forum');
2610
aa60291e 2611 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
9e86f2e7
AD
2612 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2613 }
3406acde 2614}