Merged from MOODLE_15_STABLE: Fixing bug 3977: properly for HEAD since we're dropping...
[moodle.git] / lib / datalib.php
CommitLineData
6078ba30 1<?php // $Id$
7cf1c7bd 2
3/**
4 * Library of functions for database manipulation.
5 *
7cf1c7bd 6 * Other main libraries:
7 * - weblib.php - functions that produce web output
8 * - moodlelib.php - general-purpose Moodle functions
6159ce65 9 * @author Martin Dougiamas and many others
7cf1c7bd 10 * @version $Id$
89dcb99d 11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 12 * @package moodlecore
13 */
14
df28d6c5 15
7d8c2ec3 16/// GLOBAL CONSTANTS /////////////////////////////////////////////////////////
7cf1c7bd 17
7d8c2ec3 18if ($SITE = get_site()) {
7cf1c7bd 19 /**
fbc21ae8 20 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
7cf1c7bd 21 */
7d8c2ec3 22 define('SITEID', $SITE->id);
23} else {
7cf1c7bd 24 /**
25 * @ignore
26 */
7d8c2ec3 27 define('SITEID', 1);
28}
222ac91b 29
df28d6c5 30/// FUNCTIONS FOR DATABASE HANDLING ////////////////////////////////
222ac91b 31
18a97fd8 32/**
7cf1c7bd 33 * Execute a given sql command string
34 *
35 * Completely general function - it just runs some SQL and reports success.
36 *
fbc21ae8 37 * @uses $db
38 * @param string $command The sql string you wish to be executed.
7290c7fa 39 * @param bool $feedback Set this argument to true if the results generated should be printed. Default is true.
7cf1c7bd 40 * @return string
41 */
df28d6c5 42function execute_sql($command, $feedback=true) {
43/// Completely general function - it just runs some SQL and reports success.
44
45 global $db;
8f0cd6ef 46
1734f08e 47 $olddebug = $db->debug;
48
49 if (!$feedback) {
50 $db->debug = false;
51 }
853df85e 52
53 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1734f08e 54
d4419d55 55 $result = $db->Execute($command);
df28d6c5 56
1734f08e 57 $db->debug = $olddebug;
58
df28d6c5 59 if ($result) {
60 if ($feedback) {
a8f68426 61 notify(get_string('success'), 'notifysuccess');
df28d6c5 62 }
63 return true;
64 } else {
65 if ($feedback) {
fbc21ae8 66 echo '<p><font color="red"><strong>'. get_string('error') .'</strong></font></p>';
df28d6c5 67 }
acd2279e 68 if (!empty($CFG->dblogerror)) {
31df0bb8 69 $debug=array_shift(debug_backtrace());
acd2279e 70 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $command");
71 }
df28d6c5 72 return false;
73 }
74}
1ed5abc8 75/**
76* on DBs that support it, switch to transaction mode and begin a transaction
77* you'll need to ensure you call commit_sql() or your changes *will* be lost
78* this is _very_ useful for massive updates
79*/
80function begin_sql() {
81/// Completely general function - it just runs some SQL and reports success.
82
83 global $CFG;
84 if ($CFG->dbtype === 'postgres7') {
85 return execute_sql('BEGIN', false);
86 }
87 return true;
88}
c54a5943 89/**
90* on DBs that support it, commit the transaction
91*/
92function rollback_sql() {
93/// Completely general function - it just runs some SQL and reports success.
94
95 global $CFG;
96 if ($CFG->dbtype === 'postgres7') {
97 return execute_sql('ROLLBACK', false);
98 }
99 return true;
100}
101
102
6b7f8df2 103
104/**
105 * returns db specific uppercase function
106 */
107function db_uppercase() {
108 global $CFG;
109 switch (strtolower($CFG->dbtype)) {
110
111 case "postgres7":
112 return "upper";
113 break;
114 case "mysql":
115 default:
116 return "ucase";
117 break;
118 }
119}
120
121/**
122 * returns db specific lowercase function
123 */
124function db_lowercase() {
125 global $CFG;
126 switch (strtolower($CFG->dbtype)) {
127
128 case "postgres7":
129 return "lower";
130 break;
131 case "mysql":
132 default:
133 return "lcase";
134 break;
135 }
136}
137
1ed5abc8 138/**
139* on DBs that support it, commit the transaction
140*/
141function commit_sql() {
142/// Completely general function - it just runs some SQL and reports success.
143
144 global $CFG;
145 if ($CFG->dbtype === 'postgres7') {
146 return execute_sql('COMMIT', false);
147 }
148 return true;
149}
df28d6c5 150
7cf1c7bd 151/**
152 * Run an arbitrary sequence of semicolon-delimited SQL commands
153 *
154 * Assumes that the input text (file or string) consists of
155 * a number of SQL statements ENDING WITH SEMICOLONS. The
156 * semicolons MUST be the last character in a line.
e5cf5750 157 * Lines that are blank or that start with "#" or "--" (postgres) are ignored.
7cf1c7bd 158 * Only tested with mysql dump files (mysqldump -p -d moodle)
159 *
fbc21ae8 160 * @uses $CFG
7cf1c7bd 161 * @param string $sqlfile The path where a file with sql commands can be found on the server.
162 * @param string $sqlstring If no path is supplied then a string with semicolon delimited sql
163 * commands can be supplied in this argument.
7290c7fa 164 * @return bool Returns true if databse was modified successfully.
7cf1c7bd 165 */
d4419d55 166function modify_database($sqlfile='', $sqlstring='') {
df28d6c5 167
168 global $CFG;
169
8f0cd6ef 170 $success = true; // Let's be optimistic
2b051f1c 171
172 if (!empty($sqlfile)) {
173 if (!is_readable($sqlfile)) {
174 $success = false;
d4419d55 175 echo '<p>Tried to modify database, but "'. $sqlfile .'" doesn\'t exist!</p>';
2b051f1c 176 return $success;
177 } else {
178 $lines = file($sqlfile);
179 }
180 } else {
a9676376 181 $sqlstring = trim($sqlstring);
182 if ($sqlstring{strlen($sqlstring)-1} != ";") {
183 $sqlstring .= ";"; // add it in if it's not there.
184 }
2b051f1c 185 $lines[] = $sqlstring;
186 }
187
d4419d55 188 $command = '';
2b051f1c 189
190 foreach ($lines as $line) {
191 $line = rtrim($line);
192 $length = strlen($line);
193
e5cf5750 194 if ($length and $line[0] <> '#' and $line[0].$line[1] <> '--') {
d4419d55 195 if (substr($line, $length-1, 1) == ';') {
2b051f1c 196 $line = substr($line, 0, $length-1); // strip ;
197 $command .= $line;
d4419d55 198 $command = str_replace('prefix_', $CFG->prefix, $command); // Table prefixes
2b051f1c 199 if (! execute_sql($command)) {
200 $success = false;
df28d6c5 201 }
d4419d55 202 $command = '';
2b051f1c 203 } else {
204 $command .= $line;
df28d6c5 205 }
206 }
df28d6c5 207 }
208
209 return $success;
2b051f1c 210
df28d6c5 211}
212
a3fb1c45 213/// FUNCTIONS TO MODIFY TABLES ////////////////////////////////////////////
214
18a97fd8 215/**
fbc21ae8 216 * Add a new field to a table, or modify an existing one (if oldfield is defined).
217 *
218 * @uses $CFG
219 * @uses $db
89dcb99d 220 * @param string $table ?
221 * @param string $oldfield ?
222 * @param string $field ?
7c81cc29 223 * @param string $type ?
89dcb99d 224 * @param string $size ?
225 * @param string $signed ?
226 * @param string $default ?
227 * @param string $null ?
fbc21ae8 228 * @todo Finish documenting this function
229 */
18a97fd8 230
d4419d55 231function table_column($table, $oldfield, $field, $type='integer', $size='10',
232 $signed='unsigned', $default='0', $null='not null', $after='') {
8a230a7d 233 global $CFG, $db;
a3fb1c45 234
235 switch (strtolower($CFG->dbtype)) {
236
d4419d55 237 case 'mysql':
238 case 'mysqlt':
a3fb1c45 239
240 switch (strtolower($type)) {
d4419d55 241 case 'text':
242 $type = 'TEXT';
243 $signed = '';
c2cb4545 244 break;
d4419d55 245 case 'integer':
246 $type = 'INTEGER('. $size .')';
a3fb1c45 247 break;
d4419d55 248 case 'varchar':
249 $type = 'VARCHAR('. $size .')';
250 $signed = '';
a3fb1c45 251 break;
2ecdff78 252 case 'char':
253 $type = 'CHAR('. $size .')';
254 $signed = '';
255 break;
a3fb1c45 256 }
257
258 if (!empty($oldfield)) {
d4419d55 259 $operation = 'CHANGE '. $oldfield .' '. $field;
a3fb1c45 260 } else {
d4419d55 261 $operation = 'ADD '. $field;
a3fb1c45 262 }
263
d4419d55 264 $default = 'DEFAULT \''. $default .'\'';
a3fb1c45 265
266 if (!empty($after)) {
d4419d55 267 $after = 'AFTER `'. $after .'`';
a3fb1c45 268 }
269
d4419d55 270 return execute_sql('ALTER TABLE '. $CFG->prefix . $table .' '. $operation .' '. $type .' '. $signed .' '. $default .' '. $null .' '. $after);
a3fb1c45 271 break;
272
d4419d55 273 case 'postgres7': // From Petri Asikainen
8a230a7d 274 //Check db-version
275 $dbinfo = $db->ServerInfo();
29622339 276 $dbver = substr($dbinfo['version'],0,3);
8f0cd6ef 277
5a4d292b 278 //to prevent conflicts with reserved words
d4419d55 279 $realfield = '"'. $field .'"';
280 $field = '"'. $field .'_alter_column_tmp"';
281 $oldfield = '"'. $oldfield .'"';
5a4d292b 282
283 switch (strtolower($type)) {
9c851359 284 case 'tinyint':
d4419d55 285 case 'integer':
09d4c9a9 286 if ($size <= 4) {
d4419d55 287 $type = 'INT2';
8f0cd6ef 288 }
09d4c9a9 289 if ($size <= 10) {
d4419d55 290 $type = 'INT';
5a4d292b 291 }
09d4c9a9 292 if ($size > 10) {
d4419d55 293 $type = 'INT8';
5a4d292b 294 }
295 break;
d4419d55 296 case 'varchar':
297 $type = 'VARCHAR('. $size .')';
5a4d292b 298 break;
2ecdff78 299 case 'char':
300 $type = 'CHAR('. $size .')';
301 $signed = '';
302 break;
5a4d292b 303 }
304
d4419d55 305 $default = '\''. $default .'\'';
5a4d292b 306
307 //After is not implemented in postgesql
308 //if (!empty($after)) {
309 // $after = "AFTER '$after'";
310 //}
311
d05024a7 312 //Use transactions
d4419d55 313 execute_sql('BEGIN');
d05024a7 314
7c81cc29 315 //Always use temporary column
d4419d55 316 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ADD COLUMN '. $field .' '. $type);
d05024a7 317 //Add default values
d4419d55 318 execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .'='. $default);
8f0cd6ef 319
5a4d292b 320
d4419d55 321 if ($dbver >= '7.3') {
8a230a7d 322 // modifying 'not null' is posible before 7.3
323 //update default values to table
7c56e42d 324 if (strtoupper($null) == 'NOT NULL') {
d4419d55 325 execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .'='. $default .' WHERE '. $field .' IS NULL');
326 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $null);
8a230a7d 327 } else {
d4419d55 328 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' DROP NOT NULL');
8a230a7d 329 }
5a4d292b 330 }
8a230a7d 331
d4419d55 332 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET DEFAULT '. $default);
8f0cd6ef 333
d4419d55 334 if ( $oldfield != '""' ) {
7c81cc29 335
336 // We are changing the type of a column. This may require doing some casts...
337 $casting = '';
338 $oldtype = column_type($table, $oldfield);
339 $newtype = column_type($table, $field);
340
341 // Do we need a cast?
342 if($newtype == 'N' && $oldtype == 'C') {
343 $casting = 'CAST(CAST('.$oldfield.' AS TEXT) AS REAL)';
344 }
9feb9a19 345 else if($newtype == 'I' && $oldtype == 'C') {
7c81cc29 346 $casting = 'CAST(CAST('.$oldfield.' AS TEXT) AS INTEGER)';
347 }
348 else {
349 $casting = $oldfield;
350 }
351
352 // Run the update query, casting as necessary
353 execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .' = '. $casting);
d4419d55 354 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' DROP COLUMN '. $oldfield);
d05024a7 355 }
5a4d292b 356
7cf1c7bd 357 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' RENAME COLUMN '. $field .' TO '. $realfield);
8f0cd6ef 358
d4419d55 359 return execute_sql('COMMIT');
5a4d292b 360 break;
a3fb1c45 361
362 default:
363 switch (strtolower($type)) {
d4419d55 364 case 'integer':
365 $type = 'INTEGER';
a3fb1c45 366 break;
d4419d55 367 case 'varchar':
368 $type = 'VARCHAR';
92230499 369 break;
a3fb1c45 370 }
371
d4419d55 372 $default = 'DEFAULT \''. $default .'\'';
a3fb1c45 373
374 if (!empty($after)) {
d4419d55 375 $after = 'AFTER '. $after;
a3fb1c45 376 }
377
378 if (!empty($oldfield)) {
d4419d55 379 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' RENAME COLUMN '. $oldfield .' '. $field);
a3fb1c45 380 } else {
d4419d55 381 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ADD COLUMN '. $field .' '. $type);
a3fb1c45 382 }
383
d4419d55 384 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $null);
385 return execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $default);
a3fb1c45 386 break;
387
388 }
389}
390
7c81cc29 391/**
392 * Get the data type of a table column, using an ADOdb MetaType() call.
393 *
394 * @uses $CFG
395 * @uses $db
8a7d9d15 396 * @param string $table The name of the database table
397 * @param string $column The name of the field in the table
398 * @return string Field type or false if error
7c81cc29 399 */
400
401function column_type($table, $column) {
402 global $CFG, $db;
403
853df85e 404 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
405
d20f58e7 406 if(!$rs = $db->Execute('SELECT '.$column.' FROM '.$CFG->prefix.$table.' LIMIT 0')) {
7c81cc29 407 return false;
408 }
409
410 $field = $rs->FetchField(0);
411 return $rs->MetaType($field->type);
412}
a3fb1c45 413
414
415/// GENERIC FUNCTIONS TO CHECK AND COUNT RECORDS ////////////////////////////////////////
df28d6c5 416
18a97fd8 417/**
fbc21ae8 418 * Returns true or false depending on whether the specified record exists
419 *
420 * @uses $CFG
421 * @param string $table The database table to be checked for the record.
422 * @param string $field1 The first table field to be checked for a given value. Do not supply a field1 string to leave out a WHERE clause altogether.
423 * @param string $value1 The value to match if field1 is specified.
424 * @param string $field2 The second table field to be checked for a given value.
425 * @param string $value2 The value to match if field2 is specified.
426 * @param string $field3 The third table field to be checked for a given value.
427 * @param string $value3 The value to match if field3 is specified.
7290c7fa 428 * @return bool True if record exists
fbc21ae8 429 */
d4419d55 430function record_exists($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
df28d6c5 431
432 global $CFG;
433
5c63e0c4 434 if ($field1) {
d4419d55 435 $select = 'WHERE '. $field1 .' = \''. $value1 .'\'';
9fa49e22 436 if ($field2) {
d4419d55 437 $select .= ' AND '. $field2 .' = \''. $value2 .'\'';
9fa49e22 438 if ($field3) {
d4419d55 439 $select .= ' AND '. $field3 .' = \''. $value3 .'\'';
df28d6c5 440 }
441 }
5c63e0c4 442 } else {
d4419d55 443 $select = '';
df28d6c5 444 }
445
d4419d55 446 return record_exists_sql('SELECT * FROM '. $CFG->prefix . $table .' '. $select .' LIMIT 1');
df28d6c5 447}
448
449
18a97fd8 450/**
fbc21ae8 451* Determine whether a specified record exists.
8f0cd6ef 452*
fbc21ae8 453* This function returns true if the SQL executed returns records.
18a97fd8 454*
fbc21ae8 455* @uses $CFG
456* @uses $db
457* @param string $sql The SQL statement to be executed.
7290c7fa 458* @return bool
18a97fd8 459*/
df28d6c5 460function record_exists_sql($sql) {
df28d6c5 461
06b1db82 462 global $CFG, $db;
df28d6c5 463
853df85e 464 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
465
9c7fee6c 466 if (!$rs = $db->Execute($sql)) {
2eef791f 467 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 468 notify($db->ErrorMsg().'<br /><br />'.$sql);
9c7fee6c 469 }
acd2279e 470 if (!empty($CFG->dblogerror)) {
31df0bb8 471 $debug=array_shift(debug_backtrace());
acd2279e 472 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
473 }
9c7fee6c 474 return false;
475 }
df28d6c5 476
477 if ( $rs->RecordCount() ) {
478 return true;
479 } else {
480 return false;
481 }
8a7d9d15 482 }
df28d6c5 483
484
18a97fd8 485/**
fbc21ae8 486 * Get all specified records from the specified table and return the count of them
487 *
488 * @uses $CFG
489 * @param string $table The database table to be checked against.
490 * @param string $field1 The first table field to be checked for a given value. Do not supply a field1 string to leave out a WHERE clause altogether.
491 * @param string $value1 The value to match if field1 is specified.
492 * @param string $field2 The second table field to be checked for a given value.
493 * @param string $value2 The value to match if field2 is specified.
494 * @param string $field3 The third table field to be checked for a given value.
495 * @param string $value3 The value to match if field3 is specified.
496 * @return int The count of records returned from the specified criteria.
497 */
d4419d55 498function count_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
df28d6c5 499
500 global $CFG;
501
5c63e0c4 502 if ($field1) {
d4419d55 503 $select = 'WHERE '. $field1 .' = \''. $value1 .'\'';
9fa49e22 504 if ($field2) {
d4419d55 505 $select .= ' AND '. $field2 .' = \''. $value2 .'\'';
9fa49e22 506 if ($field3) {
d4419d55 507 $select .= ' AND '. $field3 .' = \''. $value3 .'\'';
df28d6c5 508 }
509 }
5c63e0c4 510 } else {
d4419d55 511 $select = '';
df28d6c5 512 }
513
d4419d55 514 return count_records_sql('SELECT COUNT(*) FROM '. $CFG->prefix . $table .' '. $select);
df28d6c5 515}
516
18a97fd8 517/**
fbc21ae8 518 * Get all the records and count them
519 *
520 * @uses $CFG
521 * @param string $table The database table to be checked against.
522 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
523 * @param string $countitem The count string to be used in the SQL call. Default is COUNT(*).
524 * @return int The count of records returned from the specified criteria.
d0d56205 525 */
d4419d55 526function count_records_select($table, $select='', $countitem='COUNT(*)') {
9fa49e22 527
528 global $CFG;
529
d26d7ed0 530 if ($select) {
d4419d55 531 $select = 'WHERE '.$select;
d26d7ed0 532 }
533
d4419d55 534 return count_records_sql('SELECT '. $countitem .' FROM '. $CFG->prefix . $table .' '. $select);
9fa49e22 535}
536
537
18a97fd8 538/**
fbc21ae8 539 * Get all the records returned from the specified SQL call and return the count of them
540 *
541 * @uses $CFG
542 * @uses $db
543 * @param string $sql The SQL string you wish to be executed.
544 * @return int The count of records returned from the specified SQL string.
545 */
df28d6c5 546function count_records_sql($sql) {
df28d6c5 547
06b1db82 548 global $CFG, $db;
df28d6c5 549
853df85e 550 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
551
d4419d55 552 $rs = $db->Execute($sql);
9c7fee6c 553 if (!$rs) {
2eef791f 554 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 555 notify($db->ErrorMsg() .'<br /><br />'. $sql);
9c7fee6c 556 }
acd2279e 557 if (!empty($CFG->dblogerror)) {
31df0bb8 558 $debug=array_shift(debug_backtrace());
acd2279e 559 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
560 }
9c7fee6c 561 return 0;
562 }
df28d6c5 563
564 return $rs->fields[0];
565}
566
a3fb1c45 567
568
569
570/// GENERIC FUNCTIONS TO GET, INSERT, OR UPDATE DATA ///////////////////////////////////
571
18a97fd8 572/**
fbc21ae8 573 * Get a single record as an object
574 *
575 * @uses $CFG
576 * @param string $table The name of the table to select from
577 * @param string $field1 The name of the field for the first criteria
578 * @param string $value1 The value of the field for the first criteria
579 * @param string $field2 The name of the field for the second criteria
580 * @param string $value2 The value of the field for the second criteria
581 * @param string $field3 The name of the field for the third criteria
582 * @param string $value3 The value of the field for the third criteria
583 * @return object(fieldset) A fieldset object containing the first record selected
fbc21ae8 584 */
d0d0cd9c 585function get_record($table, $field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields='*') {
8f0cd6ef 586
7427070a 587 global $CFG ;
df28d6c5 588
d4419d55 589 $select = 'WHERE '. $field1 .' = \''. $value1 .'\'';
df28d6c5 590
9fa49e22 591 if ($field2) {
d4419d55 592 $select .= ' AND '. $field2 .' = \''. $value2 .'\'';
9fa49e22 593 if ($field3) {
d4419d55 594 $select .= ' AND '. $field3 .' = \''. $value3 .'\'';
df28d6c5 595 }
596 }
597
d0d0cd9c 598 return get_record_sql('SELECT '.$fields.' FROM '. $CFG->prefix . $table .' '. $select);
df28d6c5 599}
600
18a97fd8 601/**
fbc21ae8 602 * Get a single record as an object using the specified SQL statement
603 *
604 * A LIMIT is normally added to only look for 1 record
8a7d9d15 605 * If debugging is OFF only the first record is returned even if there is
606 * more than one matching record!
fbc21ae8 607 *
608 * @uses $CFG
609 * @uses $db
610 * @param string $sql The SQL string you wish to be executed.
8a7d9d15 611 * @return Found record as object. False if not found or error
fbc21ae8 612 */
e84a246a 613function get_record_sql($sql, $expectmultiple=false) {
df28d6c5 614
4d7a3735 615 global $db, $CFG;
df28d6c5 616
e84a246a 617 if (isset($CFG->debug) && $CFG->debug > 7 && !$expectmultiple) { // Debugging mode - don't use limit
d4419d55 618 $limit = '';
4d7a3735 619 } else {
d4419d55 620 $limit = ' LIMIT 1'; // Workaround - limit to one record
4d7a3735 621 }
622
853df85e 623 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
624
d4419d55 625 if (!$rs = $db->Execute($sql . $limit)) {
2eef791f 626 if (isset($CFG->debug) and $CFG->debug > 7) { // Debugging mode - print checks
d4419d55 627 notify( $db->ErrorMsg() . '<br /><br />'. $sql . $limit );
7618a8eb 628 }
acd2279e 629 if (!empty($CFG->dblogerror)) {
31df0bb8 630 $debug=array_shift(debug_backtrace());
acd2279e 631 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql$limit");
632 }
7618a8eb 633 return false;
634 }
4d7a3735 635
7618a8eb 636 if (!$recordcount = $rs->RecordCount()) {
637 return false; // Found no records
4d7a3735 638 }
df28d6c5 639
7618a8eb 640 if ($recordcount == 1) { // Found one record
df28d6c5 641 return (object)$rs->fields;
4d7a3735 642
7618a8eb 643 } else { // Error: found more than one record
d4419d55 644 notify('Error: Turn off debugging to hide this error.');
645 notify($sql . $limit);
4d7a3735 646 if ($records = $rs->GetAssoc(true)) {
d4419d55 647 notify('Found more than one record in get_record_sql !');
4d7a3735 648 print_object($records);
4d7a3735 649 } else {
d4419d55 650 notify('Very strange error in get_record_sql !');
7618a8eb 651 print_object($rs);
4d7a3735 652 }
51b0e824 653 print_continue("$CFG->wwwroot/$CFG->admin/config.php");
df28d6c5 654 }
655}
656
18a97fd8 657/**
fbc21ae8 658 * Gets one record from a table, as an object
659 *
660 * @uses $CFG
661 * @param string $table The database table to be checked against.
662 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
663 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 664 * @return object|false Returns an array of found records (as objects) or false if no records or error occured.
d0d56205 665 */
d4419d55 666function get_record_select($table, $select='', $fields='*') {
18496c59 667
668 global $CFG;
669
670 if ($select) {
d4419d55 671 $select = 'WHERE '. $select;
18496c59 672 }
673
d4419d55 674 return get_record_sql('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select);
18496c59 675}
676
677
18a97fd8 678/**
fbc21ae8 679 * Get a number of records as an array of objects
680 *
681 * Can optionally be sorted eg "time ASC" or "time DESC"
682 * If "fields" is specified, only those fields are returned
683 * The "key" is the first column returned, eg usually "id"
684 * limitfrom and limitnum must both be specified or not at all
685 *
686 * @uses $CFG
687 * @param string $table The database table to be checked against.
8a7d9d15 688 * @param string $field The database field name to search
689 * @param string $value The value to search for in $field
690 * @param string $sort Sort order (as valid SQL sort parameter)
fbc21ae8 691 * @param string $fields A comma separated list of fields to be returned from the chosen table.
8a7d9d15 692 * @param int $limitfrom Return a subset of results starting at this value (*must* set $limitnum)
693 * @param int $limitnum Return a subset of results, return this number (*must* set $limitfrom)
7290c7fa 694 * @return object|false Returns an array of found records (as objects) or false if no records or error occured.
fbc21ae8 695 */
d4419d55 696function get_records($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
df28d6c5 697
698 global $CFG;
699
9fa49e22 700 if ($field) {
d4419d55 701 $select = 'WHERE '. $field .' = \''. $value .'\'';
5c63e0c4 702 } else {
d4419d55 703 $select = '';
df28d6c5 704 }
5c63e0c4 705
d4419d55 706 if ($limitfrom !== '') {
29daf3a0 707 $limit = sql_paging_limit($limitfrom, $limitnum);
0eeac484 708 } else {
d4419d55 709 $limit = '';
0eeac484 710 }
711
df28d6c5 712 if ($sort) {
d4419d55 713 $sort = 'ORDER BY '. $sort;
df28d6c5 714 }
715
d4419d55 716 return get_records_sql('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select .' '. $sort .' '. $limit);
df28d6c5 717}
718
18a97fd8 719/**
fbc21ae8 720 * Get a number of records as an array of objects
721 *
722 * Can optionally be sorted eg "time ASC" or "time DESC"
723 * "select" is a fragment of SQL to define the selection criteria
724 * The "key" is the first column returned, eg usually "id"
725 * limitfrom and limitnum must both be specified or not at all
726 *
727 * @uses $CFG
728 * @param string $table The database table to be checked against.
729 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
8a7d9d15 730 * @param string $sort Sort order (as valid SQL sort parameter)
fbc21ae8 731 * @param string $fields A comma separated list of fields to be returned from the chosen table.
8a7d9d15 732 * @param int $limitfrom Return a subset of results starting at this value (*must* set $limitnum)
733 * @param int $limitnum Return a subset of results, return this number (*must* set $limitfrom)
7290c7fa 734 * @return object|false Returns an array of found records (as objects) or false if no records or error occured.
fbc21ae8 735 */
d4419d55 736function get_records_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
9fa49e22 737
738 global $CFG;
739
d26d7ed0 740 if ($select) {
d4419d55 741 $select = 'WHERE '. $select;
5c63e0c4 742 }
743
d4419d55 744 if ($limitfrom !== '') {
29daf3a0 745 $limit = sql_paging_limit($limitfrom, $limitnum);
4f91b296 746 } else {
d4419d55 747 $limit = '';
4f91b296 748 }
749
5c63e0c4 750 if ($sort) {
d4419d55 751 $sort = 'ORDER BY '. $sort;
d26d7ed0 752 }
753
d4419d55 754 return get_records_sql('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select .' '. $sort .' '. $limit);
9fa49e22 755}
756
df28d6c5 757
18a97fd8 758/**
fbc21ae8 759 * Get a number of records as an array of objects
760 *
761 * Differs from get_records() in that the values variable
762 * can be a comma-separated list of values eg "4,5,6,10"
763 * Can optionally be sorted eg "time ASC" or "time DESC"
764 * The "key" is the first column returned, eg usually "id"
765 *
766 * @uses $CFG
767 * @param string $table The database table to be checked against.
8a7d9d15 768 * @param string $field The field to search
769 * @param string $values Comma separated list of possible value
770 * @param string $sort Sort order (as valid SQL sort parameter)
fbc21ae8 771 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 772 * @return object|false Returns an array of found records (as objects) or false if no records or error occured.
fbc21ae8 773 */
d4419d55 774function get_records_list($table, $field='', $values='', $sort='', $fields='*') {
df28d6c5 775
776 global $CFG;
777
9fa49e22 778 if ($field) {
d4419d55 779 $select = 'WHERE '. $field .' IN ( '. $values .')';
5c63e0c4 780 } else {
d4419d55 781 $select = '';
df28d6c5 782 }
5c63e0c4 783
df28d6c5 784 if ($sort) {
d4419d55 785 $sort = 'ORDER BY '. $sort;
df28d6c5 786 }
787
d4419d55 788 return get_records_sql('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select .' '. $sort);
df28d6c5 789}
790
791
9fa49e22 792
18a97fd8 793/**
fbc21ae8 794 * Get a number of records as an array of objects
795 *
796 * The "key" is the first column returned, eg usually "id"
797 * The sql statement is provided as a string.
798 *
799 * @uses $CFG
800 * @uses $db
801 * @param string $sql The SQL string you wish to be executed.
7290c7fa 802 * @return object|false Returns an array of found records (as objects) or false if no records or error occured.
fbc21ae8 803 */
df28d6c5 804function get_records_sql($sql) {
df28d6c5 805
fbc21ae8 806 global $CFG, $db;
df28d6c5 807
853df85e 808 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
809
9c7fee6c 810 if (!$rs = $db->Execute($sql)) {
2eef791f 811 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 812 notify($db->ErrorMsg() .'<br /><br />'. $sql);
9c7fee6c 813 }
acd2279e 814 if (!empty($CFG->dblogerror)) {
31df0bb8 815 $debug=array_shift(debug_backtrace());
acd2279e 816 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
817 }
9c7fee6c 818 return false;
819 }
8f0cd6ef 820
df28d6c5 821 if ( $rs->RecordCount() > 0 ) {
822 if ($records = $rs->GetAssoc(true)) {
823 foreach ($records as $key => $record) {
824 $objects[$key] = (object) $record;
825 }
826 return $objects;
827 } else {
828 return false;
829 }
830 } else {
831 return false;
832 }
833}
834
18a97fd8 835/**
8a7d9d15 836* Get a number of first two columns in records as an associative array of objects
8f0cd6ef 837*
18a97fd8 838* Can optionally be sorted eg "time ASC" or "time DESC"
839* If "fields" is specified, only those fields are returned
840* The "key" is the first column returned, eg usually "id"
8f0cd6ef 841*
fbc21ae8 842 * @uses $CFG
843 * @param string $table The database table to be checked against.
8a7d9d15 844 * @param string $field The name of the field to search
845 * @param string $value The value to search for
846 * @param string $sort Sort order (optional) - a valid SQL order parameter
fbc21ae8 847 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 848 * @return object|bool An associative array with the results from the SQL call. False if error.
18a97fd8 849*/
d4419d55 850function get_records_menu($table, $field='', $value='', $sort='', $fields='*') {
9fa49e22 851
852 global $CFG;
853
854 if ($field) {
d4419d55 855 $select = 'WHERE '. $field .' = \''. $value .'\'';
5c63e0c4 856 } else {
d4419d55 857 $select = '';
9fa49e22 858 }
5c63e0c4 859
9fa49e22 860 if ($sort) {
d4419d55 861 $sort = 'ORDER BY '. $sort;
9fa49e22 862 }
863
d4419d55 864 return get_records_sql_menu('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select .' '. $sort);
9fa49e22 865}
866
fbc21ae8 867
18a97fd8 868/**
8a7d9d15 869 * Get a number of records (first 2 columns) as an associative array of values
fbc21ae8 870 *
871 * Can optionally be sorted eg "time ASC" or "time DESC"
872 * "select" is a fragment of SQL to define the selection criteria
873 * Returns associative array of first two fields
874 *
875 * @uses $CFG
876 * @param string $table The database table to be checked against.
877 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
8a7d9d15 878 * @param string $sort Sort order (optional) - a valid SQL order parameter
fbc21ae8 879 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 880 * @return object|bool An associative array with the results from the SQL call. False if error
fbc21ae8 881 */
d4419d55 882function get_records_select_menu($table, $select='', $sort='', $fields='*') {
9fa49e22 883
884 global $CFG;
885
d26d7ed0 886 if ($select) {
d4419d55 887 $select = 'WHERE '. $select;
d26d7ed0 888 }
889
5c63e0c4 890 if ($sort) {
d4419d55 891 $sort = 'ORDER BY '. $sort;
5c63e0c4 892 }
893
d4419d55 894 return get_records_sql_menu('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select .' '. $sort);
9fa49e22 895}
896
897
18a97fd8 898/**
8a7d9d15 899 * Retrieve an associative array of the first two columns returned from a SQL statment.
fbc21ae8 900 *
901 * Given a SQL statement, this function returns an associative
902 * array of the first two columns. This is most useful in
903 * combination with the {@link choose_from_menu()} function to create
904 * a form menu.
905 *
906 * @uses $CFG
907 * @uses $db
908 * @param string $sql The SQL string you wish to be executed.
7290c7fa 909 * @return object|bool An associative array with the results from the SQL call. False if error.
fbc21ae8 910 * @todo Finish documenting this function
911 */
df28d6c5 912function get_records_sql_menu($sql) {
df28d6c5 913
06b1db82 914 global $CFG, $db;
df28d6c5 915
853df85e 916
917 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
918
9c7fee6c 919 if (!$rs = $db->Execute($sql)) {
2eef791f 920 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 921 notify($db->ErrorMsg() .'<br /><br />'. $sql);
9c7fee6c 922 }
acd2279e 923 if (!empty($CFG->dblogerror)) {
31df0bb8 924 $debug=array_shift(debug_backtrace());
acd2279e 925 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
926 }
9c7fee6c 927 return false;
928 }
df28d6c5 929
930 if ( $rs->RecordCount() > 0 ) {
931 while (!$rs->EOF) {
932 $menu[$rs->fields[0]] = $rs->fields[1];
933 $rs->MoveNext();
934 }
935 return $menu;
8f0cd6ef 936
df28d6c5 937 } else {
938 return false;
939 }
940}
941
18a97fd8 942/**
fbc21ae8 943 * Get a single field from a database record
944 *
945 * @uses $CFG
946 * @uses $db
947 * @param string $table The database table to be checked against.
948 * @param string $field1 The first table field to be checked for a given value. Do not supply a field1 string to leave out a WHERE clause altogether.
949 * @param string $value1 The value to match if field1 is specified.
950 * @param string $field2 The second table field to be checked for a given value.
951 * @param string $value2 The value to match if field2 is specified.
952 * @param string $field3 The third table field to be checked for a given value.
953 * @param string $value3 The value to match if field3 is specified.
c6d15803 954 * @return mixed|false Returns the value return from the SQL statment or false if an error occured.
fbc21ae8 955 * @todo Finish documenting this function
956 */
d4419d55 957function get_field($table, $return, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
df28d6c5 958
959 global $db, $CFG;
960
d4419d55 961 $select = 'WHERE '. $field1 .' = \''. $value1 .'\'';
ec2a28a6 962
963 if ($field2) {
d4419d55 964 $select .= ' AND '. $field2 .' = \''. $value2 .'\'';
ec2a28a6 965 if ($field3) {
d4419d55 966 $select .= ' AND '. $field3 .' = \''. $value3 .'\'';
ec2a28a6 967 }
968 }
969
853df85e 970 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
971
d4419d55 972 $rs = $db->Execute('SELECT '. $return .' FROM '. $CFG->prefix . $table .' '. $select);
9c7fee6c 973 if (!$rs) {
2eef791f 974 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 975 notify($db->ErrorMsg() .'<br /><br />SELECT '. $return .' FROM '. $CFG->prefix . $table .' '. $select);
9c7fee6c 976 }
acd2279e 977 if (!empty($CFG->dblogerror)) {
31df0bb8 978 $debug=array_shift(debug_backtrace());
acd2279e 979 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: SELECT $return FROM $CFG->prefix$table $select");
980 }
9c7fee6c 981 return false;
982 }
df28d6c5 983
984 if ( $rs->RecordCount() == 1 ) {
d4419d55 985 return $rs->fields[$return];
df28d6c5 986 } else {
987 return false;
988 }
989}
990
b4bac9b6 991
992/**
fbc21ae8 993 * Get a single field from a database record
994 *
995 * @uses $CFG
996 * @uses $db
997 * @param string $sql The SQL string you wish to be executed.
c6d15803 998 * @return mixed|false Returns the value return from the SQL statment or false if an error occured.
fbc21ae8 999 * @todo Finish documenting this function
1000 */
b4bac9b6 1001function get_field_sql($sql) {
1002
1003 global $db, $CFG;
1004
853df85e 1005 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1006
b4bac9b6 1007 $rs = $db->Execute($sql);
1008 if (!$rs) {
1009 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 1010 notify($db->ErrorMsg() .'<br /><br />'. $sql);
b4bac9b6 1011 }
acd2279e 1012 if (!empty($CFG->dblogerror)) {
31df0bb8 1013 $debug=array_shift(debug_backtrace());
acd2279e 1014 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
1015 }
b4bac9b6 1016 return false;
1017 }
1018
1019 if ( $rs->RecordCount() == 1 ) {
1020 return $rs->fields[0];
1021 } else {
1022 return false;
1023 }
1024}
1025
18a97fd8 1026/**
fbc21ae8 1027 * Set a single field in a database record
1028 *
1029 * @uses $CFG
1030 * @uses $db
1031 * @param string $table The database table to be checked against.
1032 * @param string $field1 The first table field to be checked for a given value. Do not supply a field1 string to leave out a WHERE clause altogether.
1033 * @param string $value1 The value to match if field1 is specified.
1034 * @param string $field2 The second table field to be checked for a given value.
1035 * @param string $value2 The value to match if field2 is specified.
1036 * @param string $field3 The third table field to be checked for a given value.
1037 * @param string $value3 The value to match if field3 is specified.
7290c7fa 1038 * @return object A PHP standard object with the results from the SQL call.
fbc21ae8 1039 * @todo Verify return type
1040 */
d4419d55 1041function set_field($table, $newfield, $newvalue, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
df28d6c5 1042
1043 global $db, $CFG;
1044
853df85e 1045 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1046
d4419d55 1047 $select = 'WHERE '. $field1 .' = \''. $value1 .'\'';
ec2a28a6 1048
1049 if ($field2) {
d4419d55 1050 $select .= ' AND '. $field2 .' = \''. $value2 .'\'';
ec2a28a6 1051 if ($field3) {
d4419d55 1052 $select .= ' AND '. $field3 .' = \''. $value3 .'\'';
ec2a28a6 1053 }
1054 }
1055
d4419d55 1056 return $db->Execute('UPDATE '. $CFG->prefix . $table .' SET '. $newfield .' = \''. $newvalue .'\' '. $select);
df28d6c5 1057}
1058
18a97fd8 1059/**
fbc21ae8 1060 * Delete one or more records from a table
1061 *
1062 * @uses $CFG
1063 * @uses $db
1064 * @param string $table The database table to be checked against.
1065 * @param string $field1 The first table field to be checked for a given value. Do not supply a field1 string to leave out a WHERE clause altogether.
1066 * @param string $value1 The value to match if field1 is specified.
1067 * @param string $field2 The second table field to be checked for a given value.
1068 * @param string $value2 The value to match if field2 is specified.
1069 * @param string $field3 The third table field to be checked for a given value.
1070 * @param string $value3 The value to match if field3 is specified.
7290c7fa 1071 * @return object A PHP standard object with the results from the SQL call.
fbc21ae8 1072 * @todo Verify return type
1073 */
d4419d55 1074function delete_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
df28d6c5 1075
1076 global $db, $CFG;
1077
853df85e 1078 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1079
5c63e0c4 1080 if ($field1) {
d4419d55 1081 $select = 'WHERE '. $field1 .' = \''. $value1 .'\'';
9fa49e22 1082 if ($field2) {
d4419d55 1083 $select .= ' AND '. $field2 .' = \''. $value2 .'\'';
9fa49e22 1084 if ($field3) {
d4419d55 1085 $select .= ' AND '. $field3 .' = \''. $value3 .'\'';
df28d6c5 1086 }
1087 }
5c63e0c4 1088 } else {
d4419d55 1089 $select = '';
df28d6c5 1090 }
1091
d4419d55 1092 return $db->Execute('DELETE FROM '. $CFG->prefix . $table .' '. $select);
df28d6c5 1093}
1094
18a97fd8 1095/**
fbc21ae8 1096 * Delete one or more records from a table
1097 *
1098 * @uses $CFG
1099 * @uses $db
1100 * @param string $table The database table to be checked against.
1101 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
7290c7fa 1102 * @return object A PHP standard object with the results from the SQL call.
fbc21ae8 1103 * @todo Verify return type.
1104 */
d4419d55 1105function delete_records_select($table, $select='') {
30f89d68 1106
1107 global $CFG, $db;
1108
853df85e 1109 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1110
30f89d68 1111 if ($select) {
d4419d55 1112 $select = 'WHERE '.$select;
30f89d68 1113 }
1114
d4419d55 1115 return $db->Execute('DELETE FROM '. $CFG->prefix . $table .' '. $select);
30f89d68 1116}
1117
18a97fd8 1118/**
fbc21ae8 1119 * Insert a record into a table and return the "id" field if required
1120 *
1121 * If the return ID isn't required, then this just reports success as true/false.
1122 * $dataobject is an object containing needed data
1123 *
1124 * @uses $db
1125 * @uses $CFG
1126 * @param string $table The database table to be checked against.
f4cbf7f2 1127 * @param array $dataobject A data object with values for one or more fields in the record
7290c7fa 1128 * @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
f4cbf7f2 1129 * @param string $primarykey The primary key of the table we are inserting into (almost always "id")
fbc21ae8 1130 */
fcf9c450 1131function insert_record($table, $dataobject, $returnid=true, $primarykey='id') {
8f0cd6ef 1132
0892f7bd 1133 global $db, $CFG;
1134
853df85e 1135 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1136
d4469f2a 1137/// Execute a dummy query to get an empty recordset
d4419d55 1138 if (!$rs = $db->Execute('SELECT * FROM '. $CFG->prefix . $table .' WHERE '. $primarykey .' = \'-1\'')) {
d4469f2a 1139 return false;
1140 }
8f0cd6ef 1141
2327ce8e 1142/// In Moodle we always use auto-numbering fields for the primary ID
1143/// so let's unset it now before it causes any trouble
1144
6f2a391f 1145 unset($dataobject->id);
2327ce8e 1146
a9a9bdba 1147 /// Postgres doesn't have the concept of primary key built in
1148 /// and will return the OID which isn't what we want.
1149 /// The efficient and transaction-safe strategy is to
1150 /// move the sequence forward first, and make the insert
1151 /// with an explicit id.
2eab0668 1152 if ( empty($dataobject->{$primarykey})
a9a9bdba 1153 && $CFG->dbtype === 'postgres7'
1154 && $returnid == true ) {
9921028a 1155 if ($nextval = (int)get_field_sql("SELECT NEXTVAL('{$CFG->prefix}{$table}_{$primarykey}_seq')")) {
a9a9bdba 1156 $dataobject->{$primarykey} = $nextval;
1157 }
1158 }
1159
d4469f2a 1160/// Get the correct SQL from adoDB
1161 if (!$insertSQL = $db->GetInsertSQL($rs, (array)$dataobject, true)) {
1162 return false;
1163 }
8f0cd6ef 1164
d4469f2a 1165/// Run the SQL statement
1166 if (!$rs = $db->Execute($insertSQL)) {
2eef791f 1167 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 1168 notify($db->ErrorMsg() .'<br /><br />'.$insertSQL);
9c7fee6c 1169 }
acd2279e 1170 if (!empty($CFG->dblogerror)) {
31df0bb8 1171 $debug=array_shift(debug_backtrace());
acd2279e 1172 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $insertSQL");
1173 }
0892f7bd 1174 return false;
1175 }
8f0cd6ef 1176
d4469f2a 1177/// If a return ID is not needed then just return true now
8f0cd6ef 1178 if (!$returnid) {
0892f7bd 1179 return true;
1180 }
1181
f4cbf7f2 1182/// We already know the record PK if it's been passed explicitly,
1183/// or if we've retrieved it from a sequence (Postgres).
2eab0668 1184 if (!empty($dataobject->{$primarykey})) {
a9a9bdba 1185 return $dataobject->{$primarykey};
1186 }
0892f7bd 1187
a9a9bdba 1188/// This only gets triggered with non-Postgres databases
1189/// however we have some postgres fallback in case we failed
1190/// to find the sequence.
1191 $id = $db->Insert_ID();
1192
1193 if ($CFG->dbtype === 'postgres7') {
1194 // try to get the primary key based on id
1195 if ( ($rs = $db->Execute('SELECT '. $primarykey .' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id))
1196 && ($rs->RecordCount() == 1) ) {
1197 trigger_error("Retrieved $primarykey from oid on table $table because we could not find the sequence.");
1198 return (integer)$rs->fields[0];
1199 }
f4cbf7f2 1200 trigger_error('Failed to retrieve primary key after insert: SELECT '. $primarykey .
1201 ' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id);
a9a9bdba 1202 return false;
0892f7bd 1203 }
a9a9bdba 1204
1205 return (integer)$id;
0892f7bd 1206}
1207
11a052a6 1208/**
1209 * Escape all dangerous characters in a data record
1210 *
1211 * $dataobject is an object containing needed data
1212 * Run over each field exectuting addslashes() function
1213 * to escape SQL unfriendly characters (e.g. quotes)
1214 * Handy when writing back data read from the database
1215 *
1216 * @param $dataobject Object containing the database record
1217 * @return object Same object with neccessary characters escaped
1218 */
1219function addslashes_object( $dataobject ) {
1220 $a = get_object_vars( $dataobject);
1221 foreach ($a as $key=>$value) {
1222 $a[$key] = addslashes( $value );
1223 }
1224 return (object)$a;
1225}
0892f7bd 1226
18a97fd8 1227/**
fbc21ae8 1228 * Update a record in a table
1229 *
1230 * $dataobject is an object containing needed data
1231 * Relies on $dataobject having a variable "id" to
1232 * specify the record to update
1233 *
1234 * @uses $CFG
1235 * @uses $db
1236 * @param string $table The database table to be checked against.
11a052a6 1237 * @param array $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
7290c7fa 1238 * @return bool
fbc21ae8 1239 * @todo Finish documenting this function. Dataobject is actually an associateive array, correct?
1240 */
df28d6c5 1241function update_record($table, $dataobject) {
df28d6c5 1242
1243 global $db, $CFG;
1244
1245 if (! isset($dataobject->id) ) {
1246 return false;
1247 }
1248
1249 // Determine all the fields in the table
d4419d55 1250 if (!$columns = $db->MetaColumns($CFG->prefix . $table)) {
df28d6c5 1251 return false;
1252 }
1253 $data = (array)$dataobject;
1254
853df85e 1255 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1256
df28d6c5 1257 // Pull out data matching these fields
1258 foreach ($columns as $column) {
d4419d55 1259 if ($column->name <> 'id' and isset($data[$column->name]) ) {
df28d6c5 1260 $ddd[$column->name] = $data[$column->name];
1261 }
1262 }
1263
1264 // Construct SQL queries
1265 $numddd = count($ddd);
1266 $count = 0;
d4419d55 1267 $update = '';
df28d6c5 1268
1269 foreach ($ddd as $key => $value) {
1270 $count++;
705a2aa4 1271 $update .= $key .' = \''. $value .'\''; // All incoming data is already quoted
df28d6c5 1272 if ($count < $numddd) {
d4419d55 1273 $update .= ', ';
df28d6c5 1274 }
1275 }
1276
d4419d55 1277 if ($rs = $db->Execute('UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE id = \''. $dataobject->id .'\'')) {
df28d6c5 1278 return true;
1279 } else {
2eef791f 1280 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 1281 notify($db->ErrorMsg() .'<br /><br />UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE id = \''. $dataobject->id .'\'');
9c7fee6c 1282 }
acd2279e 1283 if (!empty($CFG->dblogerror)) {
31df0bb8 1284 $debug=array_shift(debug_backtrace());
acd2279e 1285 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: UPDATE $CFG->prefix$table SET $update WHERE id = '$dataobject->id'");
1286 }
df28d6c5 1287 return false;
1288 }
1289}
1290
1291
df28d6c5 1292
1293
1294/// USER DATABASE ////////////////////////////////////////////////
1295
18a97fd8 1296/**
fbc21ae8 1297 * Does this username and password specify a valid admin user?
1298 *
1299 * @uses $CFG
1300 * @param string $username The name of the user to be tested for admin rights
1301 * @param string $md5password The password supplied by the user in md5 encrypted format.
7290c7fa 1302 * @return bool
fbc21ae8 1303 */
df28d6c5 1304function adminlogin($username, $md5password) {
df28d6c5 1305
1306 global $CFG;
1307
8f0cd6ef 1308 return record_exists_sql("SELECT u.id
1309 FROM {$CFG->prefix}user u,
1310 {$CFG->prefix}user_admins a
1311 WHERE u.id = a.userid
1312 AND u.username = '$username'
df28d6c5 1313 AND u.password = '$md5password'");
1314}
1315
18a97fd8 1316/**
fbc21ae8 1317 * Get the guest user information from the database
1318 *
1319 * @return object(user) An associative array with the details of the guest user account.
1320 * @todo Is object(user) a correct return type? Or is array the proper return type with a note that the contents include all details for a user.
1321 */
9fa49e22 1322function get_guest() {
7c12949d 1323 return get_complete_user_data('username', 'guest');
9fa49e22 1324}
1325
1326
18a97fd8 1327/**
fbc21ae8 1328 * Returns $user object of the main admin user
1329 *
1330 * @uses $CFG
1331 * @return object(admin) An associative array representing the admin user.
1332 * @todo Verify documentation of this function
1333 */
df28d6c5 1334function get_admin () {
df28d6c5 1335
1336 global $CFG;
1337
1338 if ( $admins = get_admins() ) {
1339 foreach ($admins as $admin) {
8f0cd6ef 1340 return $admin; // ie the first one
df28d6c5 1341 }
1342 } else {
1343 return false;
1344 }
1345}
1346
18a97fd8 1347/**
fbc21ae8 1348 * Returns list of all admins
1349 *
1350 * @uses $CFG
7290c7fa 1351 * @return object
fbc21ae8 1352 */
df28d6c5 1353function get_admins() {
df28d6c5 1354
1355 global $CFG;
1356
8f0cd6ef 1357 return get_records_sql("SELECT u.*, a.id as adminid
1358 FROM {$CFG->prefix}user u,
ebc3bd2b 1359 {$CFG->prefix}user_admins a
1360 WHERE a.userid = u.id
427fdf66 1361 ORDER BY a.id ASC");
df28d6c5 1362}
1363
18a97fd8 1364/**
fbc21ae8 1365 * Returns list of all creators
1366 *
1367 * @uses $CFG
7290c7fa 1368 * @return object
fbc21ae8 1369 */
1924074c 1370function get_creators() {
1924074c 1371
1372 global $CFG;
1373
1374 return get_records_sql("SELECT u.*
1375 FROM {$CFG->prefix}user u,
1376 {$CFG->prefix}user_coursecreators a
1377 WHERE a.userid = u.id
1378 ORDER BY u.id ASC");
1379}
df28d6c5 1380
b61efafb 1381function get_courses_in_metacourse($metacourseid) {
1382 global $CFG;
1383
5f37b628 1384 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
5afa0de6 1385 AND mc.child_course = c.id ORDER BY c.shortname";
b61efafb 1386
1387 return get_records_sql($sql);
1388}
1389
1390function get_courses_notin_metacourse($metacourseid,$count=false) {
1391
1392 global $CFG;
1393
b61efafb 1394 if ($count) {
1395 $sql = "SELECT COUNT(c.id)";
c44d5d42 1396 } else {
b61efafb 1397 $sql = "SELECT c.id,c.shortname,c.fullname";
1398 }
178ccd11 1399
ffed6bf3 1400 $alreadycourses = get_courses_in_metacourse($metacourseid);
1401
c44d5d42 1402 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
5afa0de6 1403 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
1404
b61efafb 1405 return get_records_sql($sql);
1406}
1407
1408
18a97fd8 1409/**
fbc21ae8 1410 * Returns $user object of the main teacher for a course
1411 *
1412 * @uses $CFG
1413 * @param int $courseid The course in question.
89dcb99d 1414 * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
fbc21ae8 1415 * @todo Finish documenting this function
1416 */
df28d6c5 1417function get_teacher($courseid) {
df28d6c5 1418
1419 global $CFG;
1420
d4419d55 1421 if ( $teachers = get_course_teachers($courseid, 't.authority ASC')) {
df28d6c5 1422 foreach ($teachers as $teacher) {
1423 if ($teacher->authority) {
1424 return $teacher; // the highest authority teacher
1425 }
1426 }
1427 } else {
1428 return false;
1429 }
1430}
1431
18a97fd8 1432/**
fbc21ae8 1433 * Searches logs to find all enrolments since a certain date
1434 *
1435 * used to print recent activity
1436 *
1437 * @uses $CFG
1438 * @param int $courseid The course in question.
7290c7fa 1439 * @return object|false {@link $USER} records or false if error.
fbc21ae8 1440 * @todo Finish documenting this function
1441 */
0a08581d 1442function get_recent_enrolments($courseid, $timestart) {
0a08581d 1443
1444 global $CFG;
1445
fbf5081c 1446 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
0a08581d 1447 FROM {$CFG->prefix}user u,
1448 {$CFG->prefix}user_students s,
1449 {$CFG->prefix}log l
8f0cd6ef 1450 WHERE l.time > '$timestart'
0a08581d 1451 AND l.course = '$courseid'
8f0cd6ef 1452 AND l.module = 'course'
0a08581d 1453 AND l.action = 'enrol'
1454 AND l.info = u.id
1455 AND u.id = s.userid
64cbb55c 1456 AND s.course = '$courseid'
0a08581d 1457 ORDER BY l.time ASC");
1458}
1459
18a97fd8 1460/**
fbc21ae8 1461 * Returns array of userinfo of all students in this course
1462 * or on this site if courseid is id of site
1463 *
1464 * @uses $CFG
1465 * @uses SITEID
1466 * @param int $courseid The course in question.
1467 * @param string $sort ?
1468 * @param string $dir ?
1469 * @param int $page ?
1470 * @param int $recordsperpage ?
1471 * @param string $firstinitial ?
1472 * @param string $lastinitial ?
1473 * @param ? $group ?
1474 * @param string $search ?
1475 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1476 * @param string $exceptions ?
7290c7fa 1477 * @return object
fbc21ae8 1478 * @todo Finish documenting this function
1479 */
d4419d55 1480function get_course_students($courseid, $sort='s.timeaccess', $dir='', $page=0, $recordsperpage=99999,
1481 $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
df28d6c5 1482
1483 global $CFG;
8f0cd6ef 1484
1485 if ($courseid == SITEID and $CFG->allusersaresitestudents) {
2700d113 1486 // return users with confirmed, undeleted accounts who are not site teachers
1487 // the following is a mess because of different conventions in the different user functions
1488 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
1489 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
1490 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
8f0cd6ef 1491 $fields = str_replace('u.', '', $fields);
2700d113 1492 if ($sort) {
d4419d55 1493 $sort = $sort .' '. $dir;
2700d113 1494 }
1495 // Now we have to make sure site teachers are excluded
1496 if ($teachers = get_records('user_teachers', 'course', SITEID)) {
1497 foreach ($teachers as $teacher) {
d4419d55 1498 $exceptions .= ','. $teacher->userid;
2700d113 1499 }
1500 $exceptions = ltrim($exceptions, ',');
1501 }
8f0cd6ef 1502 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
2700d113 1503 $page, $recordsperpage, $fields ? $fields : '*');
1504 }
df28d6c5 1505
29daf3a0 1506 $limit = sql_paging_limit($page, $recordsperpage);
1507 $LIKE = sql_ilike();
1508 $fullname = sql_fullname('u.firstname','u.lastname');
a328425d 1509
0720313b 1510 $groupmembers = '';
f950af3c 1511
1512 // make sure it works on the site course
d4419d55 1513 $select = 's.course = \''. $courseid .'\' AND ';
222ac91b 1514 if ($courseid == SITEID) {
f950af3c 1515 $select = '';
1516 }
1517
d4419d55 1518 $select .= 's.userid = u.id AND u.deleted = \'0\' ';
73fc8c1a 1519
1284a926 1520 if (!$fields) {
1521 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
1522 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
1523 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
1524 'u.emailstop, u.lang, u.timezone, s.timeaccess as lastaccess';
1525 }
1526
73fc8c1a 1527 if ($search) {
d4419d55 1528 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
73fc8c1a 1529 }
a328425d 1530
1531 if ($firstinitial) {
d4419d55 1532 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
a328425d 1533 }
1534
1535 if ($lastinitial) {
d4419d55 1536 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
4969ad74 1537 }
1538
3d35e6b7 1539 if ($group === 0) { /// Need something here to get all students not in a group
1540 return array();
1541
1542 } else if ($group !== NULL) {
d4419d55 1543 $groupmembers = ', '. $CFG->prefix .'groups_members gm ';
1544 $select .= ' AND u.id = gm.userid AND gm.groupid = \''. $group .'\'';
0720313b 1545 }
8f0cd6ef 1546
900df8b6 1547 if (!empty($exceptions)) {
d4419d55 1548 $select .= ' AND u.id NOT IN ('. $exceptions .')';
900df8b6 1549 }
0720313b 1550
8e4c9ef7 1551 if ($sort) {
d4419d55 1552 $sort = ' ORDER BY '. $sort .' ';
8e4c9ef7 1553 }
1554
2700d113 1555 $students = get_records_sql("SELECT $fields
488acd1b 1556 FROM {$CFG->prefix}user u,
1557 {$CFG->prefix}user_students s
1558 $groupmembers
73fc8c1a 1559 WHERE $select $search $sort $dir $limit");
2700d113 1560
1561 if ($courseid != SITEID) {
1562 return $students;
1563 }
8f0cd6ef 1564
2700d113 1565 // We are here because we need the students for the site.
1566 // These also include teachers on real courses minus those on the site
1567 if ($teachers = get_records('user_teachers', 'course', SITEID)) {
1568 foreach ($teachers as $teacher) {
d4419d55 1569 $exceptions .= ','. $teacher->userid;
2700d113 1570 }
1571 $exceptions = ltrim($exceptions, ',');
d4419d55 1572 $select .= ' AND u.id NOT IN ('. $exceptions .')';
2700d113 1573 }
1574 if (!$teachers = get_records_sql("SELECT $fields
1575 FROM {$CFG->prefix}user u,
1576 {$CFG->prefix}user_teachers s
1577 $groupmembers
1578 WHERE $select $search $sort $dir $limit")) {
1579 return $students;
1580 }
1581 if (!$students) {
1582 return $teachers;
1583 }
1584 return $teachers + $students;
df28d6c5 1585}
1586
fbc21ae8 1587
a328425d 1588/**
fbc21ae8 1589 * Counts the students in a given course (or site), or a subset of them
1590 *
1591 * @param object $course The course in question as a course object.
1592 * @param string $search ?
1593 * @param string $firstinitial ?
1594 * @param string $lastinitial ?
1595 * @param ? $group ?
1596 * @param string $exceptions ?
1597 * @return int
1598 * @todo Finish documenting this function
1599 */
d4419d55 1600function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
a328425d 1601
2700d113 1602 if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
1603 return count($students);
a328425d 1604 }
2700d113 1605 return 0;
a328425d 1606}
1607
1608
18a97fd8 1609/**
fbc21ae8 1610 * Returns list of all teachers in this course
1611 *
1612 * If $courseid matches the site id then this function
1613 * returns a list of all teachers for the site.
1614 *
1615 * @uses $CFG
1616 * @param int $courseid The course in question.
1617 * @param string $sort ?
1618 * @param string $exceptions ?
7290c7fa 1619 * @return object
fbc21ae8 1620 * @todo Finish documenting this function
1621 */
d4419d55 1622function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
df28d6c5 1623
1624 global $CFG;
1625
900df8b6 1626 if (!empty($exceptions)) {
f6f319f8 1627 $exceptions = ' AND u.id NOT IN ('. $exceptions .') ';
1628 }
1629
1630 if (!empty($sort)) {
1631 $sort = ' ORDER by '.$sort;
900df8b6 1632 }
1633
8d241374 1634 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
8f0cd6ef 1635 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
86fb5ed5 1636 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
8f0cd6ef 1637 FROM {$CFG->prefix}user u,
688d06f4 1638 {$CFG->prefix}user_teachers t
8f0cd6ef 1639 WHERE t.course = '$courseid' AND t.userid = u.id
f6f319f8 1640 AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
df28d6c5 1641}
1642
18a97fd8 1643/**
fbc21ae8 1644 * Returns all the users of a course: students and teachers
1645 *
1646 * @param int $courseid The course in question.
1647 * @param string $sort ?
1648 * @param string $exceptions ?
1649 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 1650 * @return object
fbc21ae8 1651 * @todo Finish documenting this function
1652 */
d4419d55 1653function get_course_users($courseid, $sort='timeaccess DESC', $exceptions='', $fields='') {
353d0338 1654
900df8b6 1655 /// Using this method because the single SQL is too inefficient
1656 // Note that this has the effect that teachers and students are
1657 // sorted individually. Returns first all teachers, then all students
0720313b 1658
900df8b6 1659 if (!$teachers = get_course_teachers($courseid, $sort, $exceptions)) {
1660 $teachers = array();
1661 }
65ee9c16 1662 if (!$students = get_course_students($courseid, $sort, '', 0, 99999, '', '', NULL, '', $fields, $exceptions)) {
900df8b6 1663 $students = array();
1664 }
df28d6c5 1665
900df8b6 1666 return $teachers + $students;
0720313b 1667
900df8b6 1668}
0720313b 1669
900df8b6 1670/**
fbc21ae8 1671 * Search through course users
1672 *
1673 * If $coursid specifies the site course then this function searches
1674 * through all undeleted and confirmed users
1675 *
1676 * @uses $CFG
1677 * @uses SITEID
1678 * @param int $courseid The course in question.
1679 * @param int $groupid The group in question.
1680 * @param string $searchtext ?
1681 * @param string $sort ?
1682 * @param string $exceptions ?
7290c7fa 1683 * @return object
fbc21ae8 1684 * @todo Finish documenting this function
1685 */
900df8b6 1686function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
1687 global $CFG;
0720313b 1688
29daf3a0 1689 $LIKE = sql_ilike();
1690 $fullname = sql_fullname('u.firstname', 'u.lastname');
8f0cd6ef 1691
900df8b6 1692 if (!empty($exceptions)) {
d4419d55 1693 $except = ' AND u.id NOT IN ('. $exceptions .') ';
900df8b6 1694 } else {
1695 $except = '';
1696 }
2700d113 1697
900df8b6 1698 if (!empty($sort)) {
d4419d55 1699 $order = ' ORDER BY '. $sort;
900df8b6 1700 } else {
1701 $order = '';
1702 }
8f0cd6ef 1703
d4419d55 1704 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
2700d113 1705
222ac91b 1706 if (!$courseid or $courseid == SITEID) {
2700d113 1707 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
1708 FROM {$CFG->prefix}user u
1709 WHERE $select
900df8b6 1710 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
2700d113 1711 $except $order");
8f0cd6ef 1712 } else {
2700d113 1713
900df8b6 1714 if ($groupid) {
1715 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1716 FROM {$CFG->prefix}user u,
900df8b6 1717 {$CFG->prefix}groups_members g
2700d113 1718 WHERE $select AND g.groupid = '$groupid' AND g.userid = u.id
900df8b6 1719 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1720 $except $order");
1721 } else {
1722 if (!$teachers = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1723 FROM {$CFG->prefix}user u,
900df8b6 1724 {$CFG->prefix}user_teachers s
2700d113 1725 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
900df8b6 1726 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1727 $except $order")) {
1728 $teachers = array();
1729 }
1730 if (!$students = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1731 FROM {$CFG->prefix}user u,
900df8b6 1732 {$CFG->prefix}user_students s
2700d113 1733 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
900df8b6 1734 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1735 $except $order")) {
1736 $students = array();
1737 }
1738 return $teachers + $students;
1739 }
1740 }
df28d6c5 1741}
1742
2700d113 1743
18a97fd8 1744/**
fbc21ae8 1745 * Returns a list of all site users
1746 * Obsolete, just calls get_course_users(SITEID)
1747 *
1748 * @uses SITEID
c6d15803 1749 * @deprecated Use {@link get_course_users()} instead.
fbc21ae8 1750 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 1751 * @return object|false {@link $USER} records or false if error.
fbc21ae8 1752 * @todo Finish documenting this function. The return type need to be better defined.
1753 */
d4419d55 1754function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='') {
2d0b30a0 1755
65ee9c16 1756 return get_course_users(SITEID, $sort, $exceptions, $fields);
2d0b30a0 1757}
1758
9fa49e22 1759
18a97fd8 1760/**
fbc21ae8 1761 * Returns a subset of users
1762 *
1763 * @uses $CFG
7290c7fa 1764 * @param bool $get If false then only a count of the records is returned
fbc21ae8 1765 * @param string $search A simple string to search for
7290c7fa 1766 * @param bool $confirmed A switch to allow/disallow unconfirmed users
fbc21ae8 1767 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
1768 * @param string $sort A SQL snippet for the sorting criteria to use
1769 * @param string $firstinitial ?
1770 * @param string $lastinitial ?
1771 * @param string $page ?
1772 * @param string $recordsperpage ?
1773 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 1774 * @return object|false|int {@link $USER} records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.
fbc21ae8 1775 * @todo Finish documenting this function. The return type needs to be better defined.
1776 */
d4419d55 1777function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
1778 $firstinitial='', $lastinitial='', $page=0, $recordsperpage=99999, $fields='*') {
18a97fd8 1779
1780 global $CFG;
1781
29daf3a0 1782 $limit = sql_paging_limit($page, $recordsperpage);
1783 $LIKE = sql_ilike();
1784 $fullname = sql_fullname();
e384fb7b 1785
d4419d55 1786 $select = 'username <> \'guest\' AND deleted = 0';
488acd1b 1787
0044147e 1788 if (!empty($search)){
1789 $search = trim($search);
488acd1b 1790 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
e384fb7b 1791 }
1792
5a741655 1793 if ($confirmed) {
d4419d55 1794 $select .= ' AND confirmed = \'1\' ';
5a741655 1795 }
1796
1797 if ($exceptions) {
d4419d55 1798 $select .= ' AND id NOT IN ('. $exceptions .') ';
5a741655 1799 }
1800
488acd1b 1801 if ($firstinitial) {
d4419d55 1802 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
8f0cd6ef 1803 }
488acd1b 1804 if ($lastinitial) {
d4419d55 1805 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
8f0cd6ef 1806 }
488acd1b 1807
5a741655 1808 if ($sort and $get) {
d4419d55 1809 $sort = ' ORDER BY '. $sort .' ';
5a741655 1810 } else {
d4419d55 1811 $sort = '';
5a741655 1812 }
1813
1814 if ($get) {
d4419d55 1815 return get_records_select('user', $select .' '. $sort .' '. $limit, '', $fields);
5a741655 1816 } else {
d4419d55 1817 return count_records_select('user', $select .' '. $sort .' '. $limit);
5a741655 1818 }
9fa49e22 1819}
1820
5a741655 1821
18a97fd8 1822/**
fbc21ae8 1823 * shortdesc (optional)
1824 *
1825 * longdesc
1826 *
1827 * @uses $CFG
1828 * @param string $sort ?
1829 * @param string $dir ?
1830 * @param int $categoryid ?
1831 * @param int $categoryid ?
1832 * @param string $search ?
1833 * @param string $firstinitial ?
1834 * @param string $lastinitial ?
7290c7fa 1835 * @returnobject {@link $USER} records
fbc21ae8 1836 * @todo Finish documenting this function
1837 */
1838
d4419d55 1839function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=99999,
7cf1c7bd 1840 $search='', $firstinitial='', $lastinitial='') {
488acd1b 1841
9fa49e22 1842 global $CFG;
31fefa63 1843
29daf3a0 1844 $limit = sql_paging_limit($page, $recordsperpage);
1845 $LIKE = sql_ilike();
1846 $fullname = sql_fullname();
c2a96d6b 1847
488acd1b 1848 $select = 'deleted <> 1';
1849
0044147e 1850 if (!empty($search)) {
1851 $search = trim($search);
488acd1b 1852 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
1853 }
1854
1855 if ($firstinitial) {
d4419d55 1856 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
488acd1b 1857 }
1858
1859 if ($lastinitial) {
d4419d55 1860 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
c750592a 1861 }
1862
488acd1b 1863 if ($sort) {
d4419d55 1864 $sort = ' ORDER BY '. $sort .' '. $dir;
488acd1b 1865 }
1866
1867/// warning: will return UNCONFIRMED USERS
ea5d48ee 1868 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed
8f0cd6ef 1869 FROM {$CFG->prefix}user
488acd1b 1870 WHERE $select $sort $limit ");
9fa49e22 1871
1872}
1873
488acd1b 1874
18a97fd8 1875/**
7290c7fa 1876 * Full list of users that have confirmed their accounts.
fbc21ae8 1877 *
1878 * @uses $CFG
7290c7fa 1879 * @return object
fbc21ae8 1880 */
9fa49e22 1881function get_users_confirmed() {
1882 global $CFG;
8f0cd6ef 1883 return get_records_sql("SELECT *
1884 FROM {$CFG->prefix}user
1885 WHERE confirmed = 1
9fa49e22 1886 AND deleted = 0
8f0cd6ef 1887 AND username <> 'guest'
9fa49e22 1888 AND username <> 'changeme'");
1889}
1890
1891
18a97fd8 1892/**
7290c7fa 1893 * Full list of users that have not yet confirmed their accounts.
fbc21ae8 1894 *
1895 * @uses $CFG
1896 * @param string $cutofftime ?
7290c7fa 1897 * @return object {@link $USER} records
fbc21ae8 1898 * @todo Finish documenting this function
1899 */
99988d1a 1900function get_users_unconfirmed($cutofftime=2000000000) {
9fa49e22 1901 global $CFG;
8f0cd6ef 1902 return get_records_sql("SELECT *
1903 FROM {$CFG->prefix}user
9fa49e22 1904 WHERE confirmed = 0
8f0cd6ef 1905 AND firstaccess > 0
9fa49e22 1906 AND firstaccess < '$cutofftime'");
1907}
1908
1909
18a97fd8 1910/**
fbc21ae8 1911 * shortdesc (optional)
1912 *
1913 * longdesc
1914 *
1915 * @uses $CFG
1916 * @param string $cutofftime ?
7290c7fa 1917 * @return object {@link $USER} records
fbc21ae8 1918 * @todo Finish documenting this function
1919 */
9fa49e22 1920function get_users_longtimenosee($cutofftime) {
1921 global $CFG;
937ae59c 1922 return get_records_sql("SELECT DISTINCT *
1923 FROM {$CFG->prefix}user_students
8f0cd6ef 1924 WHERE timeaccess > '0'
937ae59c 1925 AND timeaccess < '$cutofftime' ");
9fa49e22 1926}
1927
f374fb10 1928/**
fbc21ae8 1929 * Returns an array of group objects that the user is a member of
1930 * in the given course. If userid isn't specified, then return a
1931 * list of all groups in the course.
1932 *
1933 * @uses $CFG
89dcb99d 1934 * @param int $courseid The id of the course in question.
fbc21ae8 1935 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
7290c7fa 1936 * @return object
fbc21ae8 1937 */
f374fb10 1938function get_groups($courseid, $userid=0) {
1939 global $CFG;
1940
1941 if ($userid) {
d4419d55 1942 $dbselect = ', '. $CFG->prefix .'groups_members m';
1943 $userselect = 'AND m.groupid = g.id AND m.userid = \''. $userid .'\'';
2d439c9d 1944 } else {
1945 $dbselect = '';
1946 $userselect = '';
f374fb10 1947 }
1948
1949 return get_records_sql("SELECT DISTINCT g.*
2d439c9d 1950 FROM {$CFG->prefix}groups g $dbselect
f374fb10 1951 WHERE g.courseid = '$courseid' $userselect ");
1952}
1953
1954
1955/**
fbc21ae8 1956 * Returns an array of user objects
1957 *
1958 * @uses $CFG
1959 * @param int $groupid The group in question.
1960 * @param string $sort ?
1961 * @param string $exceptions ?
7290c7fa 1962 * @return object
fbc21ae8 1963 * @todo Finish documenting this function
1964 */
49668367 1965function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='', $fields='u.*') {
f374fb10 1966 global $CFG;
900df8b6 1967 if (!empty($exceptions)) {
d4419d55 1968 $except = ' AND u.id NOT IN ('. $exceptions .') ';
900df8b6 1969 } else {
1970 $except = '';
1971 }
c1147b7e 1972 // in postgres, you can't have things in sort that aren't in the select, so...
1973 $extrafield = str_replace('ASC','',$sort);
d5efb299 1974 $extrafield = str_replace('DESC','',$extrafield);
c1147b7e 1975 $extrafield = trim($extrafield);
1976 if (!empty($extrafield)) {
1977 $extrafield = ','.$extrafield;
1978 }
1979 return get_records_sql("SELECT DISTINCT $fields $extrafield
f374fb10 1980 FROM {$CFG->prefix}user u,
8f0cd6ef 1981 {$CFG->prefix}groups_members m
f374fb10 1982 WHERE m.groupid = '$groupid'
900df8b6 1983 AND m.userid = u.id $except
2c4263c4 1984 ORDER BY $sort");
f374fb10 1985}
1986
1987/**
fbc21ae8 1988 * An efficient way of finding all the users who aren't in groups yet
1989 *
1990 * Currently unimplemented.
1991 * @uses $CFG
1992 * @param int $courseid The course in question.
7290c7fa 1993 * @return object
fbc21ae8 1994 */
f374fb10 1995function get_users_not_in_group($courseid) {
1996 global $CFG;
1997
1998 return array(); /// XXX TO BE DONE
1999}
2000
60b025d1 2001/**
fbc21ae8 2002 * Returns an array of user objects
2003 *
2004 * @uses $CFG
2005 * @param int $groupid The group in question.
9b10b65b 2006 * @param string $sort How to sort the results
7290c7fa 2007 * @return object
fbc21ae8 2008 */
d4419d55 2009function get_group_students($groupid, $sort='u.lastaccess DESC') {
60b025d1 2010 global $CFG;
2011 return get_records_sql("SELECT DISTINCT u.*
2012 FROM {$CFG->prefix}user u,
2013 {$CFG->prefix}groups_members m,
2014 {$CFG->prefix}groups g,
2015 {$CFG->prefix}user_students s
2016 WHERE m.groupid = '$groupid'
8f0cd6ef 2017 AND m.userid = u.id
2018 AND m.groupid = g.id
60b025d1 2019 AND g.courseid = s.course
2020 AND s.userid = u.id
2021 ORDER BY $sort");
2022}
2023
9b10b65b 2024
2025/**
2026 * Returns list of all the teachers who can access a group
2027 *
2028 * @uses $CFG
2029 * @param int $courseid The course in question.
2030 * @param int $groupid The group in question.
7290c7fa 2031 * @return object
9b10b65b 2032 */
2033function get_group_teachers($courseid, $groupid) {
2034/// Returns a list of all the teachers who can access a group
2035 if ($teachers = get_course_teachers($courseid)) {
2036 foreach ($teachers as $key => $teacher) {
2037 if ($teacher->editall) { // These can access anything
2038 continue;
2039 }
2040 if (($teacher->authority > 0) and ismember($groupid, $teacher->id)) { // Specific group teachers
2041 continue;
2042 }
9a4d45ae 2043 unset($teachers[$key]);
9b10b65b 2044 }
2045 }
2046 return $teachers;
2047}
2048
2049
f374fb10 2050/**
fbc21ae8 2051 * Returns the user's group in a particular course
2052 *
2053 * @uses $CFG
2054 * @param int $courseid The course in question.
2055 * @param int $userid The id of the user as found in the 'user' table.
7290c7fa 2056 * @return object
fbc21ae8 2057 * @todo Finish documenting this function
2058 */
f374fb10 2059function user_group($courseid, $userid) {
2060 global $CFG;
2061
2062 return get_record_sql("SELECT g.*
0da33e07 2063 FROM {$CFG->prefix}groups g,
2064 {$CFG->prefix}groups_members m
f374fb10 2065 WHERE g.courseid = '$courseid'
2066 AND g.id = m.groupid
2067 AND m.userid = '$userid'");
2068}
2069
2070
9fa49e22 2071
02ebf404 2072
2073/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
2074
2075
18a97fd8 2076/**
fbc21ae8 2077 * Returns $course object of the top-level site.
2078 *
89dcb99d 2079 * @return course A {@link $COURSE} object for the site
2080 * @todo Finish documenting this function.
fbc21ae8 2081 */
c44d5d42 2082function get_site() {
2083
2084 global $SITE;
2085
2086 if (!empty($SITE->id)) { // We already have a global to use, so return that
2087 return $SITE;
2088 }
02ebf404 2089
c44d5d42 2090 if ($course = get_record('course', 'category', 0)) {
02ebf404 2091 return $course;
2092 } else {
2093 return false;
2094 }
2095}
2096
18a97fd8 2097/**
6315b1c8 2098* Returns list of courses, for whole site, or category
2099*
2100* Returns list of courses, for whole site, or category
2101*
2102* @param type description
2103*
2104* Important: Using c.* for fields is extremely expensive because
2105* we are using distinct. You almost _NEVER_ need all the fields
2106* in such a large SELECT
2107*/
2108function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 2109
8ef9cb56 2110 global $USER, $CFG;
6315b1c8 2111
2112 $categoryselect = "";
2113 if ($categoryid != "all" && is_numeric($categoryid)) {
2114 $categoryselect = "c.category = '$categoryid'";
2115 }
2116
2117 $teachertable = "";
2118 $visiblecourses = "";
2119 $sqland = "";
2120 if (!empty($categoryselect)) {
2121 $sqland = "AND ";
2122 }
2123 if (!empty($USER->id)) { // May need to check they are a teacher
2124 if (!iscreator()) {
2125 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
2126 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
2127 }
2128 } else {
2129 $visiblecourses = "$sqland c.visible > 0";
8ef9cb56 2130 }
2131
6315b1c8 2132 if ($categoryselect or $visiblecourses) {
2133 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
14f32609 2134 } else {
6315b1c8 2135 $selectsql = "{$CFG->prefix}course c $teachertable";
14f32609 2136 }
2137
5b66416f 2138 $extrafield = str_replace('ASC','',$sort);
2139 $extrafield = str_replace('DESC','',$extrafield);
2140 $extrafield = trim($extrafield);
2141 if (!empty($extrafield)) {
2142 $extrafield = ','.$extrafield;
2143 }
2144 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
8130b77b 2145}
2146
8130b77b 2147
6315b1c8 2148/**
2149* Returns list of courses, for whole site, or category
2150*
2151* Similar to get_courses, but allows paging
2152*
2153* @param type description
2154*
2155* Important: Using c.* for fields is extremely expensive because
2156* we are using distinct. You almost _NEVER_ need all the fields
2157* in such a large SELECT
2158*/
2159function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
2160 &$totalcount, $limitfrom="", $limitnum="") {
c7fe5c6f 2161
8130b77b 2162 global $USER, $CFG;
2163
6315b1c8 2164 $categoryselect = "";
b565bbdf 2165 if ($categoryid != "all" && is_numeric($categoryid)) {
6315b1c8 2166 $categoryselect = "c.category = '$categoryid'";
8130b77b 2167 }
2168
6315b1c8 2169 $teachertable = "";
2170 $visiblecourses = "";
2171 $sqland = "";
2172 if (!empty($categoryselect)) {
2173 $sqland = "AND ";
c7fe5c6f 2174 }
2d2da684 2175 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
6315b1c8 2176 if (!iscreator()) {
2177 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
2178 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
2179 }
8130b77b 2180 } else {
6315b1c8 2181 $visiblecourses = "$sqland c.visible > 0";
8130b77b 2182 }
2183
6315b1c8 2184 if ($limitfrom !== "") {
29daf3a0 2185 $limit = sql_paging_limit($limitfrom, $limitnum);
6315b1c8 2186 } else {
2187 $limit = "";
02ebf404 2188 }
8ef9cb56 2189
6315b1c8 2190 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
8ef9cb56 2191
6315b1c8 2192 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
8ef9cb56 2193
6315b1c8 2194 return get_records_sql("SELECT DISTINCT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
02ebf404 2195}
2196
2197
18a97fd8 2198/**
7290c7fa 2199 * List of courses that a user is a member of.
fbc21ae8 2200 *
2201 * @uses $CFG
7290c7fa 2202 * @param int $userid The user of interest
fbc21ae8 2203 * @param string $sort ?
7290c7fa 2204 * @return object {@link $COURSE} records
fbc21ae8 2205 */
d4419d55 2206function get_my_courses($userid, $sort='visible DESC,sortorder ASC') {
2f3499b7 2207
02ebf404 2208 global $CFG;
2209
2f3499b7 2210 $course = array();
2211
d4419d55 2212 if ($students = get_records('user_students', 'userid', $userid, '', 'id, course')) {
2f3499b7 2213 foreach ($students as $student) {
2214 $course[$student->course] = $student->course;
2215 }
2216 }
d4419d55 2217 if ($teachers = get_records('user_teachers', 'userid', $userid, '', 'id, course')) {
2f3499b7 2218 foreach ($teachers as $teacher) {
2219 $course[$teacher->course] = $teacher->course;
2220 }
2221 }
2222 if (empty($course)) {
2223 return $course;
2224 }
2225
2226 $courseids = implode(',', $course);
2227
d4419d55 2228 return get_records_list('course', 'id', $courseids, $sort);
2f3499b7 2229
2230// The following is correct but VERY slow with large datasets
2231//
8f0cd6ef 2232// return get_records_sql("SELECT c.*
2233// FROM {$CFG->prefix}course c,
2234// {$CFG->prefix}user_students s,
2235// {$CFG->prefix}user_teachers t
2f3499b7 2236// WHERE (s.userid = '$userid' AND s.course = c.id)
2237// OR (t.userid = '$userid' AND t.course = c.id)
8f0cd6ef 2238// GROUP BY c.id
2f3499b7 2239// ORDER BY $sort");
02ebf404 2240}
2241
2242
18a97fd8 2243/**
7290c7fa 2244 * A list of courses that match a search
fbc21ae8 2245 *
2246 * @uses $CFG
2247 * @param array $searchterms ?
2248 * @param string $sort ?
2249 * @param int $page ?
2250 * @param int $recordsperpage ?
2251 * @param int $totalcount Passed in by reference. ?
7290c7fa 2252 * @return object {@link $COURSE} records
fbc21ae8 2253 * @todo Finish documenting this function
2254 */
d4419d55 2255function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
02ebf404 2256
2257 global $CFG;
2258
29daf3a0 2259 $limit = sql_paging_limit($page, $recordsperpage);
02ebf404 2260
18a97fd8 2261 //to allow case-insensitive search for postgesql
d4419d55 2262 if ($CFG->dbtype == 'postgres7') {
2263 $LIKE = 'ILIKE';
2264 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
2265 $REGEXP = '~*';
2266 $NOTREGEXP = '!~*';
02ebf404 2267 } else {
d4419d55 2268 $LIKE = 'LIKE';
2269 $NOTLIKE = 'NOT LIKE';
2270 $REGEXP = 'REGEXP';
2271 $NOTREGEXP = 'NOT REGEXP';
02ebf404 2272 }
2273
d4419d55 2274 $fullnamesearch = '';
2275 $summarysearch = '';
02ebf404 2276
02ebf404 2277 foreach ($searchterms as $searchterm) {
2278 if ($fullnamesearch) {
d4419d55 2279 $fullnamesearch .= ' AND ';
02ebf404 2280 }
02ebf404 2281 if ($summarysearch) {
d4419d55 2282 $summarysearch .= ' AND ';
02ebf404 2283 }
a8b56716 2284
d4419d55 2285 if (substr($searchterm,0,1) == '+') {
a8b56716 2286 $searchterm = substr($searchterm,1);
2287 $summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2288 $fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2289 } else if (substr($searchterm,0,1) == "-") {
2290 $searchterm = substr($searchterm,1);
2291 $summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2292 $fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2293 } else {
d4419d55 2294 $summarysearch .= ' summary '. $LIKE .'\'%'. $searchterm .'%\' ';
2295 $fullnamesearch .= ' fullname '. $LIKE .'\'%'. $searchterm .'%\' ';
a8b56716 2296 }
2297
02ebf404 2298 }
2299
d4419d55 2300 $selectsql = $CFG->prefix .'course WHERE ('. $fullnamesearch .' OR '. $summarysearch .') AND category > \'0\'';
a8b56716 2301
d4419d55 2302 $totalcount = count_records_sql('SELECT COUNT(*) FROM '. $selectsql);
02ebf404 2303
d4419d55 2304 $courses = get_records_sql('SELECT * FROM '. $selectsql .' ORDER BY '. $sort .' '. $limit);
02ebf404 2305
2306 if ($courses) { /// Remove unavailable courses from the list
2307 foreach ($courses as $key => $course) {
2308 if (!$course->visible) {
2309 if (!isteacher($course->id)) {
2310 unset($courses[$key]);
a8b56716 2311 $totalcount--;
02ebf404 2312 }
2313 }
2314 }
2315 }
2316
2317 return $courses;
2318}
2319
2320
18a97fd8 2321/**
fbc21ae8 2322 * Returns a sorted list of categories
2323 *
2324 * @param string $parent ?
2325 * @param string $sort ?
2326 * @return ?
2327 * @todo Finish documenting this function
2328 */
d4419d55 2329function get_categories($parent='none', $sort='sortorder ASC') {
02ebf404 2330
814748c9 2331 if ($parent === 'none') {
d4419d55 2332 $categories = get_records('course_categories', '', '', $sort);
02ebf404 2333 } else {
d4419d55 2334 $categories = get_records('course_categories', 'parent', $parent, $sort);
02ebf404 2335 }
2336 if ($categories) { /// Remove unavailable categories from the list
3af6e1db 2337 $creator = iscreator();
02ebf404 2338 foreach ($categories as $key => $category) {
2339 if (!$category->visible) {
3af6e1db 2340 if (!$creator) {
02ebf404 2341 unset($categories[$key]);
2342 }
2343 }
2344 }
2345 }
2346 return $categories;
2347}
2348
2349
18a97fd8 2350/**
ba87a4da 2351* This recursive function makes sure that the courseorder is consecutive
2352*
2353* @param type description
2354*
2355* $n is the starting point, offered only for compatilibity -- will be ignored!
2356* $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
2357* safely from 1.4 to 1.5
2358*/
f41ef63e 2359function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
2360
ba87a4da 2361 global $CFG;
8f0cd6ef 2362
02ebf404 2363 $count = 0;
ba87a4da 2364
f41ef63e 2365 $catgap = 1000; // "standard" category gap
2366 $tolerance = 200; // how "close" categories can get
2367
2368 if ($categoryid > 0){
2369 // update depth and path
2370 $cat = get_record('course_categories', 'id', $categoryid);
2371 if ($cat->parent == 0) {
2372 $depth = 0;
2373 $path = '';
2374 } else if ($depth == 0 ) { // doesn't make sense; get from DB
2375 // this is only called if the $depth parameter looks dodgy
2376 $parent = get_record('course_categories', 'id', $cat->parent);
2377 $path = $parent->path;
2378 $depth = $parent->depth;
2379 }
2380 $path = $path . '/' . $categoryid;
2381 $depth = $depth + 1;
ba87a4da 2382
f41ef63e 2383 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
2384 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
2385 }
39f65595 2386
2387 // get some basic info about courses in the category
ba87a4da 2388 $info = get_record_sql('SELECT MIN(sortorder) AS min,
2389 MAX(sortorder) AS max,
f41ef63e 2390 COUNT(sortorder) AS count
ba87a4da 2391 FROM ' . $CFG->prefix . 'course
2392 WHERE category=' . $categoryid);
2393 if (is_object($info)) { // no courses?
2394 $max = $info->max;
2395 $count = $info->count;
2396 $min = $info->min;
2397 unset($info);
2398 }
2399
814748c9 2400 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
2401 $n = $min;
2402 }
2403
39f65595 2404 // $hasgap flag indicates whether there's a gap in the sequence
2405 $hasgap = false;
2406 if ($max-$min+1 != $count) {
2407 $hasgap = true;
2408 }
2409
2410 // $mustshift indicates whether the sequence must be shifted to
2411 // meet its range
2412 $mustshift = false;
2413 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
2414 $mustshift = true;
2415 }
2416
ba87a4da 2417 // actually sort only if there are courses,
2418 // and we meet one ofthe triggers:
2419 // - safe flag
2420 // - they are not in a continuos block
2421 // - they are too close to the 'bottom'
39f65595 2422 if ($count && ( $safe || $hasgap || $mustshift ) ) {
2423 // special, optimized case where all we need is to shift
2424 if ( $mustshift && !$safe && !$hasgap) {
2425 $shift = $n + $catgap - $min;
2426 // UPDATE course SET sortorder=sortorder+$shift
2427 execute_sql("UPDATE {$CFG->prefix}course
2428 SET sortorder=sortorder+$shift
2429 WHERE category=$categoryid", 0);
2430 $n = $n + $catgap + $count;
2431
2432 } else { // do it slowly
2433 $n = $n + $catgap;
2434 // if the new sequence overlaps the current sequence, lack of transactions
2435 // will stop us -- shift things aside for a moment...
94afadb3 2436 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbtype==='mysql')) {
d6a49dab 2437 $shift = $max + $n + 1000;
39f65595 2438 execute_sql("UPDATE {$CFG->prefix}course
2439 SET sortorder=sortorder+$shift
2440 WHERE category=$categoryid", 0);
ba87a4da 2441 }
2442
39f65595 2443 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
2444 begin_sql();
ba87a4da 2445 foreach ($courses as $course) {
2446 if ($course->sortorder != $n ) { // save db traffic
2447 set_field('course', 'sortorder', $n, 'id', $course->id);
2448 }
2449 $n++;
2450 }
2451 commit_sql();
2452 }
02ebf404 2453 }
d4419d55 2454 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
8f0cd6ef 2455
814748c9 2456 // $n could need updating
2457 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
2458 if ($max > $n) {
2459 $n = $max;
2460 }
758b9a4d 2461
6bc502cc 2462 if ($categories = get_categories($categoryid)) {
2463 foreach ($categories as $category) {
f41ef63e 2464 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
6bc502cc 2465 }
2466 }
8f0cd6ef 2467
39f65595 2468 return $n+1;
02ebf404 2469}
2470
fbc21ae8 2471
18a97fd8 2472/**
fbc21ae8 2473 * This function creates a default separated/connected scale
2474 *
2475 * This function creates a default separated/connected scale
2476 * so there's something in the database. The locations of
2477 * strings and files is a bit odd, but this is because we
2478 * need to maintain backward compatibility with many different
2479 * existing language translations and older sites.
2480 *
2481 * @uses $CFG
2482 */
02ebf404 2483function make_default_scale() {
02ebf404 2484
2485 global $CFG;
2486
2487 $defaultscale = NULL;
2488 $defaultscale->courseid = 0;
2489 $defaultscale->userid = 0;
d4419d55 2490 $defaultscale->name = get_string('separateandconnected');
2491 $defaultscale->scale = get_string('postrating1', 'forum').','.
2492 get_string('postrating2', 'forum').','.
2493 get_string('postrating3', 'forum');
02ebf404 2494 $defaultscale->timemodified = time();
2495
8f0cd6ef 2496 /// Read in the big description from the file. Note this is not
02ebf404 2497 /// HTML (despite the file extension) but Moodle format text.
d4419d55 2498 $parentlang = get_string('parentlang');
2499 if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
2500 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
2501 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
2502 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
2503 } else if (is_readable($CFG->dirroot .'/lang/en/help/forum/ratings.html')) {
2504 $file = file($CFG->dirroot .'/lang/en/help/forum/ratings.html');
02ebf404 2505 } else {
d4419d55 2506 $file = '';
02ebf404 2507 }
2508
d4419d55 2509 $defaultscale->description = addslashes(implode('', $file));
02ebf404 2510
d4419d55 2511 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
2512 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
02ebf404 2513 }
2514}
2515
fbc21ae8 2516
18a97fd8 2517/**
fbc21ae8 2518 * Returns a menu of all available scales from the site as well as the given course
2519 *
2520 * @uses $CFG
2521 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 2522 * @return object
fbc21ae8 2523 */
02ebf404 2524function get_scales_menu($courseid=0) {
02ebf404 2525
2526 global $CFG;
8f0cd6ef 2527
2528 $sql = "SELECT id, name FROM {$CFG->prefix}scale
2529 WHERE courseid = '0' or courseid = '$courseid'
02ebf404 2530 ORDER BY courseid ASC, name ASC";
2531
d4419d55 2532 if ($scales = get_records_sql_menu($sql)) {
02ebf404 2533 return $scales;
2534 }
2535
2536 make_default_scale();
2537
d4419d55 2538 return get_records_sql_menu($sql);
02ebf404 2539}
2540
5baa0ad6 2541
2542
2543/**
2544 * Given a set of timezone records, put them in the database, replacing what is there
2545 *
2546 * @uses $CFG
2547 * @param array $timezones An array of timezone records
2548 */
2549function update_timezone_records($timezones) {
2550/// Given a set of timezone records, put them in the database
2551
2552 global $CFG;
2553
2554/// Clear out all the old stuff
2555 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
2556
2557/// Insert all the new stuff
2558 foreach ($timezones as $timezone) {
2559 insert_record('timezone', $timezone);
2560 }
2561}
2562
2563
df28d6c5 2564/// MODULE FUNCTIONS /////////////////////////////////////////////////
2565
18a97fd8 2566/**
fbc21ae8 2567 * Just gets a raw list of all modules in a course
2568 *
2569 * @uses $CFG
2570 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 2571 * @return object
fbc21ae8 2572 * @todo Finish documenting this function
2573 */
9fa49e22 2574function get_course_mods($courseid) {
9fa49e22 2575 global $CFG;
2576
7acaa63d 2577 return get_records_sql("SELECT cm.*, m.name as modname
8f0cd6ef 2578 FROM {$CFG->prefix}modules m,
7acaa63d 2579 {$CFG->prefix}course_modules cm
8f0cd6ef 2580 WHERE cm.course = '$courseid'
9fa49e22 2581 AND cm.module = m.id ");
2582}
2583
fbc21ae8 2584
18a97fd8 2585/**
fbc21ae8 2586 * Given an instance of a module, finds the coursemodule description
2587 *
2588 * @uses $CFG
2589 * @param string $modulename ?
2590 * @param string $instance ?
2591 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 2592 * @return object
fbc21ae8 2593 * @todo Finish documenting this function
2594 */
b63c0ee5 2595function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
df28d6c5 2596
2597 global $CFG;
b63c0ee5 2598
2599 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
df28d6c5 2600
2601 return get_record_sql("SELECT cm.*, m.name
8f0cd6ef 2602 FROM {$CFG->prefix}course_modules cm,
2603 {$CFG->prefix}modules md,
2604 {$CFG->prefix}$modulename m
b63c0ee5 2605 WHERE $courseselect
8f0cd6ef 2606 cm.instance = m.id AND
2607 md.name = '$modulename' AND
df28d6c5 2608 md.id = cm.module AND
2609 m.id = '$instance'");
2610
2611}
2612
fbc21ae8 2613
18a97fd8 2614/**
fbc21ae8 2615 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
2616 *
2617 * Returns an array of all the active instances of a particular
2618 * module in a given course, sorted in the order they are defined
2619 * in the course. Returns false on any errors.
2620 *
2621 * @uses $CFG
2622 * @param string $modulename The name of the module to get instances for
2623 * @param object(course) $course This depends on an accurate $course->modinfo
2624 * @todo Finish documenting this function. Is a course object to be documented as object(course) or array(course) since a coures object is really just an associative array, not a php object?
2625 */
cccb016a 2626function get_all_instances_in_course($modulename, $course) {
df28d6c5 2627
2628 global $CFG;
2629
cccb016a 2630 if (!$modinfo = unserialize($course->modinfo)) {
2631 return array();
1acfbce5 2632 }
2633
404afe6b 2634 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode
8f0cd6ef 2635 FROM {$CFG->prefix}course_modules cm,
2636 {$CFG->prefix}course_sections cw,
2637 {$CFG->prefix}modules md,
2638 {$CFG->prefix}$modulename m
2639 WHERE cm.course = '$course->id' AND
2640 cm.instance = m.id AND
8f0cd6ef 2641 cm.section = cw.id AND
2642 md.name = '$modulename' AND
cccb016a 2643 md.id = cm.module")) {
2644 return array();
2645 }
2646
2647 // Hide non-visible instances from students
2648 if (isteacher($course->id)) {
2649 $invisible = -1;
2650 } else {
2651 $invisible = 0;
2652 }
2653
2654 foreach ($modinfo as $mod) {
2655 if ($mod->mod == $modulename and $mod->visible > $invisible) {
7f12f9cd 2656 $instance = $rawmods[$mod->cm];
2657 if (!empty($mod->extra)) {
2658 $instance->extra = $mod->extra;
2659 }
2660 $outputarray[] = $instance;
cccb016a 2661 }
2662 }
2663
2664 return $outputarray;
df28d6c5 2665
2666}
2667
9fa49e22 2668
18a97fd8 2669/**
fbc21ae8 2670 * Determine whether a module instance is visible within a course
2671 *
2672 * Given a valid module object with info about the id and course,
2673 * and the module's type (eg "forum") returns whether the object
2674 * is visible or not
2675 *
2676 * @uses $CFG
2677 * @param $moduletype ?
2678 * @param $module ?
7290c7fa 2679 * @return bool
fbc21ae8 2680 * @todo Finish documenting this function
2681 */
580f2fbc 2682function instance_is_visible($moduletype, $module) {
580f2fbc 2683
2684 global $CFG;
2685
2b49ae96 2686 if (!empty($module->id)) {
2687 if ($records = get_records_sql("SELECT cm.instance, cm.visible
2688 FROM {$CFG->prefix}course_modules cm,
2689 {$CFG->prefix}modules m
2690 WHERE cm.course = '$module->course' AND
2691 cm.module = m.id AND
2692 m.name = '$moduletype' AND
2693 cm.instance = '$module->id'")) {
2694
2695 foreach ($records as $record) { // there should only be one - use the first one
2696 return $record->visible;
2697 }
580f2fbc 2698 }
2699 }
580f2fbc 2700 return true; // visible by default!
2701}
2702
a3fb1c45 2703
2704
2705
9fa49e22 2706/// LOG FUNCTIONS /////////////////////////////////////////////////////
2707
2708
18a97fd8 2709/**
fbc21ae8 2710 * Add an entry to the log table.
2711 *
2712 * Add an entry to the log table. These are "action" focussed rather
2713 * than web server hits, and provide a way to easily reconstruct what
2714 * any particular student has been doing.
2715 *
2716 * @uses $CFG
2717 * @uses $USER
2718 * @uses $db
2719 * @uses $REMOTE_ADDR
2720 * @uses SITEID
89dcb99d 2721 * @param int $courseid The course id
fbc21ae8 2722 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
2723 * @param string $action View, edit, post (often but not always the same as the file.php)
2724 * @param string $url The file and parameters used to see the results of the action
2725 * @param string $info Additional description information
2726 * @param string $cm The course_module->id if there is one
2727 * @param string $user If log regards $user other than $USER
2728 */
d4419d55 2729function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
9fa49e22 2730
fcaff7ff 2731 global $db, $CFG, $USER;
9fa49e22 2732
7a5b1fc5 2733 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 2734 $cm = 0;
2735 }
2736
3d94772d 2737 if ($user) {
2738 $userid = $user;
2739 } else {
2740 if (isset($USER->realuser)) { // Don't log
2741 return;
2742 }
d4419d55 2743 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 2744 }
2745
fcaff7ff 2746 $REMOTE_ADDR = getremoteaddr();
2747
9fa49e22 2748 $timenow = time();
2749 $info = addslashes($info);
10a760b9 2750 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
2751 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
2752 }
853df85e 2753
2754 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
2755
d4419d55 2756 $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
2757 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
ebc3bd2b 2758
ce78926d 2759 if (!$result and ($CFG->debug > 7)) {
d4419d55 2760 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
8f0cd6ef 2761 }
f78b3c34 2762 if ( isset($USER) && (empty($user) || $user==$USER->id) ) {
114176a2 2763 $db->Execute('UPDATE '. $CFG->prefix .'user SET lastIP=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
c2aa460f 2764 WHERE id = \''. $userid .'\' ');
e3a23213 2765 if ($courseid != SITEID && !empty($courseid)) { // logins etc dont't have a courseid and isteacher will break without it.
853df85e 2766 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
114176a2 2767 if (isstudent($courseid)) {
2768 $db->Execute('UPDATE '. $CFG->prefix .'user_students SET timeaccess = \''. $timenow .'\' '.
2769 'WHERE course = \''. $courseid .'\' AND userid = \''. $userid .'\'');
2770 } else if (isteacher($courseid, false, false)) {
2771 $db->Execute('UPDATE '. $CFG->prefix .'user_teachers SET timeaccess = \''. $timenow .'\' '.
2772 'WHERE course = \''. $courseid .'\' AND userid = \''. $userid .'\'');
2773 }
3d94772d 2774 }
8f0cd6ef 2775 }
9fa49e22 2776}
2777
2778
18a97fd8 2779/**
fbc21ae8 2780 * Select all log records based on SQL criteria
2781 *
2782 * @uses $CFG
2783 * @param string $select SQL select criteria
2784 * @param string $order SQL order by clause to sort the records returned
2785 * @param string $limitfrom ?
2786 * @param int $limitnum ?
2787 * @param int $totalcount Passed in by reference.
7290c7fa 2788 * @return object
fbc21ae8 2789 * @todo Finish documenting this function
2790 */
d4419d55 2791function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
9fa49e22 2792 global $CFG;
2793
d4419d55 2794 if ($limitfrom !== '') {
29daf3a0 2795 $limit = sql_paging_limit($limitfrom, $limitnum);
519d369f 2796 } else {
d4419d55 2797 $limit = '';
519d369f 2798 }
2799
2800 if ($order) {
d4419d55 2801 $order = 'ORDER BY '. $order;
519d369f 2802 }
2803
fbc21ae8 2804 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
a2ddd957 2805 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
2806
2807 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
519d369f 2808
d4419d55 2809 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
2810 FROM '. $selectsql .' '. $order .' '. $limit);
9fa49e22 2811}
2812
519d369f 2813
18a97fd8 2814/**
fbc21ae8 2815 * Select all log records for a given course and user
2816 *
2817 * @uses $CFG
2f87145b 2818 * @uses DAYSECS
fbc21ae8 2819 * @param int $userid The id of the user as found in the 'user' table.
2820 * @param int $courseid The id of the course as found in the 'course' table.
2821 * @param string $coursestart ?
2822 * @todo Finish documenting this function
2823 */
9fa49e22 2824function get_logs_usercourse($userid, $courseid, $coursestart) {
2825 global $CFG;
2826
da0c90c3 2827 if ($courseid) {
d4419d55 2828 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 2829 } else {
2830 $courseselect = '';
da0c90c3 2831 }
2832
1604a0fc 2833 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
8f0cd6ef 2834 FROM {$CFG->prefix}log
2835 WHERE userid = '$userid'
1604a0fc 2836 AND time > '$coursestart' $courseselect
9fa49e22 2837 GROUP BY day ");
2838}
2839
18a97fd8 2840/**
fbc21ae8 2841 * Select all log records for a given course, user, and day
2842 *
2843 * @uses $CFG
2f87145b 2844 * @uses HOURSECS
fbc21ae8 2845 * @param int $userid The id of the user as found in the 'user' table.
2846 * @param int $courseid The id of the course as found in the 'course' table.
2847 * @param string $daystart ?
7290c7fa 2848 * @return object
fbc21ae8 2849 * @todo Finish documenting this function
2850 */
9fa49e22 2851function get_logs_userday($userid, $courseid, $daystart) {
2852 global $CFG;
2853
7e4a6488 2854 if ($courseid) {
d4419d55 2855 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 2856 } else {
2857 $courseselect = '';
7e4a6488 2858 }
2859
1604a0fc 2860 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
9fa49e22 2861 FROM {$CFG->prefix}log
8f0cd6ef 2862 WHERE userid = '$userid'
1604a0fc 2863 AND time > '$daystart' $courseselect
9fa49e22 2864 GROUP BY hour ");
2865}
2866
b4bac9b6 2867/**
2868 * Returns an object with counts of failed login attempts
2869 *
8f0cd6ef 2870 * Returns information about failed login attempts. If the current user is
2871 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 2872 * number of accounts. For non-admins, only the attempts on the given user
2873 * are shown.
2874 *
fbc21ae8 2875 * @param string $mode Either 'admin', 'teacher' or 'everybody'
2876 * @param string $username The username we are searching for
2877 * @param string $lastlogin The date from which we are searching
2878 * @return int
b4bac9b6 2879 */
b4bac9b6 2880function count_login_failures($mode, $username, $lastlogin) {
2881
d4419d55 2882 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
b4bac9b6 2883
2884 if (isadmin()) { // Return information about all accounts
2885 if ($count->attempts = count_records_select('log', $select)) {
2886 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
2887 return $count;
2888 }
9407d456 2889 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
d4419d55 2890 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
b4bac9b6 2891 return $count;
2892 }
2893 }
2894 return NULL;
2895}
2896
2897
a3fb1c45 2898/// GENERAL HELPFUL THINGS ///////////////////////////////////
2899
18a97fd8 2900/**
fbc21ae8 2901 * Dump a given object's information in a PRE block.
2902 *
2903 * Mostly just used for debugging.
2904 *
2905 * @param mixed $object The data to be printed
2906 * @todo add example usage and example output
2907 */
a3fb1c45 2908function print_object($object) {
a3fb1c45 2909
d4419d55 2910 echo '<pre>';
2b051f1c 2911 print_r($object);
d4419d55 2912 echo '</pre>';
a3fb1c45 2913}
2914
29daf3a0 2915/**
2916 * Returns the proper SQL to do paging
2917 *
7290c7fa 2918 * @uses $CFG
2919 * @param string $page Offset page number
2920 * @param string $recordsperpage Number of records per page
2921 * @return string
29daf3a0 2922 */
2923function sql_paging_limit($page, $recordsperpage) {
2924 global $CFG;
2925
2926 switch ($CFG->dbtype) {
2927 case 'postgres7':
2928 return 'LIMIT '. $recordsperpage .' OFFSET '. $page;
2929 default:
2930 return 'LIMIT '. $page .','. $recordsperpage;
2931 }
2932}
2933
2934/**
2935 * Returns the proper SQL to do LIKE in a case-insensitive way
2936 *
7290c7fa 2937 * @uses $CFG
2938 * @return string
29daf3a0 2939 */
2940function sql_ilike() {
2941 global $CFG;
a3fb1c45 2942
29daf3a0 2943 switch ($CFG->dbtype) {
2944 case 'mysql':
2945 return 'LIKE';
2946 default:
2947 return 'ILIKE';
2948 }
2949}
2950
2951
2952/**
2953 * Returns the proper SQL to do LIKE in a case-insensitive way
2954 *
7290c7fa 2955 * @uses $CFG
2956 * @param string $firstname User's first name
2957 * @param string $lastname User's last name
2958 * @return string
29daf3a0 2959 */
7290c7fa 2960function sql_fullname($firstname='firstname', $lastname='lastname') {
29daf3a0 2961 global $CFG;
2962
2963 switch ($CFG->dbtype) {
2964 case 'mysql':
7290c7fa 2965 return ' CONCAT('. $firstname .'," ",'. $lastname .') ';
29daf3a0 2966 case 'postgres7':
7290c7fa 2967 return " ". $firstname ."||' '||". $lastname ." ";
29daf3a0 2968 default:
7290c7fa 2969 return ' '. $firstname .'||" "||'. $lastname .' ';
29daf3a0 2970 }
2971}
9fa49e22 2972
a0413b58 2973/**
2974 * Returns the proper SQL to do IS NULL
7290c7fa 2975 * @uses $CFG
2976 * @param string $fieldname The field to add IS NULL to
2977 * @return string
a0413b58 2978 */
2979function sql_isnull($fieldname) {
2980 global $CFG;
2981
2982 switch ($CFG->dbtype) {
2983 case 'mysql':
2984 return $fieldname.' IS NULL';
2985 default:
2986 return $fieldname.' IS NULL';
2987 }
2988}
2989
9d5b689c 2990// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f6f319f8 2991?>