Polished.
[moodle.git] / lib / datalib.php
CommitLineData
dcb1bd3c 1<?php // $Id$
df28d6c5 2
7d8c2ec3 3/// GLOBAL CONSTANTS /////////////////////////////////////////////////////////
4if ($SITE = get_site()) {
5 define('SITEID', $SITE->id);
6} else {
7 define('SITEID', 1);
8}
222ac91b 9
10
df28d6c5 11/// FUNCTIONS FOR DATABASE HANDLING ////////////////////////////////
222ac91b 12
18a97fd8 13/**
14* execute a given sql command string
8f0cd6ef 15*
18a97fd8 16* Completely general function - it just runs some SQL and reports success.
17*
6bc502cc 18* @param type description
18a97fd8 19*/
df28d6c5 20function execute_sql($command, $feedback=true) {
21/// Completely general function - it just runs some SQL and reports success.
22
23 global $db;
8f0cd6ef 24
df28d6c5 25 $result = $db->Execute("$command");
26
27 if ($result) {
28 if ($feedback) {
dcb1bd3c 29 echo "<p><font color=\"green\"><b>".get_string("success")."</b></font></p>";
df28d6c5 30 }
31 return true;
32 } else {
33 if ($feedback) {
dcb1bd3c 34 echo "<p><font color=\"red\"><b>".get_string("error")."</b></font></p>";
df28d6c5 35 }
36 return false;
37 }
38}
18a97fd8 39/**
40* Run an arbitrary sequence of semicolon-delimited SQL commands
8f0cd6ef 41*
42* Assumes that the input text (file or string) consists of
43* a number of SQL statements ENDING WITH SEMICOLONS. The
18a97fd8 44* semicolons MUST be the last character in a line.
45* Lines that are blank or that start with "#" are ignored.
46* Only tested with mysql dump files (mysqldump -p -d moodle)
47*
6bc502cc 48* @param type description
18a97fd8 49*/
df28d6c5 50
2b051f1c 51function modify_database($sqlfile="", $sqlstring="") {
df28d6c5 52
53 global $CFG;
54
8f0cd6ef 55 $success = true; // Let's be optimistic
2b051f1c 56
57 if (!empty($sqlfile)) {
58 if (!is_readable($sqlfile)) {
59 $success = false;
dcb1bd3c 60 echo "<p>Tried to modify database, but \"$sqlfile\" doesn't exist!</p>";
2b051f1c 61 return $success;
62 } else {
63 $lines = file($sqlfile);
64 }
65 } else {
66 $lines[] = $sqlstring;
67 }
68
69 $command = "";
70
71 foreach ($lines as $line) {
72 $line = rtrim($line);
73 $length = strlen($line);
74
8f0cd6ef 75 if ($length and $line[0] <> "#") {
2b051f1c 76 if (substr($line, $length-1, 1) == ";") {
77 $line = substr($line, 0, $length-1); // strip ;
78 $command .= $line;
79 $command = str_replace("prefix_", $CFG->prefix, $command); // Table prefixes
80 if (! execute_sql($command)) {
81 $success = false;
df28d6c5 82 }
2b051f1c 83 $command = "";
84 } else {
85 $command .= $line;
df28d6c5 86 }
87 }
df28d6c5 88 }
89
90 return $success;
2b051f1c 91
df28d6c5 92}
93
a3fb1c45 94/// FUNCTIONS TO MODIFY TABLES ////////////////////////////////////////////
95
18a97fd8 96/**
97* Add a new field to a table, or modify an existing one (if oldfield is defined).
8f0cd6ef 98*
18a97fd8 99* Add a new field to a table, or modify an existing one (if oldfield is defined).
100*
6bc502cc 101* @param type description
18a97fd8 102*/
103
92230499 104function table_column($table, $oldfield, $field, $type="integer", $size="10",
105 $signed="unsigned", $default="0", $null="not null", $after="") {
8a230a7d 106 global $CFG, $db;
a3fb1c45 107
108 switch (strtolower($CFG->dbtype)) {
109
110 case "mysql":
111 case "mysqlt":
112
113 switch (strtolower($type)) {
c2cb4545 114 case "text":
115 $type = "TEXT";
4e56c82d 116 $signed = "";
c2cb4545 117 break;
a3fb1c45 118 case "integer":
92230499 119 $type = "INTEGER($size)";
a3fb1c45 120 break;
92230499 121 case "varchar":
122 $type = "VARCHAR($size)";
4e56c82d 123 $signed = "";
a3fb1c45 124 break;
125 }
126
127 if (!empty($oldfield)) {
128 $operation = "CHANGE $oldfield $field";
129 } else {
130 $operation = "ADD $field";
131 }
132
133 $default = "DEFAULT '$default'";
134
135 if (!empty($after)) {
31ce4b53 136 $after = "AFTER `$after`";
a3fb1c45 137 }
138
fdc47ee6 139 return execute_sql("ALTER TABLE {$CFG->prefix}$table $operation $type $signed $default $null $after");
a3fb1c45 140 break;
141
5a4d292b 142 case "postgres7": // From Petri Asikainen
8a230a7d 143 //Check db-version
144 $dbinfo = $db->ServerInfo();
29622339 145 $dbver = substr($dbinfo['version'],0,3);
8f0cd6ef 146
5a4d292b 147 //to prevent conflicts with reserved words
d05024a7 148 $realfield = "\"$field\"";
149 $field = "\"${field}_alter_column_tmp\"";
5a4d292b 150 $oldfield = "\"$oldfield\"";
151
152 switch (strtolower($type)) {
153 case "integer":
09d4c9a9 154 if ($size <= 4) {
5a4d292b 155 $type = "INT2";
8f0cd6ef 156 }
09d4c9a9 157 if ($size <= 10) {
5a4d292b 158 $type = "INT";
159 }
09d4c9a9 160 if ($size > 10) {
5a4d292b 161 $type = "INT8";
162 }
163 break;
164 case "varchar":
165 $type = "VARCHAR($size)";
166 break;
167 }
168
8a230a7d 169 $default = "'$default'";
5a4d292b 170
171 //After is not implemented in postgesql
172 //if (!empty($after)) {
173 // $after = "AFTER '$after'";
174 //}
175
d05024a7 176 //Use transactions
177 execute_sql("BEGIN");
178
179 //Allways use temporaly column
180 execute_sql("ALTER TABLE {$CFG->prefix}$table ADD COLUMN $field $type");
181 //Add default values
182 execute_sql("UPDATE {$CFG->prefix}$table SET $field=$default");
8f0cd6ef 183
5a4d292b 184
8a230a7d 185 if ($dbver >= "7.3") {
186 // modifying 'not null' is posible before 7.3
187 //update default values to table
188 if ($null == "NOT NULL") {
189 execute_sql("UPDATE {$CFG->prefix}$table SET $field=$default where $field IS NULL");
190 execute_sql("ALTER TABLE {$CFG->prefix}$table ALTER COLUMN $field SET $null");
191 } else {
192 execute_sql("ALTER TABLE {$CFG->prefix}$table ALTER COLUMN $field DROP NOT NULL");
193 }
5a4d292b 194 }
8a230a7d 195
d05024a7 196 execute_sql("ALTER TABLE {$CFG->prefix}$table ALTER COLUMN $field SET DEFAULT $default");
8f0cd6ef 197
d05024a7 198 if ( $oldfield != "\"\"" ) {
199 execute_sql("UPDATE {$CFG->prefix}$table SET $field = $oldfield");
200 execute_sql("ALTER TABLE {$CFG->prefix}$table drop column $oldfield");
201 }
5a4d292b 202
8f0cd6ef 203 execute_sql("ALTER TABLE {$CFG->prefix}$table RENAME COLUMN $field TO $realfield");
204
d05024a7 205 return execute_sql("COMMIT");
5a4d292b 206 break;
a3fb1c45 207
208 default:
209 switch (strtolower($type)) {
a3fb1c45 210 case "integer":
a3fb1c45 211 $type = "INTEGER";
212 break;
92230499 213 case "varchar":
214 $type = "VARCHAR";
215 break;
a3fb1c45 216 }
217
218 $default = "DEFAULT '$default'";
219
220 if (!empty($after)) {
31ce4b53 221 $after = "AFTER $after";
a3fb1c45 222 }
223
224 if (!empty($oldfield)) {
225 execute_sql("ALTER TABLE {$CFG->prefix}$table RENAME COLUMN $oldfield $field");
226 } else {
227 execute_sql("ALTER TABLE {$CFG->prefix}$table ADD COLUMN $field $type");
228 }
229
230 execute_sql("ALTER TABLE {$CFG->prefix}$table ALTER COLUMN $field SET $null");
fdc47ee6 231 return execute_sql("ALTER TABLE {$CFG->prefix}$table ALTER COLUMN $field SET $default");
a3fb1c45 232 break;
233
234 }
235}
236
237
238
239/// GENERIC FUNCTIONS TO CHECK AND COUNT RECORDS ////////////////////////////////////////
df28d6c5 240
18a97fd8 241/**
242* Returns true or false depending on whether the specified record exists
8f0cd6ef 243*
18a97fd8 244* Returns true or false depending on whether the specified record exists
245*
6bc502cc 246* @param type description
18a97fd8 247*/
5c63e0c4 248function record_exists($table, $field1="", $value1="", $field2="", $value2="", $field3="", $value3="") {
df28d6c5 249
250 global $CFG;
251
5c63e0c4 252 if ($field1) {
253 $select = "WHERE $field1 = '$value1'";
9fa49e22 254 if ($field2) {
df28d6c5 255 $select .= " AND $field2 = '$value2'";
9fa49e22 256 if ($field3) {
df28d6c5 257 $select .= " AND $field3 = '$value3'";
258 }
259 }
5c63e0c4 260 } else {
261 $select = "";
df28d6c5 262 }
263
264 return record_exists_sql("SELECT * FROM $CFG->prefix$table $select LIMIT 1");
265}
266
267
18a97fd8 268/**
269* Returns true or false depending on whether the specified record exists
8f0cd6ef 270*
18a97fd8 271* The sql statement is provided as a string.
272*
6bc502cc 273* @param type description
18a97fd8 274*/
df28d6c5 275function record_exists_sql($sql) {
df28d6c5 276
06b1db82 277 global $CFG, $db;
df28d6c5 278
9c7fee6c 279 if (!$rs = $db->Execute($sql)) {
2eef791f 280 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 281 notify($db->ErrorMsg()."<br /><br />$sql");
282 }
283 return false;
284 }
df28d6c5 285
286 if ( $rs->RecordCount() ) {
287 return true;
288 } else {
289 return false;
290 }
291}
292
293
18a97fd8 294/**
295* Get all the records and count them
8f0cd6ef 296*
18a97fd8 297* Get all the records and count them
298*
6bc502cc 299* @param type description
18a97fd8 300*/
5c63e0c4 301function count_records($table, $field1="", $value1="", $field2="", $value2="", $field3="", $value3="") {
df28d6c5 302
303 global $CFG;
304
5c63e0c4 305 if ($field1) {
306 $select = "WHERE $field1 = '$value1'";
9fa49e22 307 if ($field2) {
df28d6c5 308 $select .= " AND $field2 = '$value2'";
9fa49e22 309 if ($field3) {
df28d6c5 310 $select .= " AND $field3 = '$value3'";
311 }
312 }
5c63e0c4 313 } else {
314 $select = "";
df28d6c5 315 }
316
317 return count_records_sql("SELECT COUNT(*) FROM $CFG->prefix$table $select");
318}
319
18a97fd8 320/**
321* Get all the records and count them
8f0cd6ef 322*
18a97fd8 323* Get all the records and count them
324*
6bc502cc 325* @param type description
18a97fd8 326*
327*/
b4bac9b6 328function count_records_select($table, $select="", $countitem="COUNT(*)") {
9fa49e22 329
330 global $CFG;
331
d26d7ed0 332 if ($select) {
333 $select = "WHERE $select";
334 }
335
b4bac9b6 336 return count_records_sql("SELECT $countitem FROM $CFG->prefix$table $select");
9fa49e22 337}
338
339
18a97fd8 340/**
341* Get all the records and count them
8f0cd6ef 342*
18a97fd8 343* The sql statement is provided as a string.
344*
6bc502cc 345* @param type description
18a97fd8 346*/
df28d6c5 347function count_records_sql($sql) {
df28d6c5 348
06b1db82 349 global $CFG, $db;
df28d6c5 350
351 $rs = $db->Execute("$sql");
9c7fee6c 352 if (!$rs) {
2eef791f 353 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 354 notify($db->ErrorMsg()."<br /><br />$sql");
355 }
356 return 0;
357 }
df28d6c5 358
359 return $rs->fields[0];
360}
361
a3fb1c45 362
363
364
365/// GENERIC FUNCTIONS TO GET, INSERT, OR UPDATE DATA ///////////////////////////////////
366
18a97fd8 367/**
368* Get a single record as an object
8f0cd6ef 369*
18a97fd8 370* Get a single record as an object
371*
6bc502cc 372* @param string $table the name of the table to select from
373* @param string $field1 the name of the field for the first criteria
374* @param string $value1 the value of the field for the first criteria
375* @param string $field2 the name of the field for the second criteria
376* @param string $value2 the value of the field for the second criteria
377* @param string $field3 the name of the field for the third criteria
378* @param string $value3 the value of the field for the third criteria
379* @return object(fieldset) a fieldset object containing the first record selected
18a97fd8 380*/
5c63e0c4 381function get_record($table, $field1, $value1, $field2="", $value2="", $field3="", $value3="") {
8f0cd6ef 382
7427070a 383 global $CFG ;
df28d6c5 384
5c63e0c4 385 $select = "WHERE $field1 = '$value1'";
df28d6c5 386
9fa49e22 387 if ($field2) {
df28d6c5 388 $select .= " AND $field2 = '$value2'";
9fa49e22 389 if ($field3) {
df28d6c5 390 $select .= " AND $field3 = '$value3'";
391 }
392 }
393
394 return get_record_sql("SELECT * FROM $CFG->prefix$table $select");
395}
396
18a97fd8 397/**
398* Get a single record as an object
8f0cd6ef 399*
18a97fd8 400* The sql statement is provided as a string.
401* A LIMIT is normally added to only look for 1 record
402*
6bc502cc 403* @param type description
18a97fd8 404*/
df28d6c5 405function get_record_sql($sql) {
df28d6c5 406
4d7a3735 407 global $db, $CFG;
df28d6c5 408
2eef791f 409 if (isset($CFG->debug) and $CFG->debug > 7) { // Debugging mode - don't use limit
4d7a3735 410 $limit = "";
411 } else {
412 $limit = " LIMIT 1"; // Workaround - limit to one record
413 }
414
7618a8eb 415 if (!$rs = $db->Execute("$sql$limit")) {
2eef791f 416 if (isset($CFG->debug) and $CFG->debug > 7) { // Debugging mode - print checks
9c7fee6c 417 notify( $db->ErrorMsg() . "<br /><br />$sql$limit" );
7618a8eb 418 }
419 return false;
420 }
4d7a3735 421
7618a8eb 422 if (!$recordcount = $rs->RecordCount()) {
423 return false; // Found no records
4d7a3735 424 }
df28d6c5 425
7618a8eb 426 if ($recordcount == 1) { // Found one record
df28d6c5 427 return (object)$rs->fields;
4d7a3735 428
7618a8eb 429 } else { // Error: found more than one record
430 notify("Error: Turn off debugging to hide this error.");
431 notify("$sql$limit");
4d7a3735 432 if ($records = $rs->GetAssoc(true)) {
7618a8eb 433 notify("Found more than one record in get_record_sql !");
4d7a3735 434 print_object($records);
4d7a3735 435 } else {
7618a8eb 436 notify("Very strange error in get_record_sql !");
437 print_object($rs);
4d7a3735 438 }
7618a8eb 439 print_continue("$CFG->wwwroot/admin/config.php");
df28d6c5 440 }
441}
442
18a97fd8 443/**
444* Gets one record from a table, as an object
8f0cd6ef 445*
18a97fd8 446* "select" is a fragment of SQL to define the selection criteria
447*
6bc502cc 448* @param type description
18a97fd8 449*/
18496c59 450function get_record_select($table, $select="", $fields="*") {
18496c59 451
452 global $CFG;
453
454 if ($select) {
455 $select = "WHERE $select";
456 }
457
458 return get_record_sql("SELECT $fields FROM $CFG->prefix$table $select");
459}
460
461
18a97fd8 462/**
463* Get a number of records as an array of objects
8f0cd6ef 464*
18a97fd8 465* Can optionally be sorted eg "time ASC" or "time DESC"
466* If "fields" is specified, only those fields are returned
467* The "key" is the first column returned, eg usually "id"
468* limitfrom and limitnum must both be specified or not at all
469*
6bc502cc 470* @param type description
18a97fd8 471*/
0eeac484 472function get_records($table, $field="", $value="", $sort="", $fields="*", $limitfrom="", $limitnum="") {
df28d6c5 473
474 global $CFG;
475
9fa49e22 476 if ($field) {
df28d6c5 477 $select = "WHERE $field = '$value'";
5c63e0c4 478 } else {
479 $select = "";
df28d6c5 480 }
5c63e0c4 481
74a0363f 482 if ($limitfrom !== "") {
0eeac484 483 switch ($CFG->dbtype) {
484 case "mysql":
485 $limit = "LIMIT $limitfrom,$limitnum";
486 break;
487 case "postgres7":
488 $limit = "LIMIT $limitnum OFFSET $limitfrom";
489 break;
8f0cd6ef 490 default:
0eeac484 491 $limit = "LIMIT $limitnum,$limitfrom";
492 }
493 } else {
494 $limit = "";
495 }
496
df28d6c5 497 if ($sort) {
5c63e0c4 498 $sort = "ORDER BY $sort";
df28d6c5 499 }
500
0eeac484 501 return get_records_sql("SELECT $fields FROM $CFG->prefix$table $select $sort $limit");
df28d6c5 502}
503
18a97fd8 504/**
505* Get a number of records as an array of objects
8f0cd6ef 506*
18a97fd8 507* Can optionally be sorted eg "time ASC" or "time DESC"
508* "select" is a fragment of SQL to define the selection criteria
509* The "key" is the first column returned, eg usually "id"
4f91b296 510* limitfrom and limitnum must both be specified or not at all
18a97fd8 511*
6bc502cc 512* @param type description
18a97fd8 513*/
4f91b296 514function get_records_select($table, $select="", $sort="", $fields="*", $limitfrom="", $limitnum="") {
9fa49e22 515
516 global $CFG;
517
d26d7ed0 518 if ($select) {
519 $select = "WHERE $select";
5c63e0c4 520 }
521
4f91b296 522 if ($limitfrom !== "") {
523 switch ($CFG->dbtype) {
524 case "mysql":
525 $limit = "LIMIT $limitfrom,$limitnum";
526 break;
527 case "postgres7":
528 $limit = "LIMIT $limitnum OFFSET $limitfrom";
529 break;
8f0cd6ef 530 default:
4f91b296 531 $limit = "LIMIT $limitnum,$limitfrom";
532 }
533 } else {
534 $limit = "";
535 }
536
5c63e0c4 537 if ($sort) {
538 $sort = "ORDER BY $sort";
d26d7ed0 539 }
540
4f91b296 541 return get_records_sql("SELECT $fields FROM $CFG->prefix$table $select $sort $limit");
9fa49e22 542}
543
df28d6c5 544
18a97fd8 545/**
546* Get a number of records as an array of objects
8f0cd6ef 547*
548* Differs from get_records() in that the values variable
18a97fd8 549* can be a comma-separated list of values eg "4,5,6,10"
550* Can optionally be sorted eg "time ASC" or "time DESC"
551* The "key" is the first column returned, eg usually "id"
552*
6bc502cc 553* @param type description
18a97fd8 554*/
df28d6c5 555function get_records_list($table, $field="", $values="", $sort="", $fields="*") {
df28d6c5 556
557 global $CFG;
558
9fa49e22 559 if ($field) {
df28d6c5 560 $select = "WHERE $field in ($values)";
5c63e0c4 561 } else {
562 $select = "";
df28d6c5 563 }
5c63e0c4 564
df28d6c5 565 if ($sort) {
5c63e0c4 566 $sort = "ORDER BY $sort";
df28d6c5 567 }
568
5c63e0c4 569 return get_records_sql("SELECT $fields FROM $CFG->prefix$table $select $sort");
df28d6c5 570}
571
572
9fa49e22 573
18a97fd8 574/**
575* Get a number of records as an array of objects
8f0cd6ef 576*
18a97fd8 577* The "key" is the first column returned, eg usually "id"
578* The sql statement is provided as a string.
579*
6bc502cc 580* @param type description
18a97fd8 581*/
df28d6c5 582function get_records_sql($sql) {
df28d6c5 583
9c7fee6c 584 global $CFG,$db;
df28d6c5 585
9c7fee6c 586 if (!$rs = $db->Execute($sql)) {
2eef791f 587 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 588 notify($db->ErrorMsg()."<br /><br />$sql");
589 }
590 return false;
591 }
8f0cd6ef 592
df28d6c5 593 if ( $rs->RecordCount() > 0 ) {
594 if ($records = $rs->GetAssoc(true)) {
595 foreach ($records as $key => $record) {
596 $objects[$key] = (object) $record;
597 }
598 return $objects;
599 } else {
600 return false;
601 }
602 } else {
603 return false;
604 }
605}
606
18a97fd8 607/**
608* Get a number of records as an array of objects
8f0cd6ef 609*
18a97fd8 610* Can optionally be sorted eg "time ASC" or "time DESC"
611* If "fields" is specified, only those fields are returned
612* The "key" is the first column returned, eg usually "id"
8f0cd6ef 613*
6bc502cc 614* @param type description
18a97fd8 615*/
9fa49e22 616function get_records_menu($table, $field="", $value="", $sort="", $fields="*") {
9fa49e22 617
618 global $CFG;
619
620 if ($field) {
621 $select = "WHERE $field = '$value'";
5c63e0c4 622 } else {
623 $select = "";
9fa49e22 624 }
5c63e0c4 625
9fa49e22 626 if ($sort) {
5c63e0c4 627 $sort = "ORDER BY $sort";
9fa49e22 628 }
629
5c63e0c4 630 return get_records_sql_menu("SELECT $fields FROM $CFG->prefix$table $select $sort");
9fa49e22 631}
632
18a97fd8 633/**
634* Get a number of records as an array of objects
8f0cd6ef 635*
18a97fd8 636* Can optionally be sorted eg "time ASC" or "time DESC"
637* "select" is a fragment of SQL to define the selection criteria
638* Returns associative array of first two fields
8f0cd6ef 639*
6bc502cc 640* @param type description
18a97fd8 641*/
9fa49e22 642function get_records_select_menu($table, $select="", $sort="", $fields="*") {
9fa49e22 643
644 global $CFG;
645
d26d7ed0 646 if ($select) {
647 $select = "WHERE $select";
648 }
649
5c63e0c4 650 if ($sort) {
651 $sort = "ORDER BY $sort";
652 }
653
654 return get_records_sql_menu("SELECT $fields FROM $CFG->prefix$table $select $sort");
9fa49e22 655}
656
657
18a97fd8 658/**
8f0cd6ef 659* Given an SQL select, this function returns an associative
660*
661* array of the first two columns. This is most useful in
662* combination with the choose_from_menu function to create
18a97fd8 663* a form menu.
664*
6bc502cc 665* @param type description
18a97fd8 666*/
df28d6c5 667function get_records_sql_menu($sql) {
df28d6c5 668
06b1db82 669 global $CFG, $db;
df28d6c5 670
9c7fee6c 671 if (!$rs = $db->Execute($sql)) {
2eef791f 672 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 673 notify($db->ErrorMsg()."<br /><br />$sql");
674 }
675 return false;
676 }
df28d6c5 677
678 if ( $rs->RecordCount() > 0 ) {
679 while (!$rs->EOF) {
680 $menu[$rs->fields[0]] = $rs->fields[1];
681 $rs->MoveNext();
682 }
683 return $menu;
8f0cd6ef 684
df28d6c5 685 } else {
686 return false;
687 }
688}
689
18a97fd8 690/**
691* Get a single field from a database record
8f0cd6ef 692*
18a97fd8 693* longdesc
694*
6bc502cc 695* @param type description
18a97fd8 696*/
ec2a28a6 697function get_field($table, $return, $field1, $value1, $field2="", $value2="", $field3="", $value3="") {
df28d6c5 698
699 global $db, $CFG;
700
ec2a28a6 701 $select = "WHERE $field1 = '$value1'";
702
703 if ($field2) {
704 $select .= " AND $field2 = '$value2'";
705 if ($field3) {
706 $select .= " AND $field3 = '$value3'";
707 }
708 }
709
710 $rs = $db->Execute("SELECT $return FROM $CFG->prefix$table $select");
9c7fee6c 711 if (!$rs) {
2eef791f 712 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 713 notify($db->ErrorMsg()."<br /><br />SELECT $return FROM $CFG->prefix$table $select");
714 }
715 return false;
716 }
df28d6c5 717
718 if ( $rs->RecordCount() == 1 ) {
719 return $rs->fields["$return"];
720 } else {
721 return false;
722 }
723}
724
b4bac9b6 725
726/**
727* Get a single field from a database record
8f0cd6ef 728*
b4bac9b6 729* longdesc
730*
731* @param type description
732*/
733function get_field_sql($sql) {
734
735 global $db, $CFG;
736
737 $rs = $db->Execute($sql);
738 if (!$rs) {
739 if (isset($CFG->debug) and $CFG->debug > 7) {
740 notify($db->ErrorMsg()."<br /><br />$sql");
741 }
742 return false;
743 }
744
745 if ( $rs->RecordCount() == 1 ) {
746 return $rs->fields[0];
747 } else {
748 return false;
749 }
750}
751
18a97fd8 752/**
753* Set a single field in a database record
8f0cd6ef 754*
18a97fd8 755* longdesc
756*
6bc502cc 757* @param type description
18a97fd8 758*/
ec2a28a6 759function set_field($table, $newfield, $newvalue, $field1, $value1, $field2="", $value2="", $field3="", $value3="") {
df28d6c5 760
761 global $db, $CFG;
762
ec2a28a6 763 $select = "WHERE $field1 = '$value1'";
764
765 if ($field2) {
766 $select .= " AND $field2 = '$value2'";
767 if ($field3) {
768 $select .= " AND $field3 = '$value3'";
769 }
770 }
771
772 return $db->Execute("UPDATE $CFG->prefix$table SET $newfield = '$newvalue' $select");
df28d6c5 773}
774
775
18a97fd8 776/**
777* Delete one or more records from a table
8f0cd6ef 778*
18a97fd8 779* Delete one or more records from a table
780*
6bc502cc 781* @param type description
18a97fd8 782*/
5c63e0c4 783function delete_records($table, $field1="", $value1="", $field2="", $value2="", $field3="", $value3="") {
df28d6c5 784
785 global $db, $CFG;
786
5c63e0c4 787 if ($field1) {
788 $select = "WHERE $field1 = '$value1'";
9fa49e22 789 if ($field2) {
df28d6c5 790 $select .= " AND $field2 = '$value2'";
9fa49e22 791 if ($field3) {
df28d6c5 792 $select .= " AND $field3 = '$value3'";
793 }
794 }
5c63e0c4 795 } else {
796 $select = "";
df28d6c5 797 }
798
799 return $db->Execute("DELETE FROM $CFG->prefix$table $select");
800}
801
18a97fd8 802/**
803* Delete one or more records from a table
8f0cd6ef 804*
18a97fd8 805* "select" is a fragment of SQL to define the selection criteria
806*
6bc502cc 807* @param type description
18a97fd8 808*/
30f89d68 809function delete_records_select($table, $select="") {
30f89d68 810
811 global $CFG, $db;
812
813 if ($select) {
814 $select = "WHERE $select";
815 }
816
817 return $db->Execute("DELETE FROM $CFG->prefix$table $select");
818}
819
df28d6c5 820
18a97fd8 821/**
822* Insert a record into a table and return the "id" field if required
8f0cd6ef 823*
18a97fd8 824* If the return ID isn't required, then this just reports success as true/false.
825* $dataobject is an object containing needed data
826*
6bc502cc 827* @param type description
18a97fd8 828*/
fcf9c450 829function insert_record($table, $dataobject, $returnid=true, $primarykey='id') {
8f0cd6ef 830
0892f7bd 831 global $db, $CFG;
832
d4469f2a 833/// Execute a dummy query to get an empty recordset
834 if (!$rs = $db->Execute("SELECT * FROM $CFG->prefix$table WHERE $primarykey ='-1'")) {
835 return false;
836 }
8f0cd6ef 837
d4469f2a 838/// Get the correct SQL from adoDB
839 if (!$insertSQL = $db->GetInsertSQL($rs, (array)$dataobject, true)) {
840 return false;
841 }
8f0cd6ef 842
d4469f2a 843/// Run the SQL statement
844 if (!$rs = $db->Execute($insertSQL)) {
2eef791f 845 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 846 notify($db->ErrorMsg()."<br /><br />$insertSQL");
847 }
0892f7bd 848 return false;
849 }
8f0cd6ef 850
d4469f2a 851/// If a return ID is not needed then just return true now
8f0cd6ef 852 if (!$returnid) {
0892f7bd 853 return true;
854 }
855
d4469f2a 856/// Find the return ID of the newly inserted record
0892f7bd 857 switch ($CFG->dbtype) {
d4469f2a 858 case "postgres7": // Just loves to be special
0892f7bd 859 $oid = $db->Insert_ID();
fcf9c450 860 if ($rs = $db->Execute("SELECT $primarykey FROM $CFG->prefix$table WHERE oid = $oid")) {
0892f7bd 861 if ($rs->RecordCount() == 1) {
fcf9c450 862 return (integer) $rs->fields[0];
0892f7bd 863 }
864 }
865 return false;
866
8f0cd6ef 867 default:
d4469f2a 868 return $db->Insert_ID(); // Should work on most databases, but not all!
0892f7bd 869 }
870}
871
872
18a97fd8 873/**
874* Update a record in a table
8f0cd6ef 875*
18a97fd8 876* $dataobject is an object containing needed data
8f0cd6ef 877* Relies on $dataobject having a variable "id" to
18a97fd8 878* specify the record to update
879*
6bc502cc 880* @param type description
18a97fd8 881*/
df28d6c5 882function update_record($table, $dataobject) {
df28d6c5 883
884 global $db, $CFG;
885
886 if (! isset($dataobject->id) ) {
887 return false;
888 }
889
890 // Determine all the fields in the table
891 if (!$columns = $db->MetaColumns("$CFG->prefix$table")) {
892 return false;
893 }
894 $data = (array)$dataobject;
895
896 // Pull out data matching these fields
897 foreach ($columns as $column) {
92230499 898 if ($column->name <> "id" and isset($data[$column->name]) ) {
df28d6c5 899 $ddd[$column->name] = $data[$column->name];
900 }
901 }
902
903 // Construct SQL queries
904 $numddd = count($ddd);
905 $count = 0;
906 $update = "";
907
908 foreach ($ddd as $key => $value) {
909 $count++;
910 $update .= "$key = '$value'";
911 if ($count < $numddd) {
912 $update .= ", ";
913 }
914 }
915
916 if ($rs = $db->Execute("UPDATE $CFG->prefix$table SET $update WHERE id = '$dataobject->id'")) {
917 return true;
918 } else {
2eef791f 919 if (isset($CFG->debug) and $CFG->debug > 7) {
9c7fee6c 920 notify($db->ErrorMsg()."<br /><br />UPDATE $CFG->prefix$table SET $update WHERE id = '$dataobject->id'");
921 }
df28d6c5 922 return false;
923 }
924}
925
926
df28d6c5 927
928
929/// USER DATABASE ////////////////////////////////////////////////
930
18a97fd8 931/**
8f0cd6ef 932* Get a complete user record, which includes all the info
933*
18a97fd8 934* in the user record, as well as membership information
935* Suitable for setting as $USER session cookie.
936*
6bc502cc 937* @param type description
18a97fd8 938*/
df28d6c5 939function get_user_info_from_db($field, $value) {
df28d6c5 940
ca60b03b 941 global $CFG;
942
18496c59 943 if (!$field or !$value) {
df28d6c5 944 return false;
df28d6c5 945 }
946
ca60b03b 947/// Get all the basic user data
948
18496c59 949 if (! $user = get_record_select("user", "$field = '$value' AND deleted <> '1'")) {
950 return false;
951 }
df28d6c5 952
ca60b03b 953/// Add membership information
954
955 if ($admins = get_records("user_admins", "userid", $user->id)) {
956 $user->admin = true;
957 }
df28d6c5 958
222ac91b 959 $user->student[SITEID] = isstudent(SITEID, $user->id);
df28d6c5 960
ca60b03b 961/// Determine enrolments based on current enrolment module
df28d6c5 962
ca60b03b 963 require_once("$CFG->dirroot/enrol/$CFG->enrol/enrol.php");
964 $enrol = new enrolment_plugin();
965 $enrol->get_student_courses($user);
966 $enrol->get_teacher_courses($user);
df28d6c5 967
ca60b03b 968/// Get various settings and preferences
18496c59 969
b86fc0e2 970 if ($displays = get_records("course_display", "userid", $user->id)) {
971 foreach ($displays as $display) {
972 $user->display[$display->course] = $display->display;
973 }
974 }
975
ca60b03b 976 if ($preferences = get_records('user_preferences', 'userid', $user->id)) {
977 foreach ($preferences as $preference) {
978 $user->preference[$preference->name] = $preference->value;
979 }
980 }
981
0da33e07 982 if ($groups = get_records("groups_members", "userid", $user->id)) {
3facf28f 983 foreach ($groups as $groupmember) {
984 $courseid = get_field("groups", "courseid", "id", $groupmember->groupid);
985 $user->groupmember[$courseid] = $groupmember->groupid;
f374fb10 986 }
987 }
988
70812e39 989
18496c59 990 return $user;
df28d6c5 991}
992
df28d6c5 993
18a97fd8 994/**
995* Does this username and password specify a valid admin user?
8f0cd6ef 996*
18a97fd8 997* longdesc
998*
6bc502cc 999* @param type description
18a97fd8 1000*/
df28d6c5 1001function adminlogin($username, $md5password) {
df28d6c5 1002
1003 global $CFG;
1004
8f0cd6ef 1005 return record_exists_sql("SELECT u.id
1006 FROM {$CFG->prefix}user u,
1007 {$CFG->prefix}user_admins a
1008 WHERE u.id = a.userid
1009 AND u.username = '$username'
df28d6c5 1010 AND u.password = '$md5password'");
1011}
1012
1013
18a97fd8 1014/**
1015* Get the guest user information from the database
8f0cd6ef 1016*
18a97fd8 1017* longdesc
1018*
6bc502cc 1019* @param type description
18a97fd8 1020*/
9fa49e22 1021function get_guest() {
1022 return get_user_info_from_db("username", "guest");
1023}
1024
1025
18a97fd8 1026/**
1027* Returns $user object of the main admin user
8f0cd6ef 1028*
18a97fd8 1029* longdesc
1030*
6bc502cc 1031* @param type description
18a97fd8 1032*/
df28d6c5 1033function get_admin () {
df28d6c5 1034
1035 global $CFG;
1036
1037 if ( $admins = get_admins() ) {
1038 foreach ($admins as $admin) {
8f0cd6ef 1039 return $admin; // ie the first one
df28d6c5 1040 }
1041 } else {
1042 return false;
1043 }
1044}
1045
18a97fd8 1046/**
1047* Returns list of all admins
8f0cd6ef 1048*
18a97fd8 1049* longdesc
1050*
6bc502cc 1051* @param type description
18a97fd8 1052*/
df28d6c5 1053function get_admins() {
df28d6c5 1054
1055 global $CFG;
1056
8f0cd6ef 1057 return get_records_sql("SELECT u.*, a.id as adminid
1058 FROM {$CFG->prefix}user u,
ebc3bd2b 1059 {$CFG->prefix}user_admins a
1060 WHERE a.userid = u.id
427fdf66 1061 ORDER BY a.id ASC");
df28d6c5 1062}
1063
18a97fd8 1064/**
1065* Returns list of all creators
8f0cd6ef 1066*
18a97fd8 1067* longdesc
1068*
6bc502cc 1069* @param type description
18a97fd8 1070*/
1924074c 1071function get_creators() {
1924074c 1072
1073 global $CFG;
1074
1075 return get_records_sql("SELECT u.*
1076 FROM {$CFG->prefix}user u,
1077 {$CFG->prefix}user_coursecreators a
1078 WHERE a.userid = u.id
1079 ORDER BY u.id ASC");
1080}
df28d6c5 1081
18a97fd8 1082/**
1083* Returns $user object of the main teacher for a course
8f0cd6ef 1084*
18a97fd8 1085* longdesc
1086*
6bc502cc 1087* @param type description
18a97fd8 1088*/
df28d6c5 1089function get_teacher($courseid) {
df28d6c5 1090
1091 global $CFG;
1092
1093 if ( $teachers = get_course_teachers($courseid, "t.authority ASC")) {
1094 foreach ($teachers as $teacher) {
1095 if ($teacher->authority) {
1096 return $teacher; // the highest authority teacher
1097 }
1098 }
1099 } else {
1100 return false;
1101 }
1102}
1103
18a97fd8 1104/**
1105* Searches logs to find all enrolments since a certain date
8f0cd6ef 1106*
18a97fd8 1107* used to print recent activity
1108*
6bc502cc 1109* @param type description
18a97fd8 1110*/
0a08581d 1111function get_recent_enrolments($courseid, $timestart) {
0a08581d 1112
1113 global $CFG;
1114
fbf5081c 1115 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
0a08581d 1116 FROM {$CFG->prefix}user u,
1117 {$CFG->prefix}user_students s,
1118 {$CFG->prefix}log l
8f0cd6ef 1119 WHERE l.time > '$timestart'
0a08581d 1120 AND l.course = '$courseid'
8f0cd6ef 1121 AND l.module = 'course'
0a08581d 1122 AND l.action = 'enrol'
1123 AND l.info = u.id
1124 AND u.id = s.userid
64cbb55c 1125 AND s.course = '$courseid'
0a08581d 1126 ORDER BY l.time ASC");
1127}
1128
18a97fd8 1129/**
2cc72e84 1130* Returns array of userinfo of all students in this course
1131* or on this site if courseid is id of site
8f0cd6ef 1132*
6bc502cc 1133* @param type description
18a97fd8 1134*/
a328425d 1135function get_course_students($courseid, $sort="s.timeaccess", $dir="", $page=0, $recordsperpage=99999,
900df8b6 1136 $firstinitial="", $lastinitial="", $group=NULL, $search="", $fields='', $exceptions='') {
df28d6c5 1137
1138 global $CFG;
8f0cd6ef 1139
1140 if ($courseid == SITEID and $CFG->allusersaresitestudents) {
2700d113 1141 // return users with confirmed, undeleted accounts who are not site teachers
1142 // the following is a mess because of different conventions in the different user functions
1143 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
1144 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
1145 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
8f0cd6ef 1146 $fields = str_replace('u.', '', $fields);
2700d113 1147 if ($sort) {
1148 $sort = "$sort $dir";
1149 }
1150 // Now we have to make sure site teachers are excluded
1151 if ($teachers = get_records('user_teachers', 'course', SITEID)) {
1152 foreach ($teachers as $teacher) {
1153 $exceptions .= ",$teacher->userid";
1154 }
1155 $exceptions = ltrim($exceptions, ',');
1156 }
8f0cd6ef 1157 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
2700d113 1158 $page, $recordsperpage, $fields ? $fields : '*');
1159 }
df28d6c5 1160
4969ad74 1161 switch ($CFG->dbtype) {
1162 case "mysql":
73fc8c1a 1163 $fullname = " CONCAT(firstname,\" \",lastname) ";
4969ad74 1164 $limit = "LIMIT $page,$recordsperpage";
a328425d 1165 $LIKE = "LIKE";
4969ad74 1166 break;
1167 case "postgres7":
73fc8c1a 1168 $fullname = " firstname||' '||lastname ";
4969ad74 1169 $limit = "LIMIT $recordsperpage OFFSET ".($page);
a328425d 1170 $LIKE = "ILIKE";
4969ad74 1171 break;
8f0cd6ef 1172 default:
73fc8c1a 1173 $fullname = " firstname||\" \"||lastname ";
4969ad74 1174 $limit = "LIMIT $recordsperpage,$page";
a328425d 1175 $LIKE = "ILIKE";
1176 }
1177
0720313b 1178 $groupmembers = '';
f950af3c 1179
1180 // make sure it works on the site course
1181 $select = "s.course = '$courseid' AND ";
222ac91b 1182 if ($courseid == SITEID) {
f950af3c 1183 $select = '';
1184 }
1185
1186 $select .= "s.userid = u.id AND u.deleted = '0' ";
73fc8c1a 1187
1284a926 1188 if (!$fields) {
1189 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
1190 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
1191 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
1192 'u.emailstop, u.lang, u.timezone, s.timeaccess as lastaccess';
1193 }
1194
73fc8c1a 1195 if ($search) {
1196 $search = " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
1197 }
a328425d 1198
1199 if ($firstinitial) {
1200 $select .= " AND u.firstname $LIKE '$firstinitial%' ";
1201 }
1202
1203 if ($lastinitial) {
1204 $select .= " AND u.lastname $LIKE '$lastinitial%' ";
4969ad74 1205 }
1206
3d35e6b7 1207 if ($group === 0) { /// Need something here to get all students not in a group
1208 return array();
1209
1210 } else if ($group !== NULL) {
0720313b 1211 $groupmembers = ", {$CFG->prefix}groups_members gm ";
1212 $select .= " AND u.id = gm.userid AND gm.groupid = '$group'";
1213 }
8f0cd6ef 1214
900df8b6 1215 if (!empty($exceptions)) {
1216 $select .= " AND u.id NOT IN ($exceptions)";
1217 }
0720313b 1218
8e4c9ef7 1219 if ($sort) {
1220 $sort = " ORDER BY $sort ";
1221 }
1222
2700d113 1223 $students = get_records_sql("SELECT $fields
488acd1b 1224 FROM {$CFG->prefix}user u,
1225 {$CFG->prefix}user_students s
1226 $groupmembers
73fc8c1a 1227 WHERE $select $search $sort $dir $limit");
2700d113 1228
1229 if ($courseid != SITEID) {
1230 return $students;
1231 }
8f0cd6ef 1232
2700d113 1233 // We are here because we need the students for the site.
1234 // These also include teachers on real courses minus those on the site
1235 if ($teachers = get_records('user_teachers', 'course', SITEID)) {
1236 foreach ($teachers as $teacher) {
1237 $exceptions .= ",$teacher->userid";
1238 }
1239 $exceptions = ltrim($exceptions, ',');
1240 $select .= " AND u.id NOT IN ($exceptions)";
1241 }
1242 if (!$teachers = get_records_sql("SELECT $fields
1243 FROM {$CFG->prefix}user u,
1244 {$CFG->prefix}user_teachers s
1245 $groupmembers
1246 WHERE $select $search $sort $dir $limit")) {
1247 return $students;
1248 }
1249 if (!$students) {
1250 return $teachers;
1251 }
1252 return $teachers + $students;
df28d6c5 1253}
1254
a328425d 1255/**
2cc72e84 1256* Counts the students in a given course (or site), or a subset of them
8f0cd6ef 1257*
6bc502cc 1258* @param type description
a328425d 1259*/
900df8b6 1260function count_course_students($course, $search="", $firstinitial="", $lastinitial="", $group=NULL, $exceptions='') {
a328425d 1261
2700d113 1262 if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
1263 return count($students);
a328425d 1264 }
2700d113 1265 return 0;
a328425d 1266}
1267
1268
18a97fd8 1269/**
8f0cd6ef 1270* Returns list of all teachers in this course
2cc72e84 1271* (also works for site)
8f0cd6ef 1272*
6bc502cc 1273* @param type description
18a97fd8 1274*/
900df8b6 1275function get_course_teachers($courseid, $sort="t.authority ASC", $exceptions='') {
df28d6c5 1276
1277 global $CFG;
1278
900df8b6 1279 if (!empty($exceptions)) {
1280 $except = " AND u.id NOT IN ($exceptions) ";
1281 } else {
1282 $except = '';
1283 }
1284
8d241374 1285 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
8f0cd6ef 1286 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
86fb5ed5 1287 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
8f0cd6ef 1288 FROM {$CFG->prefix}user u,
688d06f4 1289 {$CFG->prefix}user_teachers t
8f0cd6ef 1290 WHERE t.course = '$courseid' AND t.userid = u.id
2700d113 1291 AND u.deleted = '0' AND u.confirmed = '1' $except
df28d6c5 1292 ORDER BY $sort");
1293}
1294
18a97fd8 1295/**
1296* Returns all the users of a course: students and teachers
18a97fd8 1297*
6bc502cc 1298* @param type description
18a97fd8 1299*/
09f275ce 1300function get_course_users($courseid, $sort="timeaccess DESC", $exceptions='', $fields='') {
353d0338 1301
900df8b6 1302 /// Using this method because the single SQL is too inefficient
1303 // Note that this has the effect that teachers and students are
1304 // sorted individually. Returns first all teachers, then all students
0720313b 1305
900df8b6 1306 if (!$teachers = get_course_teachers($courseid, $sort, $exceptions)) {
1307 $teachers = array();
1308 }
65ee9c16 1309 if (!$students = get_course_students($courseid, $sort, '', 0, 99999, '', '', NULL, '', $fields, $exceptions)) {
900df8b6 1310 $students = array();
1311 }
df28d6c5 1312
900df8b6 1313 return $teachers + $students;
0720313b 1314
900df8b6 1315}
0720313b 1316
df28d6c5 1317
900df8b6 1318/**
1319* Search through course users
2700d113 1320* If used for the site course searches through all undeleted, confirmed users
900df8b6 1321*
1322* @param type description
1323*/
1324function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
1325 global $CFG;
0720313b 1326
900df8b6 1327 switch ($CFG->dbtype) {
1328 case "mysql":
1329 $fullname = " CONCAT(u.firstname,\" \",u.lastname) ";
1330 $LIKE = "LIKE";
1331 break;
1332 case "postgres7":
1333 $fullname = " u.firstname||' '||u.lastname ";
1334 $LIKE = "ILIKE";
1335 break;
8f0cd6ef 1336 default:
900df8b6 1337 $fullname = " u.firstname||\" \"||u.lastname ";
1338 $LIKE = "ILIKE";
1339 }
8f0cd6ef 1340
900df8b6 1341 if (!empty($exceptions)) {
1342 $except = " AND u.id NOT IN ($exceptions) ";
1343 } else {
1344 $except = '';
1345 }
2700d113 1346
900df8b6 1347 if (!empty($sort)) {
1348 $order = " ORDER by $sort";
1349 } else {
1350 $order = '';
1351 }
8f0cd6ef 1352
2700d113 1353 $select = "u.deleted = '0' AND u.confirmed = '1'";
1354
222ac91b 1355 if (!$courseid or $courseid == SITEID) {
2700d113 1356 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
1357 FROM {$CFG->prefix}user u
1358 WHERE $select
900df8b6 1359 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
2700d113 1360 $except $order");
8f0cd6ef 1361 } else {
2700d113 1362
900df8b6 1363 if ($groupid) {
1364 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1365 FROM {$CFG->prefix}user u,
900df8b6 1366 {$CFG->prefix}groups_members g
2700d113 1367 WHERE $select AND g.groupid = '$groupid' AND g.userid = u.id
900df8b6 1368 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1369 $except $order");
1370 } else {
1371 if (!$teachers = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1372 FROM {$CFG->prefix}user u,
900df8b6 1373 {$CFG->prefix}user_teachers s
2700d113 1374 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
900df8b6 1375 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1376 $except $order")) {
1377 $teachers = array();
1378 }
1379 if (!$students = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1380 FROM {$CFG->prefix}user u,
900df8b6 1381 {$CFG->prefix}user_students s
2700d113 1382 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
900df8b6 1383 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1384 $except $order")) {
1385 $students = array();
1386 }
1387 return $teachers + $students;
1388 }
1389 }
df28d6c5 1390}
1391
2700d113 1392
18a97fd8 1393/**
2700d113 1394* Returns a list of all site users
1395* Obsolete, just calls get_course_users(SITEID)
18a97fd8 1396*
6bc502cc 1397* @param type description
18a97fd8 1398*/
65ee9c16 1399function get_site_users($sort="u.lastaccess DESC", $fields='*', $exceptions='') {
2d0b30a0 1400
65ee9c16 1401 return get_course_users(SITEID, $sort, $exceptions, $fields);
2d0b30a0 1402}
1403
9fa49e22 1404
18a97fd8 1405/**
8f0cd6ef 1406* Returns a subset of users
1407*
18a97fd8 1408* longdesc
1409*
6bc502cc 1410* @param bookean $get if false then only a count of the records is returned
1411* @param string $search a simple string to search for
1412* @param boolean $confirmed a switch to allow/disallow unconfirmed users
1413* @param array(int) $exceptions a list of IDs to ignore, eg 2,4,5,8,9,10
1414* @param string $sort a SQL snippet for the sorting criteria to use
1284a926 1415* @param string $firstinitial
1416* @param string $lastinitial
1417* @param string $page
1418* @param string $recordsperpage
1419* @param string $fields a comma separated list of fields
18a97fd8 1420*/
488acd1b 1421function get_users($get=true, $search="", $confirmed=false, $exceptions="", $sort="firstname ASC",
1284a926 1422 $firstinitial="", $lastinitial="", $page=0, $recordsperpage=99999, $fields="*") {
18a97fd8 1423
1424 global $CFG;
1425
1426 switch ($CFG->dbtype) {
1427 case "mysql":
62b80756 1428 $limit = "LIMIT $page,$recordsperpage";
18a97fd8 1429 $fullname = " CONCAT(firstname,\" \",lastname) ";
489b2919 1430 $LIKE = "LIKE";
1431 break;
1432 case "postgres7":
62b80756 1433 $limit = "LIMIT $recordsperpage OFFSET ".($page);
3a954ad4 1434 $fullname = " firstname||' '||lastname ";
489b2919 1435 $LIKE = "ILIKE";
18a97fd8 1436 break;
8f0cd6ef 1437 default:
62b80756 1438 $limit = "LIMIT $recordsperpage,$page";
18a97fd8 1439 $fullname = " firstname||\" \"||lastname ";
489b2919 1440 $LIKE = "ILIKE";
18a97fd8 1441 }
e384fb7b 1442
488acd1b 1443 $select = "username <> 'guest' AND deleted = 0";
1444
e384fb7b 1445 if ($search) {
488acd1b 1446 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
e384fb7b 1447 }
1448
5a741655 1449 if ($confirmed) {
488acd1b 1450 $select .= " AND confirmed = '1' ";
5a741655 1451 }
1452
1453 if ($exceptions) {
488acd1b 1454 $select .= " AND id NOT IN ($exceptions) ";
5a741655 1455 }
1456
488acd1b 1457 if ($firstinitial) {
1458 $select .= " AND firstname $LIKE '$firstinitial%'";
8f0cd6ef 1459 }
488acd1b 1460 if ($lastinitial) {
1461 $select .= " AND lastname $LIKE '$lastinitial%'";
8f0cd6ef 1462 }
488acd1b 1463
5a741655 1464 if ($sort and $get) {
1465 $sort = " ORDER BY $sort ";
1466 } else {
1467 $sort = "";
1468 }
1469
1470 if ($get) {
1284a926 1471 return get_records_select("user", "$select $sort $limit", '', $fields);
5a741655 1472 } else {
62b80756 1473 return count_records_select("user", "$select $sort $limit");
5a741655 1474 }
9fa49e22 1475}
1476
5a741655 1477
18a97fd8 1478/**
1479* shortdesc
8f0cd6ef 1480*
18a97fd8 1481* longdesc
1482*
6bc502cc 1483* @param type description
18a97fd8 1484*/
488acd1b 1485function get_users_listing($sort="lastaccess", $dir="ASC", $page=0, $recordsperpage=99999,
1486 $search="", $firstinitial="", $lastinitial="") {
1487
9fa49e22 1488 global $CFG;
31fefa63 1489
c2a96d6b 1490 switch ($CFG->dbtype) {
1491 case "mysql":
1492 $limit = "LIMIT $page,$recordsperpage";
18a97fd8 1493 $fullname = " CONCAT(firstname,\" \",lastname) ";
489b2919 1494 $LIKE = "LIKE";
c2a96d6b 1495 break;
1496 case "postgres7":
a918234e 1497 $limit = "LIMIT $recordsperpage OFFSET ".($page);
3a954ad4 1498 $fullname = " firstname||' '||lastname ";
489b2919 1499 $LIKE = "ILIKE";
c2a96d6b 1500 break;
8f0cd6ef 1501 default:
c2a96d6b 1502 $limit = "LIMIT $recordsperpage,$page";
488acd1b 1503 $fullname = " firstname||' '||lastname ";
489b2919 1504 $LIKE = "LIKE";
31fefa63 1505 }
c2a96d6b 1506
488acd1b 1507 $select = 'deleted <> 1';
1508
c750592a 1509 if ($search) {
488acd1b 1510 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
1511 }
1512
1513 if ($firstinitial) {
1514 $select .= " AND firstname $LIKE '$firstinitial%' ";
1515 }
1516
1517 if ($lastinitial) {
1518 $select .= " AND lastname $LIKE '$lastinitial%' ";
c750592a 1519 }
1520
488acd1b 1521 if ($sort) {
1522 $sort = " ORDER BY $sort $dir";
1523 }
1524
1525/// warning: will return UNCONFIRMED USERS
ea5d48ee 1526 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed
8f0cd6ef 1527 FROM {$CFG->prefix}user
488acd1b 1528 WHERE $select $sort $limit ");
9fa49e22 1529
1530}
1531
488acd1b 1532
18a97fd8 1533/**
1534* shortdesc
8f0cd6ef 1535*
18a97fd8 1536* longdesc
1537*
6bc502cc 1538* @param type description
18a97fd8 1539*/
9fa49e22 1540function get_users_confirmed() {
1541 global $CFG;
8f0cd6ef 1542 return get_records_sql("SELECT *
1543 FROM {$CFG->prefix}user
1544 WHERE confirmed = 1
9fa49e22 1545 AND deleted = 0
8f0cd6ef 1546 AND username <> 'guest'
9fa49e22 1547 AND username <> 'changeme'");
1548}
1549
1550
18a97fd8 1551/**
1552* shortdesc
8f0cd6ef 1553*
18a97fd8 1554* longdesc
1555*
6bc502cc 1556* @param type description
18a97fd8 1557*/
99988d1a 1558function get_users_unconfirmed($cutofftime=2000000000) {
9fa49e22 1559 global $CFG;
8f0cd6ef 1560 return get_records_sql("SELECT *
1561 FROM {$CFG->prefix}user
9fa49e22 1562 WHERE confirmed = 0
8f0cd6ef 1563 AND firstaccess > 0
9fa49e22 1564 AND firstaccess < '$cutofftime'");
1565}
1566
1567
18a97fd8 1568/**
1569* shortdesc
8f0cd6ef 1570*
18a97fd8 1571* longdesc
1572*
6bc502cc 1573* @param type description
18a97fd8 1574*/
9fa49e22 1575function get_users_longtimenosee($cutofftime) {
1576 global $CFG;
937ae59c 1577 return get_records_sql("SELECT DISTINCT *
1578 FROM {$CFG->prefix}user_students
8f0cd6ef 1579 WHERE timeaccess > '0'
937ae59c 1580 AND timeaccess < '$cutofftime' ");
9fa49e22 1581}
1582
f374fb10 1583/**
1584* Returns an array of group objects that the user is a member of
8f0cd6ef 1585* in the given course. If userid isn't specified, then return a
f374fb10 1586* list of all groups in the course.
8f0cd6ef 1587*
6bc502cc 1588* @param type description
f374fb10 1589*/
1590function get_groups($courseid, $userid=0) {
1591 global $CFG;
1592
1593 if ($userid) {
2d439c9d 1594 $dbselect = ", {$CFG->prefix}groups_members m";
f374fb10 1595 $userselect = "AND m.groupid = g.id AND m.userid = '$userid'";
2d439c9d 1596 } else {
1597 $dbselect = '';
1598 $userselect = '';
f374fb10 1599 }
1600
1601 return get_records_sql("SELECT DISTINCT g.*
2d439c9d 1602 FROM {$CFG->prefix}groups g $dbselect
f374fb10 1603 WHERE g.courseid = '$courseid' $userselect ");
1604}
1605
1606
1607/**
1608* Returns an array of user objects
8f0cd6ef 1609*
6bc502cc 1610* @param type description
f374fb10 1611*/
900df8b6 1612function get_group_users($groupid, $sort="u.lastaccess DESC", $exceptions='') {
f374fb10 1613 global $CFG;
900df8b6 1614 if (!empty($exceptions)) {
1615 $except = " AND u.id NOT IN ($exceptions) ";
1616 } else {
1617 $except = '';
1618 }
f374fb10 1619 return get_records_sql("SELECT DISTINCT u.*
1620 FROM {$CFG->prefix}user u,
8f0cd6ef 1621 {$CFG->prefix}groups_members m
f374fb10 1622 WHERE m.groupid = '$groupid'
900df8b6 1623 AND m.userid = u.id $except
2c4263c4 1624 ORDER BY $sort");
f374fb10 1625}
1626
1627/**
1628* An efficient way of finding all the users who aren't in groups yet
8f0cd6ef 1629*
6bc502cc 1630* @param type description
f374fb10 1631*/
1632function get_users_not_in_group($courseid) {
1633 global $CFG;
1634
1635 return array(); /// XXX TO BE DONE
1636}
1637
60b025d1 1638
1639/**
1640* Returns an array of user objects
8f0cd6ef 1641*
6bc502cc 1642* @param type description
60b025d1 1643*/
1644function get_group_students($groupid, $sort="u.lastaccess DESC") {
1645 global $CFG;
1646 return get_records_sql("SELECT DISTINCT u.*
1647 FROM {$CFG->prefix}user u,
1648 {$CFG->prefix}groups_members m,
1649 {$CFG->prefix}groups g,
1650 {$CFG->prefix}user_students s
1651 WHERE m.groupid = '$groupid'
8f0cd6ef 1652 AND m.userid = u.id
1653 AND m.groupid = g.id
60b025d1 1654 AND g.courseid = s.course
1655 AND s.userid = u.id
1656 ORDER BY $sort");
1657}
1658
1659
f374fb10 1660/**
1661* Returns the user's group in a particular course
8f0cd6ef 1662*
6bc502cc 1663* @param type description
f374fb10 1664*/
1665function user_group($courseid, $userid) {
1666 global $CFG;
1667
1668 return get_record_sql("SELECT g.*
0da33e07 1669 FROM {$CFG->prefix}groups g,
1670 {$CFG->prefix}groups_members m
f374fb10 1671 WHERE g.courseid = '$courseid'
1672 AND g.id = m.groupid
1673 AND m.userid = '$userid'");
1674}
1675
1676
9fa49e22 1677
02ebf404 1678
1679/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
1680
1681
18a97fd8 1682/**
1683* Returns $course object of the top-level site.
8f0cd6ef 1684*
18a97fd8 1685* Returns $course object of the top-level site.
1686*
6bc502cc 1687* @param type description
18a97fd8 1688*/
02ebf404 1689function get_site () {
02ebf404 1690
1691 if ( $course = get_record("course", "category", 0)) {
1692 return $course;
1693 } else {
1694 return false;
1695 }
1696}
1697
1698
18a97fd8 1699/**
1700* Returns list of courses, for whole site, or category
8f0cd6ef 1701*
18a97fd8 1702* Returns list of courses, for whole site, or category
1703*
6bc502cc 1704* @param type description
18a97fd8 1705*/
8130b77b 1706function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 1707
8ef9cb56 1708 global $USER, $CFG;
1709
1710 $categoryselect = "";
1711 if ($categoryid != "all") {
14f32609 1712 $categoryselect = "c.category = '$categoryid'";
02ebf404 1713 }
1714
8ef9cb56 1715 $teachertable = "";
f68e5995 1716 $visiblecourses = "";
4b929531 1717 $sqland = "";
1718 if (!empty($categoryselect)) {
1719 $sqland = "AND ";
1720 }
e1f3202a 1721 if (!empty($USER->id)) { // May need to check they are a teacher
3af6e1db 1722 if (!iscreator()) {
4b929531 1723 $visiblecourses = "$sqland ((c.visible > 0) OR (t.userid = '$USER->id' AND t.course = c.id))";
8ef9cb56 1724 $teachertable = ", {$CFG->prefix}user_teachers t";
1725 }
f68e5995 1726 } else {
4b929531 1727 $visiblecourses = "$sqland c.visible > 0";
8ef9cb56 1728 }
1729
14f32609 1730 if ($categoryselect or $visiblecourses) {
1731 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
1732 } else {
1733 $selectsql = "{$CFG->prefix}course c $teachertable";
1734 }
1735
8130b77b 1736
0db8b2e2 1737 return get_records_sql("SELECT DISTINCT $fields FROM $selectsql ORDER BY $sort");
8130b77b 1738}
1739
1740
18a97fd8 1741/**
1742* Returns list of courses, for whole site, or category
8f0cd6ef 1743*
18a97fd8 1744* Similar to get_courses, but allows paging
1745*
6bc502cc 1746* @param type description
18a97fd8 1747*/
8f0cd6ef 1748function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
8130b77b 1749 &$totalcount, $limitfrom="", $limitnum="") {
8130b77b 1750
1751 global $USER, $CFG;
1752
1753 $categoryselect = "";
1754 if ($categoryid != "all") {
1755 $categoryselect = "c.category = '$categoryid'";
1756 }
1757
1758 $teachertable = "";
8130b77b 1759 $visiblecourses = "";
4b929531 1760 $sqland = "";
1761 if (!empty($categoryselect)) {
1762 $sqland = "AND ";
1763 }
8130b77b 1764 if (!empty($USER)) { // May need to check they are a teacher
3af6e1db 1765 if (!iscreator()) {
4b929531 1766 $visiblecourses = "$sqland ((c.visible > 0) OR (t.userid = '$USER->id' AND t.course = c.id))";
8130b77b 1767 $teachertable = ", {$CFG->prefix}user_teachers t";
8130b77b 1768 }
1769 } else {
4b929531 1770 $visiblecourses = "$sqland c.visible > 0";
8130b77b 1771 }
1772
8ef9cb56 1773 if ($limitfrom !== "") {
1774 switch ($CFG->dbtype) {
1775 case "mysql":
1776 $limit = "LIMIT $limitfrom,$limitnum";
1777 break;
1778 case "postgres7":
1779 $limit = "LIMIT $limitnum OFFSET $limitfrom";
1780 break;
8f0cd6ef 1781 default:
8ef9cb56 1782 $limit = "LIMIT $limitnum,$limitfrom";
02ebf404 1783 }
8ef9cb56 1784 } else {
1785 $limit = "";
02ebf404 1786 }
8ef9cb56 1787
53b67df5 1788 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
8ef9cb56 1789
53b67df5 1790 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
8ef9cb56 1791
0db8b2e2 1792 return get_records_sql("SELECT DISTINCT $fields FROM $selectsql ORDER BY $sort $limit");
02ebf404 1793}
1794
1795
18a97fd8 1796/**
1797* shortdesc
8f0cd6ef 1798*
18a97fd8 1799* longdesc
1800*
6bc502cc 1801* @param type description
18a97fd8 1802*/
6bc502cc 1803function get_my_courses($userid, $sort="visible DESC,sortorder ASC") {
2f3499b7 1804
02ebf404 1805 global $CFG;
1806
2f3499b7 1807 $course = array();
1808
1809 if ($students = get_records("user_students", "userid", $userid, "", "id, course")) {
1810 foreach ($students as $student) {
1811 $course[$student->course] = $student->course;
1812 }
1813 }
1814 if ($teachers = get_records("user_teachers", "userid", $userid, "", "id, course")) {
1815 foreach ($teachers as $teacher) {
1816 $course[$teacher->course] = $teacher->course;
1817 }
1818 }
1819 if (empty($course)) {
1820 return $course;
1821 }
1822
1823 $courseids = implode(',', $course);
1824
1825 return get_records_list("course", "id", $courseids, $sort);
1826
1827// The following is correct but VERY slow with large datasets
1828//
8f0cd6ef 1829// return get_records_sql("SELECT c.*
1830// FROM {$CFG->prefix}course c,
1831// {$CFG->prefix}user_students s,
1832// {$CFG->prefix}user_teachers t
2f3499b7 1833// WHERE (s.userid = '$userid' AND s.course = c.id)
1834// OR (t.userid = '$userid' AND t.course = c.id)
8f0cd6ef 1835// GROUP BY c.id
2f3499b7 1836// ORDER BY $sort");
02ebf404 1837}
1838
1839
18a97fd8 1840/**
1841* Returns a list of courses that match a search
8f0cd6ef 1842*
18a97fd8 1843* Returns a list of courses that match a search
1844*
6bc502cc 1845* @param type description
18a97fd8 1846*/
a8b56716 1847function get_courses_search($searchterms, $sort="fullname ASC", $page=0, $recordsperpage=50, &$totalcount) {
02ebf404 1848
1849 global $CFG;
1850
1851 switch ($CFG->dbtype) {
1852 case "mysql":
1853 $limit = "LIMIT $page,$recordsperpage";
1854 break;
1855 case "postgres7":
1856 $limit = "LIMIT $recordsperpage OFFSET ".($page * $recordsperpage);
1857 break;
8f0cd6ef 1858 default:
02ebf404 1859 $limit = "LIMIT $recordsperpage,$page";
1860 }
1861
18a97fd8 1862 //to allow case-insensitive search for postgesql
02ebf404 1863 if ($CFG->dbtype == "postgres7") {
a8b56716 1864 $LIKE = "ILIKE";
1865 $NOTLIKE = "NOT ILIKE"; // case-insensitive
1866 $REGEXP = "~*";
1867 $NOTREGEXP = "!~*";
02ebf404 1868 } else {
a8b56716 1869 $LIKE = "LIKE";
1870 $NOTLIKE = "NOT LIKE";
1871 $REGEXP = "REGEXP";
1872 $NOTREGEXP = "NOT REGEXP";
02ebf404 1873 }
1874
1875 $fullnamesearch = "";
1876 $summarysearch = "";
1877
02ebf404 1878 foreach ($searchterms as $searchterm) {
1879 if ($fullnamesearch) {
1880 $fullnamesearch .= " AND ";
1881 }
02ebf404 1882 if ($summarysearch) {
1883 $summarysearch .= " AND ";
1884 }
a8b56716 1885
1886 if (substr($searchterm,0,1) == "+") {
1887 $searchterm = substr($searchterm,1);
1888 $summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1889 $fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1890 } else if (substr($searchterm,0,1) == "-") {
1891 $searchterm = substr($searchterm,1);
1892 $summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1893 $fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1894 } else {
1895 $summarysearch .= " summary $LIKE '%$searchterm%' ";
1896 $fullnamesearch .= " fullname $LIKE '%$searchterm%' ";
1897 }
1898
02ebf404 1899 }
1900
356fea4a 1901 $selectsql = "{$CFG->prefix}course WHERE ($fullnamesearch OR $summarysearch) AND category > '0'";
a8b56716 1902
1903 $totalcount = count_records_sql("SELECT COUNT(*) FROM $selectsql");
02ebf404 1904
8f0cd6ef 1905 $courses = get_records_sql("SELECT * FROM $selectsql ORDER BY $sort $limit");
02ebf404 1906
1907 if ($courses) { /// Remove unavailable courses from the list
1908 foreach ($courses as $key => $course) {
1909 if (!$course->visible) {
1910 if (!isteacher($course->id)) {
1911 unset($courses[$key]);
a8b56716 1912 $totalcount--;
02ebf404 1913 }
1914 }
1915 }
1916 }
1917
1918 return $courses;
1919}
1920
1921
18a97fd8 1922/**
1923* Returns a sorted list of categories
8f0cd6ef 1924*
18a97fd8 1925* Returns a sorted list of categories
1926*
6bc502cc 1927* @param type description
18a97fd8 1928*/
02ebf404 1929function get_categories($parent="none", $sort="sortorder ASC") {
02ebf404 1930
1931 if ($parent == "none") {
1932 $categories = get_records("course_categories", "", "", $sort);
1933 } else {
1934 $categories = get_records("course_categories", "parent", $parent, $sort);
1935 }
1936 if ($categories) { /// Remove unavailable categories from the list
3af6e1db 1937 $creator = iscreator();
02ebf404 1938 foreach ($categories as $key => $category) {
1939 if (!$category->visible) {
3af6e1db 1940 if (!$creator) {
02ebf404 1941 unset($categories[$key]);
1942 }
1943 }
1944 }
1945 }
1946 return $categories;
1947}
1948
1949
18a97fd8 1950/**
6bc502cc 1951* This recursive function makes sure that the courseorder is consecutive
18a97fd8 1952*
6bc502cc 1953* @param type description
18a97fd8 1954*/
6bc502cc 1955function fix_course_sortorder($categoryid=0, $n=0) {
8f0cd6ef 1956
02ebf404 1957 $count = 0;
6bc502cc 1958 if ($courses = get_courses($categoryid)) {
1959 foreach ($courses as $course) {
1960 set_field('course', 'sortorder', $n, 'id', $course->id);
1961 $n++;
1962 $count++;
02ebf404 1963 }
02ebf404 1964 }
9936fe81 1965 set_field("course_categories", "coursecount", $count, "id", $categoryid);
8f0cd6ef 1966
6bc502cc 1967 if ($categories = get_categories($categoryid)) {
1968 foreach ($categories as $category) {
1969 $n = fix_course_sortorder($category->id, $n);
1970 }
1971 }
8f0cd6ef 1972
6bc502cc 1973 return $n;
02ebf404 1974}
1975
18a97fd8 1976/**
1977* This function creates a default separated/connected scale
8f0cd6ef 1978*
18a97fd8 1979* This function creates a default separated/connected scale
8f0cd6ef 1980* so there's something in the database. The locations of
1981* strings and files is a bit odd, but this is because we
18a97fd8 1982* need to maintain backward compatibility with many different
1983* existing language translations and older sites.
1984*
6bc502cc 1985* @param type description
18a97fd8 1986*/
02ebf404 1987function make_default_scale() {
02ebf404 1988
1989 global $CFG;
1990
1991 $defaultscale = NULL;
1992 $defaultscale->courseid = 0;
1993 $defaultscale->userid = 0;
1994 $defaultscale->name = get_string("separateandconnected");
1995 $defaultscale->scale = get_string("postrating1", "forum").",".
1996 get_string("postrating2", "forum").",".
1997 get_string("postrating3", "forum");
1998 $defaultscale->timemodified = time();
1999
8f0cd6ef 2000 /// Read in the big description from the file. Note this is not
02ebf404 2001 /// HTML (despite the file extension) but Moodle format text.
2002 $parentlang = get_string("parentlang");
2003 if (is_readable("$CFG->dirroot/lang/$CFG->lang/help/forum/ratings.html")) {
2004 $file = file("$CFG->dirroot/lang/$CFG->lang/help/forum/ratings.html");
2005 } else if ($parentlang and is_readable("$CFG->dirroot/lang/$parentlang/help/forum/ratings.html")) {
2006 $file = file("$CFG->dirroot/lang/$parentlang/help/forum/ratings.html");
2007 } else if (is_readable("$CFG->dirroot/lang/en/help/forum/ratings.html")) {
2008 $file = file("$CFG->dirroot/lang/en/help/forum/ratings.html");
2009 } else {
2010 $file = "";
2011 }
2012
2013 $defaultscale->description = addslashes(implode("", $file));
2014
2015 if ($defaultscale->id = insert_record("scale", $defaultscale)) {
94d782eb 2016 execute_sql("UPDATE {$CFG->prefix}forum SET scale = '$defaultscale->id'", false);
02ebf404 2017 }
2018}
2019
18a97fd8 2020/**
2021* Returns a menu of all available scales from the site as well as the given course
8f0cd6ef 2022*
18a97fd8 2023* Returns a menu of all available scales from the site as well as the given course
2024*
6bc502cc 2025* @param type description
18a97fd8 2026*/
02ebf404 2027function get_scales_menu($courseid=0) {
02ebf404 2028
2029 global $CFG;
8f0cd6ef 2030
2031 $sql = "SELECT id, name FROM {$CFG->prefix}scale
2032 WHERE courseid = '0' or courseid = '$courseid'
02ebf404 2033 ORDER BY courseid ASC, name ASC";
2034
2035 if ($scales = get_records_sql_menu("$sql")) {
2036 return $scales;
2037 }
2038
2039 make_default_scale();
2040
2041 return get_records_sql_menu("$sql");
2042}
2043
df28d6c5 2044/// MODULE FUNCTIONS /////////////////////////////////////////////////
2045
18a97fd8 2046/**
2047* Just gets a raw list of all modules in a course
8f0cd6ef 2048*
18a97fd8 2049* Just gets a raw list of all modules in a course
2050*
6bc502cc 2051* @param type description
18a97fd8 2052*/
9fa49e22 2053function get_course_mods($courseid) {
9fa49e22 2054 global $CFG;
2055
7acaa63d 2056 return get_records_sql("SELECT cm.*, m.name as modname
8f0cd6ef 2057 FROM {$CFG->prefix}modules m,
7acaa63d 2058 {$CFG->prefix}course_modules cm
8f0cd6ef 2059 WHERE cm.course = '$courseid'
9fa49e22 2060 AND cm.deleted = '0'
2061 AND cm.module = m.id ");
2062}
2063
18a97fd8 2064/**
2065* Given an instance of a module, finds the coursemodule description
8f0cd6ef 2066*
18a97fd8 2067* Given an instance of a module, finds the coursemodule description
2068*
6bc502cc 2069* @param type description
18a97fd8 2070*/
df28d6c5 2071function get_coursemodule_from_instance($modulename, $instance, $courseid) {
df28d6c5 2072
2073 global $CFG;
2074
2075 return get_record_sql("SELECT cm.*, m.name
8f0cd6ef 2076 FROM {$CFG->prefix}course_modules cm,
2077 {$CFG->prefix}modules md,
2078 {$CFG->prefix}$modulename m
2079 WHERE cm.course = '$courseid' AND
df28d6c5 2080 cm.deleted = '0' AND
8f0cd6ef 2081 cm.instance = m.id AND
2082 md.name = '$modulename' AND
df28d6c5 2083 md.id = cm.module AND
2084 m.id = '$instance'");
2085
2086}
2087
18a97fd8 2088/**
2089* Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
8f0cd6ef 2090*
18a97fd8 2091* Returns an array of all the active instances of a particular
2092* module in a given course, sorted in the order they are defined
2093* in the course. Returns false on any errors.
2094*
6bc502cc 2095* @param string $modulename the name of the module to get instances for
2096* @param object(course) $course this depends on an accurate $course->modinfo
18a97fd8 2097*/
cccb016a 2098function get_all_instances_in_course($modulename, $course) {
df28d6c5 2099
2100 global $CFG;
2101
cccb016a 2102 if (!$modinfo = unserialize($course->modinfo)) {
2103 return array();
1acfbce5 2104 }
2105
404afe6b 2106 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode
8f0cd6ef 2107 FROM {$CFG->prefix}course_modules cm,
2108 {$CFG->prefix}course_sections cw,
2109 {$CFG->prefix}modules md,
2110 {$CFG->prefix}$modulename m
2111 WHERE cm.course = '$course->id' AND
2112 cm.instance = m.id AND
df28d6c5 2113 cm.deleted = '0' AND
8f0cd6ef 2114 cm.section = cw.id AND
2115 md.name = '$modulename' AND
cccb016a 2116 md.id = cm.module")) {
2117 return array();
2118 }
2119
2120 // Hide non-visible instances from students
2121 if (isteacher($course->id)) {
2122 $invisible = -1;
2123 } else {
2124 $invisible = 0;
2125 }
2126
2127 foreach ($modinfo as $mod) {
2128 if ($mod->mod == $modulename and $mod->visible > $invisible) {
7f12f9cd 2129 $instance = $rawmods[$mod->cm];
2130 if (!empty($mod->extra)) {
2131 $instance->extra = $mod->extra;
2132 }
2133 $outputarray[] = $instance;
cccb016a 2134 }
2135 }
2136
2137 return $outputarray;
df28d6c5 2138
2139}
2140
9fa49e22 2141
18a97fd8 2142/**
2143* determine whether a module instance is visible within a course
8f0cd6ef 2144*
2145* Given a valid module object with info about the id and course,
2146* and the module's type (eg "forum") returns whether the object
18a97fd8 2147* is visible or not
2148*
6bc502cc 2149* @param type description
18a97fd8 2150*/
580f2fbc 2151function instance_is_visible($moduletype, $module) {
580f2fbc 2152
2153 global $CFG;
2154
86e6076b 2155 if ($records = get_records_sql("SELECT cm.instance, cm.visible
580f2fbc 2156 FROM {$CFG->prefix}course_modules cm,
580f2fbc 2157 {$CFG->prefix}modules m
2158 WHERE cm.course = '$module->course' AND
8f0cd6ef 2159 cm.module = m.id AND
2160 m.name = '$moduletype' AND
2161 cm.instance = '$module->id'")) {
580f2fbc 2162
2163 foreach ($records as $record) { // there should only be one - use the first one
2164 return $record->visible;
2165 }
2166 }
2167
2168 return true; // visible by default!
2169}
2170
a3fb1c45 2171
2172
2173
9fa49e22 2174/// LOG FUNCTIONS /////////////////////////////////////////////////////
2175
2176
18a97fd8 2177/**
2178* Add an entry to the log table.
8f0cd6ef 2179*
18a97fd8 2180* Add an entry to the log table. These are "action" focussed rather
8f0cd6ef 2181* than web server hits, and provide a way to easily reconstruct what
18a97fd8 2182* any particular student has been doing.
2183*
6bc502cc 2184* @param int $course the course id
2185* @param string $module the module name - e.g. forum, journal, resource, course, user etc
2186* @param string $action view, edit, post (often but not always the same as the file.php)
2187* @param string $url the file and parameters used to see the results of the action
8f0cd6ef 2188* @param string $info additional description information
6bc502cc 2189* @param string $cm the course_module->id if there is one
2190* @param string $user if log regards $user other than $USER
18a97fd8 2191*/
69d79bc3 2192function add_to_log($courseid, $module, $action, $url="", $info="", $cm=0, $user=0) {
9fa49e22 2193
31fefa63 2194 global $db, $CFG, $USER, $REMOTE_ADDR;
9fa49e22 2195
3d94772d 2196 if ($user) {
2197 $userid = $user;
2198 } else {
2199 if (isset($USER->realuser)) { // Don't log
2200 return;
2201 }
b4bac9b6 2202 $userid = empty($USER->id) ? "0" : $USER->id;
9fa49e22 2203 }
2204
2205 $timenow = time();
2206 $info = addslashes($info);
8f0cd6ef 2207 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
9fa49e22 2208
69d79bc3 2209 $result = $db->Execute("INSERT INTO {$CFG->prefix}log (time, userid, course, ip, module, cmid, action, url, info)
2210 VALUES ('$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
ebc3bd2b 2211
ce78926d 2212 if (!$result and ($CFG->debug > 7)) {
dcb1bd3c 2213 echo "<p>Error: Could not insert a new entry to the Moodle log</p>"; // Don't throw an error
8f0cd6ef 2214 }
540995b8 2215 if (!$user and isset($USER->id)) {
222ac91b 2216 if ($courseid == SITEID) {
8f0cd6ef 2217 $db->Execute("UPDATE {$CFG->prefix}user SET lastIP='$REMOTE_ADDR', lastaccess='$timenow'
222ac91b 2218 WHERE id = '$USER->id' ");
540995b8 2219 } else if (isstudent($courseid)) {
3d94772d 2220 $db->Execute("UPDATE {$CFG->prefix}user_students SET timeaccess = '$timenow' ".
2221 "WHERE course = '$courseid' AND userid = '$userid'");
540995b8 2222 } else if (isteacher($courseid, false, false)) {
3d94772d 2223 $db->Execute("UPDATE {$CFG->prefix}user_teachers SET timeaccess = '$timenow' ".
2224 "WHERE course = '$courseid' AND userid = '$userid'");
2225 }
8f0cd6ef 2226 }
9fa49e22 2227}
2228
2229
18a97fd8 2230/**
2231* select all log records based on SQL criteria
8f0cd6ef 2232*
18a97fd8 2233* select all log records based on SQL criteria
8f0cd6ef 2234*
6bc502cc 2235* @param string $select SQL select criteria
2236* @param string $order SQL order by clause to sort the records returned
18a97fd8 2237*/
519d369f 2238function get_logs($select, $order="l.time DESC", $limitfrom="", $limitnum="", &$totalcount) {
9fa49e22 2239 global $CFG;
2240
519d369f 2241 if ($limitfrom !== "") {
2242 switch ($CFG->dbtype) {
2243 case "mysql":
2244 $limit = "LIMIT $limitfrom,$limitnum";
2245 break;
2246 case "postgres7":
2247 $limit = "LIMIT $limitnum OFFSET $limitfrom";
2248 break;
8f0cd6ef 2249 default:
519d369f 2250 $limit = "LIMIT $limitnum,$limitfrom";
2251 }
2252 } else {
2253 $limit = "";
2254 }
2255
2256 if ($order) {
2257 $order = "ORDER BY $order";
2258 }
2259
b4bac9b6 2260 $selectsql = "{$CFG->prefix}log l LEFT JOIN {$CFG->prefix}user u ON l.userid = u.id ".((strlen($select) > 0) ? "WHERE $select" : "");
519d369f 2261 $totalcount = count_records_sql("SELECT COUNT(*) FROM $selectsql");
2262
8f0cd6ef 2263 return get_records_sql("SELECT l.*, u.firstname, u.lastname, u.picture
2264 FROM $selectsql $order $limit");
9fa49e22 2265}
2266
519d369f 2267
18a97fd8 2268/**
2269* select all log records for a given course and user
8f0cd6ef 2270*
18a97fd8 2271* select all log records for a given course and user
2272*
6bc502cc 2273* @param type description
18a97fd8 2274*/
9fa49e22 2275function get_logs_usercourse($userid, $courseid, $coursestart) {
2276 global $CFG;
2277
da0c90c3 2278 if ($courseid) {
2700d113 2279 $courseselect = " AND course = '$courseid' ";
2280 } else {
2281 $courseselect = '';
da0c90c3 2282 }
2283
8f0cd6ef 2284 return get_records_sql("SELECT floor((`time` - $coursestart)/86400) as day, count(*) as num
2285 FROM {$CFG->prefix}log
2286 WHERE userid = '$userid'
da0c90c3 2287 AND `time` > '$coursestart' $courseselect
9fa49e22 2288 GROUP BY day ");
2289}
2290
18a97fd8 2291/**
2292* select all log records for a given course, user, and day
8f0cd6ef 2293*
18a97fd8 2294* select all log records for a given course, user, and day
2295*
6bc502cc 2296* @param type description
18a97fd8 2297*/
9fa49e22 2298function get_logs_userday($userid, $courseid, $daystart) {
2299 global $CFG;
2300
7e4a6488 2301 if ($courseid) {
2700d113 2302 $courseselect = " AND course = '$courseid' ";
2303 } else {
2304 $courseselect = '';
7e4a6488 2305 }
2306
9fa49e22 2307 return get_records_sql("SELECT floor((`time` - $daystart)/3600) as hour, count(*) as num
2308 FROM {$CFG->prefix}log
8f0cd6ef 2309 WHERE userid = '$userid'
7e4a6488 2310 AND `time` > '$daystart' $courseselect
9fa49e22 2311 GROUP BY hour ");
2312}
2313
b4bac9b6 2314/**
2315 * Returns an object with counts of failed login attempts
2316 *
8f0cd6ef 2317 * Returns information about failed login attempts. If the current user is
2318 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 2319 * number of accounts. For non-admins, only the attempts on the given user
2320 * are shown.
2321 *
2322 * @param mode - admin, teacher or everybody
2323 * @param username - the username we are searching for
2324 * @param lastlogin - the date from which we are searching
2325 */
2326
2327function count_login_failures($mode, $username, $lastlogin) {
2328
2329 $select = "module='login' AND action='error' AND time > $lastlogin";
2330
2331 if (isadmin()) { // Return information about all accounts
2332 if ($count->attempts = count_records_select('log', $select)) {
2333 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
2334 return $count;
2335 }
2336 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacher())) {
2337 if ($count->attempts = count_records_select('log', "$select AND info = '$username'")) {
2338 return $count;
2339 }
2340 }
2341 return NULL;
2342}
2343
2344
a3fb1c45 2345/// GENERAL HELPFUL THINGS ///////////////////////////////////
2346
18a97fd8 2347/**
2348* dump a given object's information in a PRE block
8f0cd6ef 2349*
18a97fd8 2350* dump a given object's information in a PRE block
2351* Mostly just for debugging
2352*
6bc502cc 2353* @param type description
18a97fd8 2354*/
a3fb1c45 2355function print_object($object) {
a3fb1c45 2356
dcb1bd3c 2357 echo "<pre>";
2b051f1c 2358 print_r($object);
dcb1bd3c 2359 echo "</pre>";
a3fb1c45 2360}
2361
2362
9fa49e22 2363
9d5b689c 2364// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
df28d6c5 2365?>