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