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