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