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