New help file to cover new additions to uploadusers format (for teachers)
[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;
a2bed059 1134 static $empty_rs_cache;
0892f7bd 1135
853df85e 1136 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1137
a2bed059 1138 /// Get an empty recordset. Cache for multiple inserts.
8f0cd6ef 1139
a2bed059 1140 if (empty($empty_rs_cache[$table])) {
1141
1142 /// Execute a dummy query to get an empty recordset
1143 if (!$empty_rs_cache[$table] = $db->Execute('SELECT * FROM '. $CFG->prefix . $table .' WHERE '. $primarykey .' = \'-1\'')) {
1144 return false;
1145 }
1146
1147 /// In Moodle we always use auto-numbering fields for the primary ID
1148 /// so let's unset it now before it causes any trouble
1149 unset($dataobject->{$primarykey});
1150 }
2327ce8e 1151
a2bed059 1152 $rs = $empty_rs_cache[$table];
2327ce8e 1153
a9a9bdba 1154 /// Postgres doesn't have the concept of primary key built in
1155 /// and will return the OID which isn't what we want.
1156 /// The efficient and transaction-safe strategy is to
1157 /// move the sequence forward first, and make the insert
1158 /// with an explicit id.
2eab0668 1159 if ( empty($dataobject->{$primarykey})
a9a9bdba 1160 && $CFG->dbtype === 'postgres7'
1161 && $returnid == true ) {
9921028a 1162 if ($nextval = (int)get_field_sql("SELECT NEXTVAL('{$CFG->prefix}{$table}_{$primarykey}_seq')")) {
a9a9bdba 1163 $dataobject->{$primarykey} = $nextval;
1164 }
1165 }
1166
d4469f2a 1167/// Get the correct SQL from adoDB
1168 if (!$insertSQL = $db->GetInsertSQL($rs, (array)$dataobject, true)) {
1169 return false;
1170 }
8f0cd6ef 1171
d4469f2a 1172/// Run the SQL statement
1173 if (!$rs = $db->Execute($insertSQL)) {
2eef791f 1174 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 1175 notify($db->ErrorMsg() .'<br /><br />'.$insertSQL);
9c7fee6c 1176 }
acd2279e 1177 if (!empty($CFG->dblogerror)) {
31df0bb8 1178 $debug=array_shift(debug_backtrace());
acd2279e 1179 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $insertSQL");
1180 }
0892f7bd 1181 return false;
1182 }
8f0cd6ef 1183
d4469f2a 1184/// If a return ID is not needed then just return true now
8f0cd6ef 1185 if (!$returnid) {
0892f7bd 1186 return true;
1187 }
1188
f4cbf7f2 1189/// We already know the record PK if it's been passed explicitly,
1190/// or if we've retrieved it from a sequence (Postgres).
2eab0668 1191 if (!empty($dataobject->{$primarykey})) {
a9a9bdba 1192 return $dataobject->{$primarykey};
1193 }
0892f7bd 1194
a9a9bdba 1195/// This only gets triggered with non-Postgres databases
1196/// however we have some postgres fallback in case we failed
1197/// to find the sequence.
1198 $id = $db->Insert_ID();
1199
1200 if ($CFG->dbtype === 'postgres7') {
1201 // try to get the primary key based on id
1202 if ( ($rs = $db->Execute('SELECT '. $primarykey .' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id))
1203 && ($rs->RecordCount() == 1) ) {
1204 trigger_error("Retrieved $primarykey from oid on table $table because we could not find the sequence.");
1205 return (integer)$rs->fields[0];
1206 }
f4cbf7f2 1207 trigger_error('Failed to retrieve primary key after insert: SELECT '. $primarykey .
1208 ' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id);
a9a9bdba 1209 return false;
0892f7bd 1210 }
a9a9bdba 1211
1212 return (integer)$id;
0892f7bd 1213}
1214
11a052a6 1215/**
1216 * Escape all dangerous characters in a data record
1217 *
1218 * $dataobject is an object containing needed data
1219 * Run over each field exectuting addslashes() function
1220 * to escape SQL unfriendly characters (e.g. quotes)
1221 * Handy when writing back data read from the database
1222 *
1223 * @param $dataobject Object containing the database record
1224 * @return object Same object with neccessary characters escaped
1225 */
1226function addslashes_object( $dataobject ) {
1227 $a = get_object_vars( $dataobject);
1228 foreach ($a as $key=>$value) {
1229 $a[$key] = addslashes( $value );
1230 }
1231 return (object)$a;
1232}
0892f7bd 1233
18a97fd8 1234/**
fbc21ae8 1235 * Update a record in a table
1236 *
1237 * $dataobject is an object containing needed data
1238 * Relies on $dataobject having a variable "id" to
1239 * specify the record to update
1240 *
1241 * @uses $CFG
1242 * @uses $db
1243 * @param string $table The database table to be checked against.
11a052a6 1244 * @param array $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
7290c7fa 1245 * @return bool
fbc21ae8 1246 * @todo Finish documenting this function. Dataobject is actually an associateive array, correct?
1247 */
df28d6c5 1248function update_record($table, $dataobject) {
df28d6c5 1249
1250 global $db, $CFG;
1251
1252 if (! isset($dataobject->id) ) {
1253 return false;
1254 }
1255
1256 // Determine all the fields in the table
d4419d55 1257 if (!$columns = $db->MetaColumns($CFG->prefix . $table)) {
df28d6c5 1258 return false;
1259 }
1260 $data = (array)$dataobject;
1261
853df85e 1262 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
1263
df28d6c5 1264 // Pull out data matching these fields
1265 foreach ($columns as $column) {
d4419d55 1266 if ($column->name <> 'id' and isset($data[$column->name]) ) {
df28d6c5 1267 $ddd[$column->name] = $data[$column->name];
1268 }
1269 }
1270
1271 // Construct SQL queries
1272 $numddd = count($ddd);
1273 $count = 0;
d4419d55 1274 $update = '';
df28d6c5 1275
1276 foreach ($ddd as $key => $value) {
1277 $count++;
705a2aa4 1278 $update .= $key .' = \''. $value .'\''; // All incoming data is already quoted
df28d6c5 1279 if ($count < $numddd) {
d4419d55 1280 $update .= ', ';
df28d6c5 1281 }
1282 }
1283
d4419d55 1284 if ($rs = $db->Execute('UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE id = \''. $dataobject->id .'\'')) {
df28d6c5 1285 return true;
1286 } else {
2eef791f 1287 if (isset($CFG->debug) and $CFG->debug > 7) {
d4419d55 1288 notify($db->ErrorMsg() .'<br /><br />UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE id = \''. $dataobject->id .'\'');
9c7fee6c 1289 }
acd2279e 1290 if (!empty($CFG->dblogerror)) {
31df0bb8 1291 $debug=array_shift(debug_backtrace());
acd2279e 1292 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: UPDATE $CFG->prefix$table SET $update WHERE id = '$dataobject->id'");
1293 }
df28d6c5 1294 return false;
1295 }
1296}
1297
1298
df28d6c5 1299
1300
1301/// USER DATABASE ////////////////////////////////////////////////
1302
18a97fd8 1303/**
fbc21ae8 1304 * Does this username and password specify a valid admin user?
1305 *
1306 * @uses $CFG
1307 * @param string $username The name of the user to be tested for admin rights
1308 * @param string $md5password The password supplied by the user in md5 encrypted format.
7290c7fa 1309 * @return bool
fbc21ae8 1310 */
df28d6c5 1311function adminlogin($username, $md5password) {
df28d6c5 1312
1313 global $CFG;
1314
8f0cd6ef 1315 return record_exists_sql("SELECT u.id
1316 FROM {$CFG->prefix}user u,
1317 {$CFG->prefix}user_admins a
1318 WHERE u.id = a.userid
1319 AND u.username = '$username'
df28d6c5 1320 AND u.password = '$md5password'");
1321}
1322
18a97fd8 1323/**
fbc21ae8 1324 * Get the guest user information from the database
1325 *
1326 * @return object(user) An associative array with the details of the guest user account.
1327 * @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.
1328 */
9fa49e22 1329function get_guest() {
7c12949d 1330 return get_complete_user_data('username', 'guest');
9fa49e22 1331}
1332
1333
18a97fd8 1334/**
fbc21ae8 1335 * Returns $user object of the main admin user
1336 *
1337 * @uses $CFG
1338 * @return object(admin) An associative array representing the admin user.
1339 * @todo Verify documentation of this function
1340 */
df28d6c5 1341function get_admin () {
df28d6c5 1342
1343 global $CFG;
1344
1345 if ( $admins = get_admins() ) {
1346 foreach ($admins as $admin) {
8f0cd6ef 1347 return $admin; // ie the first one
df28d6c5 1348 }
1349 } else {
1350 return false;
1351 }
1352}
1353
18a97fd8 1354/**
fbc21ae8 1355 * Returns list of all admins
1356 *
1357 * @uses $CFG
7290c7fa 1358 * @return object
fbc21ae8 1359 */
df28d6c5 1360function get_admins() {
df28d6c5 1361
1362 global $CFG;
1363
8f0cd6ef 1364 return get_records_sql("SELECT u.*, a.id as adminid
1365 FROM {$CFG->prefix}user u,
ebc3bd2b 1366 {$CFG->prefix}user_admins a
1367 WHERE a.userid = u.id
427fdf66 1368 ORDER BY a.id ASC");
df28d6c5 1369}
1370
18a97fd8 1371/**
fbc21ae8 1372 * Returns list of all creators
1373 *
1374 * @uses $CFG
7290c7fa 1375 * @return object
fbc21ae8 1376 */
1924074c 1377function get_creators() {
1924074c 1378
1379 global $CFG;
1380
1381 return get_records_sql("SELECT u.*
1382 FROM {$CFG->prefix}user u,
1383 {$CFG->prefix}user_coursecreators a
1384 WHERE a.userid = u.id
1385 ORDER BY u.id ASC");
1386}
df28d6c5 1387
b61efafb 1388function get_courses_in_metacourse($metacourseid) {
1389 global $CFG;
1390
5f37b628 1391 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
5afa0de6 1392 AND mc.child_course = c.id ORDER BY c.shortname";
b61efafb 1393
1394 return get_records_sql($sql);
1395}
1396
1397function get_courses_notin_metacourse($metacourseid,$count=false) {
1398
1399 global $CFG;
1400
b61efafb 1401 if ($count) {
1402 $sql = "SELECT COUNT(c.id)";
c44d5d42 1403 } else {
b61efafb 1404 $sql = "SELECT c.id,c.shortname,c.fullname";
1405 }
178ccd11 1406
ffed6bf3 1407 $alreadycourses = get_courses_in_metacourse($metacourseid);
1408
c44d5d42 1409 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
5afa0de6 1410 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
1411
b61efafb 1412 return get_records_sql($sql);
1413}
1414
1415
18a97fd8 1416/**
fbc21ae8 1417 * Returns $user object of the main teacher for a course
1418 *
1419 * @uses $CFG
1420 * @param int $courseid The course in question.
89dcb99d 1421 * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
fbc21ae8 1422 * @todo Finish documenting this function
1423 */
df28d6c5 1424function get_teacher($courseid) {
df28d6c5 1425
1426 global $CFG;
1427
d4419d55 1428 if ( $teachers = get_course_teachers($courseid, 't.authority ASC')) {
df28d6c5 1429 foreach ($teachers as $teacher) {
1430 if ($teacher->authority) {
1431 return $teacher; // the highest authority teacher
1432 }
1433 }
1434 } else {
1435 return false;
1436 }
1437}
1438
18a97fd8 1439/**
fbc21ae8 1440 * Searches logs to find all enrolments since a certain date
1441 *
1442 * used to print recent activity
1443 *
1444 * @uses $CFG
1445 * @param int $courseid The course in question.
7290c7fa 1446 * @return object|false {@link $USER} records or false if error.
fbc21ae8 1447 * @todo Finish documenting this function
1448 */
0a08581d 1449function get_recent_enrolments($courseid, $timestart) {
0a08581d 1450
1451 global $CFG;
1452
fbf5081c 1453 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
0a08581d 1454 FROM {$CFG->prefix}user u,
1455 {$CFG->prefix}user_students s,
1456 {$CFG->prefix}log l
8f0cd6ef 1457 WHERE l.time > '$timestart'
0a08581d 1458 AND l.course = '$courseid'
8f0cd6ef 1459 AND l.module = 'course'
0a08581d 1460 AND l.action = 'enrol'
1461 AND l.info = u.id
1462 AND u.id = s.userid
64cbb55c 1463 AND s.course = '$courseid'
0a08581d 1464 ORDER BY l.time ASC");
1465}
1466
18a97fd8 1467/**
fbc21ae8 1468 * Returns array of userinfo of all students in this course
1469 * or on this site if courseid is id of site
1470 *
1471 * @uses $CFG
1472 * @uses SITEID
1473 * @param int $courseid The course in question.
1474 * @param string $sort ?
1475 * @param string $dir ?
1476 * @param int $page ?
1477 * @param int $recordsperpage ?
1478 * @param string $firstinitial ?
1479 * @param string $lastinitial ?
1480 * @param ? $group ?
1481 * @param string $search ?
1482 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1483 * @param string $exceptions ?
7290c7fa 1484 * @return object
fbc21ae8 1485 * @todo Finish documenting this function
1486 */
d4419d55 1487function get_course_students($courseid, $sort='s.timeaccess', $dir='', $page=0, $recordsperpage=99999,
1488 $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
df28d6c5 1489
1490 global $CFG;
8f0cd6ef 1491
1492 if ($courseid == SITEID and $CFG->allusersaresitestudents) {
2700d113 1493 // return users with confirmed, undeleted accounts who are not site teachers
1494 // the following is a mess because of different conventions in the different user functions
1495 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
1496 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
1497 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
8f0cd6ef 1498 $fields = str_replace('u.', '', $fields);
2700d113 1499 if ($sort) {
d4419d55 1500 $sort = $sort .' '. $dir;
2700d113 1501 }
1502 // Now we have to make sure site teachers are excluded
1503 if ($teachers = get_records('user_teachers', 'course', SITEID)) {
1504 foreach ($teachers as $teacher) {
d4419d55 1505 $exceptions .= ','. $teacher->userid;
2700d113 1506 }
1507 $exceptions = ltrim($exceptions, ',');
1508 }
8f0cd6ef 1509 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
2700d113 1510 $page, $recordsperpage, $fields ? $fields : '*');
1511 }
df28d6c5 1512
29daf3a0 1513 $limit = sql_paging_limit($page, $recordsperpage);
1514 $LIKE = sql_ilike();
1515 $fullname = sql_fullname('u.firstname','u.lastname');
a328425d 1516
0720313b 1517 $groupmembers = '';
f950af3c 1518
1519 // make sure it works on the site course
d4419d55 1520 $select = 's.course = \''. $courseid .'\' AND ';
222ac91b 1521 if ($courseid == SITEID) {
f950af3c 1522 $select = '';
1523 }
1524
d4419d55 1525 $select .= 's.userid = u.id AND u.deleted = \'0\' ';
73fc8c1a 1526
1284a926 1527 if (!$fields) {
1528 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
1529 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
1530 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
1531 'u.emailstop, u.lang, u.timezone, s.timeaccess as lastaccess';
1532 }
1533
73fc8c1a 1534 if ($search) {
d4419d55 1535 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
73fc8c1a 1536 }
a328425d 1537
1538 if ($firstinitial) {
d4419d55 1539 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
a328425d 1540 }
1541
1542 if ($lastinitial) {
d4419d55 1543 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
4969ad74 1544 }
1545
3d35e6b7 1546 if ($group === 0) { /// Need something here to get all students not in a group
1547 return array();
1548
1549 } else if ($group !== NULL) {
d4419d55 1550 $groupmembers = ', '. $CFG->prefix .'groups_members gm ';
1551 $select .= ' AND u.id = gm.userid AND gm.groupid = \''. $group .'\'';
0720313b 1552 }
8f0cd6ef 1553
900df8b6 1554 if (!empty($exceptions)) {
d4419d55 1555 $select .= ' AND u.id NOT IN ('. $exceptions .')';
900df8b6 1556 }
0720313b 1557
8e4c9ef7 1558 if ($sort) {
d4419d55 1559 $sort = ' ORDER BY '. $sort .' ';
8e4c9ef7 1560 }
1561
2700d113 1562 $students = get_records_sql("SELECT $fields
488acd1b 1563 FROM {$CFG->prefix}user u,
1564 {$CFG->prefix}user_students s
1565 $groupmembers
73fc8c1a 1566 WHERE $select $search $sort $dir $limit");
2700d113 1567
1568 if ($courseid != SITEID) {
1569 return $students;
1570 }
8f0cd6ef 1571
2700d113 1572 // We are here because we need the students for the site.
1573 // These also include teachers on real courses minus those on the site
1574 if ($teachers = get_records('user_teachers', 'course', SITEID)) {
1575 foreach ($teachers as $teacher) {
d4419d55 1576 $exceptions .= ','. $teacher->userid;
2700d113 1577 }
1578 $exceptions = ltrim($exceptions, ',');
d4419d55 1579 $select .= ' AND u.id NOT IN ('. $exceptions .')';
2700d113 1580 }
1581 if (!$teachers = get_records_sql("SELECT $fields
1582 FROM {$CFG->prefix}user u,
1583 {$CFG->prefix}user_teachers s
1584 $groupmembers
1585 WHERE $select $search $sort $dir $limit")) {
1586 return $students;
1587 }
1588 if (!$students) {
1589 return $teachers;
1590 }
1591 return $teachers + $students;
df28d6c5 1592}
1593
fbc21ae8 1594
a328425d 1595/**
fbc21ae8 1596 * Counts the students in a given course (or site), or a subset of them
1597 *
1598 * @param object $course The course in question as a course object.
1599 * @param string $search ?
1600 * @param string $firstinitial ?
1601 * @param string $lastinitial ?
1602 * @param ? $group ?
1603 * @param string $exceptions ?
1604 * @return int
1605 * @todo Finish documenting this function
1606 */
d4419d55 1607function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
a328425d 1608
2700d113 1609 if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
1610 return count($students);
a328425d 1611 }
2700d113 1612 return 0;
a328425d 1613}
1614
1615
18a97fd8 1616/**
fbc21ae8 1617 * Returns list of all teachers in this course
1618 *
1619 * If $courseid matches the site id then this function
1620 * returns a list of all teachers for the site.
1621 *
1622 * @uses $CFG
1623 * @param int $courseid The course in question.
1624 * @param string $sort ?
1625 * @param string $exceptions ?
7290c7fa 1626 * @return object
fbc21ae8 1627 * @todo Finish documenting this function
1628 */
d4419d55 1629function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
df28d6c5 1630
1631 global $CFG;
1632
900df8b6 1633 if (!empty($exceptions)) {
f6f319f8 1634 $exceptions = ' AND u.id NOT IN ('. $exceptions .') ';
1635 }
1636
1637 if (!empty($sort)) {
1638 $sort = ' ORDER by '.$sort;
900df8b6 1639 }
1640
8d241374 1641 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
8f0cd6ef 1642 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
86fb5ed5 1643 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
8f0cd6ef 1644 FROM {$CFG->prefix}user u,
688d06f4 1645 {$CFG->prefix}user_teachers t
8f0cd6ef 1646 WHERE t.course = '$courseid' AND t.userid = u.id
f6f319f8 1647 AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
df28d6c5 1648}
1649
18a97fd8 1650/**
fbc21ae8 1651 * Returns all the users of a course: students and teachers
1652 *
1653 * @param int $courseid The course in question.
1654 * @param string $sort ?
1655 * @param string $exceptions ?
1656 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 1657 * @return object
fbc21ae8 1658 * @todo Finish documenting this function
1659 */
d4419d55 1660function get_course_users($courseid, $sort='timeaccess DESC', $exceptions='', $fields='') {
353d0338 1661
900df8b6 1662 /// Using this method because the single SQL is too inefficient
1663 // Note that this has the effect that teachers and students are
1664 // sorted individually. Returns first all teachers, then all students
0720313b 1665
900df8b6 1666 if (!$teachers = get_course_teachers($courseid, $sort, $exceptions)) {
1667 $teachers = array();
1668 }
65ee9c16 1669 if (!$students = get_course_students($courseid, $sort, '', 0, 99999, '', '', NULL, '', $fields, $exceptions)) {
900df8b6 1670 $students = array();
1671 }
df28d6c5 1672
900df8b6 1673 return $teachers + $students;
0720313b 1674
900df8b6 1675}
0720313b 1676
900df8b6 1677/**
fbc21ae8 1678 * Search through course users
1679 *
1680 * If $coursid specifies the site course then this function searches
1681 * through all undeleted and confirmed users
1682 *
1683 * @uses $CFG
1684 * @uses SITEID
1685 * @param int $courseid The course in question.
1686 * @param int $groupid The group in question.
1687 * @param string $searchtext ?
1688 * @param string $sort ?
1689 * @param string $exceptions ?
7290c7fa 1690 * @return object
fbc21ae8 1691 * @todo Finish documenting this function
1692 */
900df8b6 1693function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
1694 global $CFG;
0720313b 1695
29daf3a0 1696 $LIKE = sql_ilike();
1697 $fullname = sql_fullname('u.firstname', 'u.lastname');
8f0cd6ef 1698
900df8b6 1699 if (!empty($exceptions)) {
d4419d55 1700 $except = ' AND u.id NOT IN ('. $exceptions .') ';
900df8b6 1701 } else {
1702 $except = '';
1703 }
2700d113 1704
900df8b6 1705 if (!empty($sort)) {
d4419d55 1706 $order = ' ORDER BY '. $sort;
900df8b6 1707 } else {
1708 $order = '';
1709 }
8f0cd6ef 1710
d4419d55 1711 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
2700d113 1712
222ac91b 1713 if (!$courseid or $courseid == SITEID) {
2700d113 1714 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
1715 FROM {$CFG->prefix}user u
1716 WHERE $select
900df8b6 1717 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
2700d113 1718 $except $order");
8f0cd6ef 1719 } else {
2700d113 1720
900df8b6 1721 if ($groupid) {
1722 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1723 FROM {$CFG->prefix}user u,
900df8b6 1724 {$CFG->prefix}groups_members g
2700d113 1725 WHERE $select AND g.groupid = '$groupid' AND g.userid = u.id
900df8b6 1726 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1727 $except $order");
1728 } else {
1729 if (!$teachers = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1730 FROM {$CFG->prefix}user u,
900df8b6 1731 {$CFG->prefix}user_teachers s
2700d113 1732 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
900df8b6 1733 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1734 $except $order")) {
1735 $teachers = array();
1736 }
1737 if (!$students = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 1738 FROM {$CFG->prefix}user u,
900df8b6 1739 {$CFG->prefix}user_students s
2700d113 1740 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
900df8b6 1741 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
1742 $except $order")) {
1743 $students = array();
1744 }
1745 return $teachers + $students;
1746 }
1747 }
df28d6c5 1748}
1749
2700d113 1750
18a97fd8 1751/**
fbc21ae8 1752 * Returns a list of all site users
1753 * Obsolete, just calls get_course_users(SITEID)
1754 *
1755 * @uses SITEID
c6d15803 1756 * @deprecated Use {@link get_course_users()} instead.
fbc21ae8 1757 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 1758 * @return object|false {@link $USER} records or false if error.
fbc21ae8 1759 * @todo Finish documenting this function. The return type need to be better defined.
1760 */
d4419d55 1761function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='') {
2d0b30a0 1762
65ee9c16 1763 return get_course_users(SITEID, $sort, $exceptions, $fields);
2d0b30a0 1764}
1765
9fa49e22 1766
18a97fd8 1767/**
fbc21ae8 1768 * Returns a subset of users
1769 *
1770 * @uses $CFG
7290c7fa 1771 * @param bool $get If false then only a count of the records is returned
fbc21ae8 1772 * @param string $search A simple string to search for
7290c7fa 1773 * @param bool $confirmed A switch to allow/disallow unconfirmed users
fbc21ae8 1774 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
1775 * @param string $sort A SQL snippet for the sorting criteria to use
1776 * @param string $firstinitial ?
1777 * @param string $lastinitial ?
1778 * @param string $page ?
1779 * @param string $recordsperpage ?
1780 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 1781 * @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 1782 * @todo Finish documenting this function. The return type needs to be better defined.
1783 */
d4419d55 1784function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
1785 $firstinitial='', $lastinitial='', $page=0, $recordsperpage=99999, $fields='*') {
18a97fd8 1786
1787 global $CFG;
1788
29daf3a0 1789 $limit = sql_paging_limit($page, $recordsperpage);
1790 $LIKE = sql_ilike();
1791 $fullname = sql_fullname();
e384fb7b 1792
d4419d55 1793 $select = 'username <> \'guest\' AND deleted = 0';
488acd1b 1794
0044147e 1795 if (!empty($search)){
1796 $search = trim($search);
488acd1b 1797 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
e384fb7b 1798 }
1799
5a741655 1800 if ($confirmed) {
d4419d55 1801 $select .= ' AND confirmed = \'1\' ';
5a741655 1802 }
1803
1804 if ($exceptions) {
d4419d55 1805 $select .= ' AND id NOT IN ('. $exceptions .') ';
5a741655 1806 }
1807
488acd1b 1808 if ($firstinitial) {
d4419d55 1809 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
8f0cd6ef 1810 }
488acd1b 1811 if ($lastinitial) {
d4419d55 1812 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
8f0cd6ef 1813 }
488acd1b 1814
5a741655 1815 if ($sort and $get) {
d4419d55 1816 $sort = ' ORDER BY '. $sort .' ';
5a741655 1817 } else {
d4419d55 1818 $sort = '';
5a741655 1819 }
1820
1821 if ($get) {
d4419d55 1822 return get_records_select('user', $select .' '. $sort .' '. $limit, '', $fields);
5a741655 1823 } else {
d4419d55 1824 return count_records_select('user', $select .' '. $sort .' '. $limit);
5a741655 1825 }
9fa49e22 1826}
1827
5a741655 1828
18a97fd8 1829/**
fbc21ae8 1830 * shortdesc (optional)
1831 *
1832 * longdesc
1833 *
1834 * @uses $CFG
1835 * @param string $sort ?
1836 * @param string $dir ?
1837 * @param int $categoryid ?
1838 * @param int $categoryid ?
1839 * @param string $search ?
1840 * @param string $firstinitial ?
1841 * @param string $lastinitial ?
7290c7fa 1842 * @returnobject {@link $USER} records
fbc21ae8 1843 * @todo Finish documenting this function
1844 */
1845
d4419d55 1846function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=99999,
7cf1c7bd 1847 $search='', $firstinitial='', $lastinitial='') {
488acd1b 1848
9fa49e22 1849 global $CFG;
31fefa63 1850
29daf3a0 1851 $limit = sql_paging_limit($page, $recordsperpage);
1852 $LIKE = sql_ilike();
1853 $fullname = sql_fullname();
c2a96d6b 1854
488acd1b 1855 $select = 'deleted <> 1';
1856
0044147e 1857 if (!empty($search)) {
1858 $search = trim($search);
488acd1b 1859 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
1860 }
1861
1862 if ($firstinitial) {
d4419d55 1863 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
488acd1b 1864 }
1865
1866 if ($lastinitial) {
d4419d55 1867 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
c750592a 1868 }
1869
488acd1b 1870 if ($sort) {
d4419d55 1871 $sort = ' ORDER BY '. $sort .' '. $dir;
488acd1b 1872 }
1873
1874/// warning: will return UNCONFIRMED USERS
ea5d48ee 1875 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed
8f0cd6ef 1876 FROM {$CFG->prefix}user
488acd1b 1877 WHERE $select $sort $limit ");
9fa49e22 1878
1879}
1880
488acd1b 1881
18a97fd8 1882/**
7290c7fa 1883 * Full list of users that have confirmed their accounts.
fbc21ae8 1884 *
1885 * @uses $CFG
7290c7fa 1886 * @return object
fbc21ae8 1887 */
9fa49e22 1888function get_users_confirmed() {
1889 global $CFG;
8f0cd6ef 1890 return get_records_sql("SELECT *
1891 FROM {$CFG->prefix}user
1892 WHERE confirmed = 1
9fa49e22 1893 AND deleted = 0
8f0cd6ef 1894 AND username <> 'guest'
9fa49e22 1895 AND username <> 'changeme'");
1896}
1897
1898
18a97fd8 1899/**
7290c7fa 1900 * Full list of users that have not yet confirmed their accounts.
fbc21ae8 1901 *
1902 * @uses $CFG
1903 * @param string $cutofftime ?
7290c7fa 1904 * @return object {@link $USER} records
fbc21ae8 1905 * @todo Finish documenting this function
1906 */
99988d1a 1907function get_users_unconfirmed($cutofftime=2000000000) {
9fa49e22 1908 global $CFG;
8f0cd6ef 1909 return get_records_sql("SELECT *
1910 FROM {$CFG->prefix}user
9fa49e22 1911 WHERE confirmed = 0
8f0cd6ef 1912 AND firstaccess > 0
9fa49e22 1913 AND firstaccess < '$cutofftime'");
1914}
1915
1916
18a97fd8 1917/**
fbc21ae8 1918 * shortdesc (optional)
1919 *
1920 * longdesc
1921 *
1922 * @uses $CFG
1923 * @param string $cutofftime ?
7290c7fa 1924 * @return object {@link $USER} records
fbc21ae8 1925 * @todo Finish documenting this function
1926 */
9fa49e22 1927function get_users_longtimenosee($cutofftime) {
1928 global $CFG;
937ae59c 1929 return get_records_sql("SELECT DISTINCT *
1930 FROM {$CFG->prefix}user_students
8f0cd6ef 1931 WHERE timeaccess > '0'
937ae59c 1932 AND timeaccess < '$cutofftime' ");
9fa49e22 1933}
1934
f374fb10 1935/**
fbc21ae8 1936 * Returns an array of group objects that the user is a member of
1937 * in the given course. If userid isn't specified, then return a
1938 * list of all groups in the course.
1939 *
1940 * @uses $CFG
89dcb99d 1941 * @param int $courseid The id of the course in question.
fbc21ae8 1942 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
7290c7fa 1943 * @return object
fbc21ae8 1944 */
f374fb10 1945function get_groups($courseid, $userid=0) {
1946 global $CFG;
1947
1948 if ($userid) {
d4419d55 1949 $dbselect = ', '. $CFG->prefix .'groups_members m';
1950 $userselect = 'AND m.groupid = g.id AND m.userid = \''. $userid .'\'';
2d439c9d 1951 } else {
1952 $dbselect = '';
1953 $userselect = '';
f374fb10 1954 }
1955
1956 return get_records_sql("SELECT DISTINCT g.*
2d439c9d 1957 FROM {$CFG->prefix}groups g $dbselect
f374fb10 1958 WHERE g.courseid = '$courseid' $userselect ");
1959}
1960
1961
1962/**
fbc21ae8 1963 * Returns an array of user objects
1964 *
1965 * @uses $CFG
1966 * @param int $groupid The group in question.
1967 * @param string $sort ?
1968 * @param string $exceptions ?
7290c7fa 1969 * @return object
fbc21ae8 1970 * @todo Finish documenting this function
1971 */
49668367 1972function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='', $fields='u.*') {
f374fb10 1973 global $CFG;
900df8b6 1974 if (!empty($exceptions)) {
d4419d55 1975 $except = ' AND u.id NOT IN ('. $exceptions .') ';
900df8b6 1976 } else {
1977 $except = '';
1978 }
c1147b7e 1979 // in postgres, you can't have things in sort that aren't in the select, so...
1980 $extrafield = str_replace('ASC','',$sort);
d5efb299 1981 $extrafield = str_replace('DESC','',$extrafield);
c1147b7e 1982 $extrafield = trim($extrafield);
1983 if (!empty($extrafield)) {
1984 $extrafield = ','.$extrafield;
1985 }
1986 return get_records_sql("SELECT DISTINCT $fields $extrafield
f374fb10 1987 FROM {$CFG->prefix}user u,
8f0cd6ef 1988 {$CFG->prefix}groups_members m
f374fb10 1989 WHERE m.groupid = '$groupid'
900df8b6 1990 AND m.userid = u.id $except
2c4263c4 1991 ORDER BY $sort");
f374fb10 1992}
1993
1994/**
fbc21ae8 1995 * An efficient way of finding all the users who aren't in groups yet
1996 *
1997 * Currently unimplemented.
1998 * @uses $CFG
1999 * @param int $courseid The course in question.
7290c7fa 2000 * @return object
fbc21ae8 2001 */
f374fb10 2002function get_users_not_in_group($courseid) {
2003 global $CFG;
2004
2005 return array(); /// XXX TO BE DONE
2006}
2007
60b025d1 2008/**
fbc21ae8 2009 * Returns an array of user objects
2010 *
2011 * @uses $CFG
2012 * @param int $groupid The group in question.
9b10b65b 2013 * @param string $sort How to sort the results
7290c7fa 2014 * @return object
fbc21ae8 2015 */
d4419d55 2016function get_group_students($groupid, $sort='u.lastaccess DESC') {
60b025d1 2017 global $CFG;
2018 return get_records_sql("SELECT DISTINCT u.*
2019 FROM {$CFG->prefix}user u,
2020 {$CFG->prefix}groups_members m,
2021 {$CFG->prefix}groups g,
2022 {$CFG->prefix}user_students s
2023 WHERE m.groupid = '$groupid'
8f0cd6ef 2024 AND m.userid = u.id
2025 AND m.groupid = g.id
60b025d1 2026 AND g.courseid = s.course
2027 AND s.userid = u.id
2028 ORDER BY $sort");
2029}
2030
9b10b65b 2031
2032/**
2033 * Returns list of all the teachers who can access a group
2034 *
2035 * @uses $CFG
2036 * @param int $courseid The course in question.
2037 * @param int $groupid The group in question.
7290c7fa 2038 * @return object
9b10b65b 2039 */
2040function get_group_teachers($courseid, $groupid) {
2041/// Returns a list of all the teachers who can access a group
2042 if ($teachers = get_course_teachers($courseid)) {
2043 foreach ($teachers as $key => $teacher) {
2044 if ($teacher->editall) { // These can access anything
2045 continue;
2046 }
2047 if (($teacher->authority > 0) and ismember($groupid, $teacher->id)) { // Specific group teachers
2048 continue;
2049 }
9a4d45ae 2050 unset($teachers[$key]);
9b10b65b 2051 }
2052 }
2053 return $teachers;
2054}
2055
2056
f374fb10 2057/**
fbc21ae8 2058 * Returns the user's group in a particular course
2059 *
2060 * @uses $CFG
2061 * @param int $courseid The course in question.
2062 * @param int $userid The id of the user as found in the 'user' table.
7290c7fa 2063 * @return object
fbc21ae8 2064 * @todo Finish documenting this function
2065 */
f374fb10 2066function user_group($courseid, $userid) {
2067 global $CFG;
2068
2069 return get_record_sql("SELECT g.*
0da33e07 2070 FROM {$CFG->prefix}groups g,
2071 {$CFG->prefix}groups_members m
f374fb10 2072 WHERE g.courseid = '$courseid'
2073 AND g.id = m.groupid
2074 AND m.userid = '$userid'");
2075}
2076
2077
9fa49e22 2078
02ebf404 2079
2080/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
2081
2082
18a97fd8 2083/**
fbc21ae8 2084 * Returns $course object of the top-level site.
2085 *
89dcb99d 2086 * @return course A {@link $COURSE} object for the site
2087 * @todo Finish documenting this function.
fbc21ae8 2088 */
c44d5d42 2089function get_site() {
2090
2091 global $SITE;
2092
2093 if (!empty($SITE->id)) { // We already have a global to use, so return that
2094 return $SITE;
2095 }
02ebf404 2096
c44d5d42 2097 if ($course = get_record('course', 'category', 0)) {
02ebf404 2098 return $course;
2099 } else {
2100 return false;
2101 }
2102}
2103
18a97fd8 2104/**
6315b1c8 2105* Returns list of courses, for whole site, or category
2106*
2107* Returns list of courses, for whole site, or category
2108*
2109* @param type description
2110*
2111* Important: Using c.* for fields is extremely expensive because
2112* we are using distinct. You almost _NEVER_ need all the fields
2113* in such a large SELECT
2114*/
2115function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 2116
8ef9cb56 2117 global $USER, $CFG;
6315b1c8 2118
2119 $categoryselect = "";
2120 if ($categoryid != "all" && is_numeric($categoryid)) {
2121 $categoryselect = "c.category = '$categoryid'";
2122 }
2123
2124 $teachertable = "";
2125 $visiblecourses = "";
2126 $sqland = "";
2127 if (!empty($categoryselect)) {
2128 $sqland = "AND ";
2129 }
2130 if (!empty($USER->id)) { // May need to check they are a teacher
2131 if (!iscreator()) {
2132 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
2133 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
2134 }
2135 } else {
2136 $visiblecourses = "$sqland c.visible > 0";
8ef9cb56 2137 }
2138
6315b1c8 2139 if ($categoryselect or $visiblecourses) {
2140 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
14f32609 2141 } else {
6315b1c8 2142 $selectsql = "{$CFG->prefix}course c $teachertable";
14f32609 2143 }
2144
5b66416f 2145 $extrafield = str_replace('ASC','',$sort);
2146 $extrafield = str_replace('DESC','',$extrafield);
2147 $extrafield = trim($extrafield);
2148 if (!empty($extrafield)) {
2149 $extrafield = ','.$extrafield;
2150 }
2151 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
8130b77b 2152}
2153
8130b77b 2154
6315b1c8 2155/**
2156* Returns list of courses, for whole site, or category
2157*
2158* Similar to get_courses, but allows paging
2159*
2160* @param type description
2161*
2162* Important: Using c.* for fields is extremely expensive because
2163* we are using distinct. You almost _NEVER_ need all the fields
2164* in such a large SELECT
2165*/
2166function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
2167 &$totalcount, $limitfrom="", $limitnum="") {
c7fe5c6f 2168
8130b77b 2169 global $USER, $CFG;
2170
6315b1c8 2171 $categoryselect = "";
b565bbdf 2172 if ($categoryid != "all" && is_numeric($categoryid)) {
6315b1c8 2173 $categoryselect = "c.category = '$categoryid'";
8130b77b 2174 }
2175
6315b1c8 2176 $teachertable = "";
2177 $visiblecourses = "";
2178 $sqland = "";
2179 if (!empty($categoryselect)) {
2180 $sqland = "AND ";
c7fe5c6f 2181 }
2d2da684 2182 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
6315b1c8 2183 if (!iscreator()) {
2184 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
2185 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
2186 }
8130b77b 2187 } else {
6315b1c8 2188 $visiblecourses = "$sqland c.visible > 0";
8130b77b 2189 }
2190
6315b1c8 2191 if ($limitfrom !== "") {
29daf3a0 2192 $limit = sql_paging_limit($limitfrom, $limitnum);
6315b1c8 2193 } else {
2194 $limit = "";
02ebf404 2195 }
8ef9cb56 2196
6315b1c8 2197 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
8ef9cb56 2198
6315b1c8 2199 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
8ef9cb56 2200
6315b1c8 2201 return get_records_sql("SELECT DISTINCT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
02ebf404 2202}
2203
2204
18a97fd8 2205/**
7290c7fa 2206 * List of courses that a user is a member of.
fbc21ae8 2207 *
2208 * @uses $CFG
7290c7fa 2209 * @param int $userid The user of interest
fbc21ae8 2210 * @param string $sort ?
7290c7fa 2211 * @return object {@link $COURSE} records
fbc21ae8 2212 */
d4419d55 2213function get_my_courses($userid, $sort='visible DESC,sortorder ASC') {
2f3499b7 2214
02ebf404 2215 global $CFG;
2216
2f3499b7 2217 $course = array();
2218
d4419d55 2219 if ($students = get_records('user_students', 'userid', $userid, '', 'id, course')) {
2f3499b7 2220 foreach ($students as $student) {
2221 $course[$student->course] = $student->course;
2222 }
2223 }
d4419d55 2224 if ($teachers = get_records('user_teachers', 'userid', $userid, '', 'id, course')) {
2f3499b7 2225 foreach ($teachers as $teacher) {
2226 $course[$teacher->course] = $teacher->course;
2227 }
2228 }
2229 if (empty($course)) {
2230 return $course;
2231 }
2232
2233 $courseids = implode(',', $course);
2234
d4419d55 2235 return get_records_list('course', 'id', $courseids, $sort);
2f3499b7 2236
2237// The following is correct but VERY slow with large datasets
2238//
8f0cd6ef 2239// return get_records_sql("SELECT c.*
2240// FROM {$CFG->prefix}course c,
2241// {$CFG->prefix}user_students s,
2242// {$CFG->prefix}user_teachers t
2f3499b7 2243// WHERE (s.userid = '$userid' AND s.course = c.id)
2244// OR (t.userid = '$userid' AND t.course = c.id)
8f0cd6ef 2245// GROUP BY c.id
2f3499b7 2246// ORDER BY $sort");
02ebf404 2247}
2248
2249
18a97fd8 2250/**
7290c7fa 2251 * A list of courses that match a search
fbc21ae8 2252 *
2253 * @uses $CFG
2254 * @param array $searchterms ?
2255 * @param string $sort ?
2256 * @param int $page ?
2257 * @param int $recordsperpage ?
2258 * @param int $totalcount Passed in by reference. ?
7290c7fa 2259 * @return object {@link $COURSE} records
fbc21ae8 2260 * @todo Finish documenting this function
2261 */
d4419d55 2262function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
02ebf404 2263
2264 global $CFG;
2265
29daf3a0 2266 $limit = sql_paging_limit($page, $recordsperpage);
02ebf404 2267
18a97fd8 2268 //to allow case-insensitive search for postgesql
d4419d55 2269 if ($CFG->dbtype == 'postgres7') {
2270 $LIKE = 'ILIKE';
2271 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
2272 $REGEXP = '~*';
2273 $NOTREGEXP = '!~*';
02ebf404 2274 } else {
d4419d55 2275 $LIKE = 'LIKE';
2276 $NOTLIKE = 'NOT LIKE';
2277 $REGEXP = 'REGEXP';
2278 $NOTREGEXP = 'NOT REGEXP';
02ebf404 2279 }
2280
d4419d55 2281 $fullnamesearch = '';
2282 $summarysearch = '';
02ebf404 2283
02ebf404 2284 foreach ($searchterms as $searchterm) {
2285 if ($fullnamesearch) {
d4419d55 2286 $fullnamesearch .= ' AND ';
02ebf404 2287 }
02ebf404 2288 if ($summarysearch) {
d4419d55 2289 $summarysearch .= ' AND ';
02ebf404 2290 }
a8b56716 2291
d4419d55 2292 if (substr($searchterm,0,1) == '+') {
a8b56716 2293 $searchterm = substr($searchterm,1);
2294 $summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2295 $fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2296 } else if (substr($searchterm,0,1) == "-") {
2297 $searchterm = substr($searchterm,1);
2298 $summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2299 $fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
2300 } else {
d4419d55 2301 $summarysearch .= ' summary '. $LIKE .'\'%'. $searchterm .'%\' ';
2302 $fullnamesearch .= ' fullname '. $LIKE .'\'%'. $searchterm .'%\' ';
a8b56716 2303 }
2304
02ebf404 2305 }
2306
d4419d55 2307 $selectsql = $CFG->prefix .'course WHERE ('. $fullnamesearch .' OR '. $summarysearch .') AND category > \'0\'';
a8b56716 2308
d4419d55 2309 $totalcount = count_records_sql('SELECT COUNT(*) FROM '. $selectsql);
02ebf404 2310
d4419d55 2311 $courses = get_records_sql('SELECT * FROM '. $selectsql .' ORDER BY '. $sort .' '. $limit);
02ebf404 2312
2313 if ($courses) { /// Remove unavailable courses from the list
2314 foreach ($courses as $key => $course) {
2315 if (!$course->visible) {
2316 if (!isteacher($course->id)) {
2317 unset($courses[$key]);
a8b56716 2318 $totalcount--;
02ebf404 2319 }
2320 }
2321 }
2322 }
2323
2324 return $courses;
2325}
2326
2327
18a97fd8 2328/**
fbc21ae8 2329 * Returns a sorted list of categories
2330 *
2331 * @param string $parent ?
2332 * @param string $sort ?
2333 * @return ?
2334 * @todo Finish documenting this function
2335 */
d4419d55 2336function get_categories($parent='none', $sort='sortorder ASC') {
02ebf404 2337
814748c9 2338 if ($parent === 'none') {
d4419d55 2339 $categories = get_records('course_categories', '', '', $sort);
02ebf404 2340 } else {
d4419d55 2341 $categories = get_records('course_categories', 'parent', $parent, $sort);
02ebf404 2342 }
2343 if ($categories) { /// Remove unavailable categories from the list
3af6e1db 2344 $creator = iscreator();
02ebf404 2345 foreach ($categories as $key => $category) {
2346 if (!$category->visible) {
3af6e1db 2347 if (!$creator) {
02ebf404 2348 unset($categories[$key]);
2349 }
2350 }
2351 }
2352 }
2353 return $categories;
2354}
2355
2356
18a97fd8 2357/**
ba87a4da 2358* This recursive function makes sure that the courseorder is consecutive
2359*
2360* @param type description
2361*
2362* $n is the starting point, offered only for compatilibity -- will be ignored!
2363* $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
2364* safely from 1.4 to 1.5
2365*/
f41ef63e 2366function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
2367
ba87a4da 2368 global $CFG;
8f0cd6ef 2369
02ebf404 2370 $count = 0;
ba87a4da 2371
f41ef63e 2372 $catgap = 1000; // "standard" category gap
2373 $tolerance = 200; // how "close" categories can get
2374
2375 if ($categoryid > 0){
2376 // update depth and path
2377 $cat = get_record('course_categories', 'id', $categoryid);
2378 if ($cat->parent == 0) {
2379 $depth = 0;
2380 $path = '';
2381 } else if ($depth == 0 ) { // doesn't make sense; get from DB
2382 // this is only called if the $depth parameter looks dodgy
2383 $parent = get_record('course_categories', 'id', $cat->parent);
2384 $path = $parent->path;
2385 $depth = $parent->depth;
2386 }
2387 $path = $path . '/' . $categoryid;
2388 $depth = $depth + 1;
ba87a4da 2389
f41ef63e 2390 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
2391 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
2392 }
39f65595 2393
2394 // get some basic info about courses in the category
ba87a4da 2395 $info = get_record_sql('SELECT MIN(sortorder) AS min,
2396 MAX(sortorder) AS max,
f41ef63e 2397 COUNT(sortorder) AS count
ba87a4da 2398 FROM ' . $CFG->prefix . 'course
2399 WHERE category=' . $categoryid);
2400 if (is_object($info)) { // no courses?
2401 $max = $info->max;
2402 $count = $info->count;
2403 $min = $info->min;
2404 unset($info);
2405 }
2406
814748c9 2407 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
2408 $n = $min;
2409 }
2410
39f65595 2411 // $hasgap flag indicates whether there's a gap in the sequence
2412 $hasgap = false;
2413 if ($max-$min+1 != $count) {
2414 $hasgap = true;
2415 }
2416
2417 // $mustshift indicates whether the sequence must be shifted to
2418 // meet its range
2419 $mustshift = false;
2420 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
2421 $mustshift = true;
2422 }
2423
ba87a4da 2424 // actually sort only if there are courses,
2425 // and we meet one ofthe triggers:
2426 // - safe flag
2427 // - they are not in a continuos block
2428 // - they are too close to the 'bottom'
39f65595 2429 if ($count && ( $safe || $hasgap || $mustshift ) ) {
2430 // special, optimized case where all we need is to shift
2431 if ( $mustshift && !$safe && !$hasgap) {
2432 $shift = $n + $catgap - $min;
2433 // UPDATE course SET sortorder=sortorder+$shift
2434 execute_sql("UPDATE {$CFG->prefix}course
2435 SET sortorder=sortorder+$shift
2436 WHERE category=$categoryid", 0);
2437 $n = $n + $catgap + $count;
2438
2439 } else { // do it slowly
2440 $n = $n + $catgap;
2441 // if the new sequence overlaps the current sequence, lack of transactions
2442 // will stop us -- shift things aside for a moment...
94afadb3 2443 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbtype==='mysql')) {
d6a49dab 2444 $shift = $max + $n + 1000;
39f65595 2445 execute_sql("UPDATE {$CFG->prefix}course
2446 SET sortorder=sortorder+$shift
2447 WHERE category=$categoryid", 0);
ba87a4da 2448 }
2449
39f65595 2450 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
2451 begin_sql();
ba87a4da 2452 foreach ($courses as $course) {
2453 if ($course->sortorder != $n ) { // save db traffic
2454 set_field('course', 'sortorder', $n, 'id', $course->id);
2455 }
2456 $n++;
2457 }
2458 commit_sql();
2459 }
02ebf404 2460 }
d4419d55 2461 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
8f0cd6ef 2462
814748c9 2463 // $n could need updating
2464 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
2465 if ($max > $n) {
2466 $n = $max;
2467 }
758b9a4d 2468
6bc502cc 2469 if ($categories = get_categories($categoryid)) {
2470 foreach ($categories as $category) {
f41ef63e 2471 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
6bc502cc 2472 }
2473 }
8f0cd6ef 2474
39f65595 2475 return $n+1;
02ebf404 2476}
2477
fbc21ae8 2478
18a97fd8 2479/**
fbc21ae8 2480 * This function creates a default separated/connected scale
2481 *
2482 * This function creates a default separated/connected scale
2483 * so there's something in the database. The locations of
2484 * strings and files is a bit odd, but this is because we
2485 * need to maintain backward compatibility with many different
2486 * existing language translations and older sites.
2487 *
2488 * @uses $CFG
2489 */
02ebf404 2490function make_default_scale() {
02ebf404 2491
2492 global $CFG;
2493
2494 $defaultscale = NULL;
2495 $defaultscale->courseid = 0;
2496 $defaultscale->userid = 0;
d4419d55 2497 $defaultscale->name = get_string('separateandconnected');
2498 $defaultscale->scale = get_string('postrating1', 'forum').','.
2499 get_string('postrating2', 'forum').','.
2500 get_string('postrating3', 'forum');
02ebf404 2501 $defaultscale->timemodified = time();
2502
8f0cd6ef 2503 /// Read in the big description from the file. Note this is not
02ebf404 2504 /// HTML (despite the file extension) but Moodle format text.
d4419d55 2505 $parentlang = get_string('parentlang');
2506 if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
2507 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
2508 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
2509 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
2510 } else if (is_readable($CFG->dirroot .'/lang/en/help/forum/ratings.html')) {
2511 $file = file($CFG->dirroot .'/lang/en/help/forum/ratings.html');
02ebf404 2512 } else {
d4419d55 2513 $file = '';
02ebf404 2514 }
2515
d4419d55 2516 $defaultscale->description = addslashes(implode('', $file));
02ebf404 2517
d4419d55 2518 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
2519 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
02ebf404 2520 }
2521}
2522
fbc21ae8 2523
18a97fd8 2524/**
fbc21ae8 2525 * Returns a menu of all available scales from the site as well as the given course
2526 *
2527 * @uses $CFG
2528 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 2529 * @return object
fbc21ae8 2530 */
02ebf404 2531function get_scales_menu($courseid=0) {
02ebf404 2532
2533 global $CFG;
8f0cd6ef 2534
2535 $sql = "SELECT id, name FROM {$CFG->prefix}scale
2536 WHERE courseid = '0' or courseid = '$courseid'
02ebf404 2537 ORDER BY courseid ASC, name ASC";
2538
d4419d55 2539 if ($scales = get_records_sql_menu($sql)) {
02ebf404 2540 return $scales;
2541 }
2542
2543 make_default_scale();
2544
d4419d55 2545 return get_records_sql_menu($sql);
02ebf404 2546}
2547
5baa0ad6 2548
2549
2550/**
2551 * Given a set of timezone records, put them in the database, replacing what is there
2552 *
2553 * @uses $CFG
2554 * @param array $timezones An array of timezone records
2555 */
2556function update_timezone_records($timezones) {
2557/// Given a set of timezone records, put them in the database
2558
2559 global $CFG;
2560
2561/// Clear out all the old stuff
2562 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
2563
2564/// Insert all the new stuff
2565 foreach ($timezones as $timezone) {
2566 insert_record('timezone', $timezone);
2567 }
2568}
2569
2570
df28d6c5 2571/// MODULE FUNCTIONS /////////////////////////////////////////////////
2572
18a97fd8 2573/**
fbc21ae8 2574 * Just gets a raw list of all modules in a course
2575 *
2576 * @uses $CFG
2577 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 2578 * @return object
fbc21ae8 2579 * @todo Finish documenting this function
2580 */
9fa49e22 2581function get_course_mods($courseid) {
9fa49e22 2582 global $CFG;
2583
7acaa63d 2584 return get_records_sql("SELECT cm.*, m.name as modname
8f0cd6ef 2585 FROM {$CFG->prefix}modules m,
7acaa63d 2586 {$CFG->prefix}course_modules cm
8f0cd6ef 2587 WHERE cm.course = '$courseid'
9fa49e22 2588 AND cm.module = m.id ");
2589}
2590
fbc21ae8 2591
18a97fd8 2592/**
fbc21ae8 2593 * Given an instance of a module, finds the coursemodule description
2594 *
2595 * @uses $CFG
2596 * @param string $modulename ?
2597 * @param string $instance ?
2598 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 2599 * @return object
fbc21ae8 2600 * @todo Finish documenting this function
2601 */
b63c0ee5 2602function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
df28d6c5 2603
2604 global $CFG;
b63c0ee5 2605
2606 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
df28d6c5 2607
2608 return get_record_sql("SELECT cm.*, m.name
8f0cd6ef 2609 FROM {$CFG->prefix}course_modules cm,
2610 {$CFG->prefix}modules md,
2611 {$CFG->prefix}$modulename m
b63c0ee5 2612 WHERE $courseselect
8f0cd6ef 2613 cm.instance = m.id AND
2614 md.name = '$modulename' AND
df28d6c5 2615 md.id = cm.module AND
2616 m.id = '$instance'");
2617
2618}
2619
fbc21ae8 2620
18a97fd8 2621/**
fbc21ae8 2622 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
2623 *
2624 * Returns an array of all the active instances of a particular
2625 * module in a given course, sorted in the order they are defined
2626 * in the course. Returns false on any errors.
2627 *
2628 * @uses $CFG
2629 * @param string $modulename The name of the module to get instances for
2630 * @param object(course) $course This depends on an accurate $course->modinfo
2631 * @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?
2632 */
cccb016a 2633function get_all_instances_in_course($modulename, $course) {
df28d6c5 2634
2635 global $CFG;
2636
cccb016a 2637 if (!$modinfo = unserialize($course->modinfo)) {
2638 return array();
1acfbce5 2639 }
2640
404afe6b 2641 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode
8f0cd6ef 2642 FROM {$CFG->prefix}course_modules cm,
2643 {$CFG->prefix}course_sections cw,
2644 {$CFG->prefix}modules md,
2645 {$CFG->prefix}$modulename m
2646 WHERE cm.course = '$course->id' AND
2647 cm.instance = m.id AND
8f0cd6ef 2648 cm.section = cw.id AND
2649 md.name = '$modulename' AND
cccb016a 2650 md.id = cm.module")) {
2651 return array();
2652 }
2653
2654 // Hide non-visible instances from students
2655 if (isteacher($course->id)) {
2656 $invisible = -1;
2657 } else {
2658 $invisible = 0;
2659 }
2660
2661 foreach ($modinfo as $mod) {
2662 if ($mod->mod == $modulename and $mod->visible > $invisible) {
7f12f9cd 2663 $instance = $rawmods[$mod->cm];
2664 if (!empty($mod->extra)) {
2665 $instance->extra = $mod->extra;
2666 }
2667 $outputarray[] = $instance;
cccb016a 2668 }
2669 }
2670
2671 return $outputarray;
df28d6c5 2672
2673}
2674
9fa49e22 2675
18a97fd8 2676/**
fbc21ae8 2677 * Determine whether a module instance is visible within a course
2678 *
2679 * Given a valid module object with info about the id and course,
2680 * and the module's type (eg "forum") returns whether the object
2681 * is visible or not
2682 *
2683 * @uses $CFG
2684 * @param $moduletype ?
2685 * @param $module ?
7290c7fa 2686 * @return bool
fbc21ae8 2687 * @todo Finish documenting this function
2688 */
580f2fbc 2689function instance_is_visible($moduletype, $module) {
580f2fbc 2690
2691 global $CFG;
2692
2b49ae96 2693 if (!empty($module->id)) {
2694 if ($records = get_records_sql("SELECT cm.instance, cm.visible
2695 FROM {$CFG->prefix}course_modules cm,
2696 {$CFG->prefix}modules m
2697 WHERE cm.course = '$module->course' AND
2698 cm.module = m.id AND
2699 m.name = '$moduletype' AND
2700 cm.instance = '$module->id'")) {
2701
2702 foreach ($records as $record) { // there should only be one - use the first one
2703 return $record->visible;
2704 }
580f2fbc 2705 }
2706 }
580f2fbc 2707 return true; // visible by default!
2708}
2709
a3fb1c45 2710
2711
2712
9fa49e22 2713/// LOG FUNCTIONS /////////////////////////////////////////////////////
2714
2715
18a97fd8 2716/**
fbc21ae8 2717 * Add an entry to the log table.
2718 *
2719 * Add an entry to the log table. These are "action" focussed rather
2720 * than web server hits, and provide a way to easily reconstruct what
2721 * any particular student has been doing.
2722 *
2723 * @uses $CFG
2724 * @uses $USER
2725 * @uses $db
2726 * @uses $REMOTE_ADDR
2727 * @uses SITEID
89dcb99d 2728 * @param int $courseid The course id
fbc21ae8 2729 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
2730 * @param string $action View, edit, post (often but not always the same as the file.php)
2731 * @param string $url The file and parameters used to see the results of the action
2732 * @param string $info Additional description information
2733 * @param string $cm The course_module->id if there is one
2734 * @param string $user If log regards $user other than $USER
2735 */
d4419d55 2736function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
9fa49e22 2737
fcaff7ff 2738 global $db, $CFG, $USER;
9fa49e22 2739
7a5b1fc5 2740 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 2741 $cm = 0;
2742 }
2743
3d94772d 2744 if ($user) {
2745 $userid = $user;
2746 } else {
2747 if (isset($USER->realuser)) { // Don't log
2748 return;
2749 }
d4419d55 2750 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 2751 }
2752
fcaff7ff 2753 $REMOTE_ADDR = getremoteaddr();
2754
9fa49e22 2755 $timenow = time();
2756 $info = addslashes($info);
10a760b9 2757 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
2758 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
2759 }
853df85e 2760
2761 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
2762
d4419d55 2763 $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
2764 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
ebc3bd2b 2765
ce78926d 2766 if (!$result and ($CFG->debug > 7)) {
d4419d55 2767 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
8f0cd6ef 2768 }
f78b3c34 2769 if ( isset($USER) && (empty($user) || $user==$USER->id) ) {
114176a2 2770 $db->Execute('UPDATE '. $CFG->prefix .'user SET lastIP=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
c2aa460f 2771 WHERE id = \''. $userid .'\' ');
e3a23213 2772 if ($courseid != SITEID && !empty($courseid)) { // logins etc dont't have a courseid and isteacher will break without it.
853df85e 2773 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
114176a2 2774 if (isstudent($courseid)) {
2775 $db->Execute('UPDATE '. $CFG->prefix .'user_students SET timeaccess = \''. $timenow .'\' '.
2776 'WHERE course = \''. $courseid .'\' AND userid = \''. $userid .'\'');
2777 } else if (isteacher($courseid, false, false)) {
2778 $db->Execute('UPDATE '. $CFG->prefix .'user_teachers SET timeaccess = \''. $timenow .'\' '.
2779 'WHERE course = \''. $courseid .'\' AND userid = \''. $userid .'\'');
2780 }
3d94772d 2781 }
8f0cd6ef 2782 }
9fa49e22 2783}
2784
2785
18a97fd8 2786/**
fbc21ae8 2787 * Select all log records based on SQL criteria
2788 *
2789 * @uses $CFG
2790 * @param string $select SQL select criteria
2791 * @param string $order SQL order by clause to sort the records returned
2792 * @param string $limitfrom ?
2793 * @param int $limitnum ?
2794 * @param int $totalcount Passed in by reference.
7290c7fa 2795 * @return object
fbc21ae8 2796 * @todo Finish documenting this function
2797 */
d4419d55 2798function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
9fa49e22 2799 global $CFG;
2800
d4419d55 2801 if ($limitfrom !== '') {
29daf3a0 2802 $limit = sql_paging_limit($limitfrom, $limitnum);
519d369f 2803 } else {
d4419d55 2804 $limit = '';
519d369f 2805 }
2806
2807 if ($order) {
d4419d55 2808 $order = 'ORDER BY '. $order;
519d369f 2809 }
2810
fbc21ae8 2811 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
a2ddd957 2812 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
2813
2814 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
519d369f 2815
d4419d55 2816 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
2817 FROM '. $selectsql .' '. $order .' '. $limit);
9fa49e22 2818}
2819
519d369f 2820
18a97fd8 2821/**
fbc21ae8 2822 * Select all log records for a given course and user
2823 *
2824 * @uses $CFG
2f87145b 2825 * @uses DAYSECS
fbc21ae8 2826 * @param int $userid The id of the user as found in the 'user' table.
2827 * @param int $courseid The id of the course as found in the 'course' table.
2828 * @param string $coursestart ?
2829 * @todo Finish documenting this function
2830 */
9fa49e22 2831function get_logs_usercourse($userid, $courseid, $coursestart) {
2832 global $CFG;
2833
da0c90c3 2834 if ($courseid) {
d4419d55 2835 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 2836 } else {
2837 $courseselect = '';
da0c90c3 2838 }
2839
1604a0fc 2840 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
8f0cd6ef 2841 FROM {$CFG->prefix}log
2842 WHERE userid = '$userid'
1604a0fc 2843 AND time > '$coursestart' $courseselect
9fa49e22 2844 GROUP BY day ");
2845}
2846
18a97fd8 2847/**
fbc21ae8 2848 * Select all log records for a given course, user, and day
2849 *
2850 * @uses $CFG
2f87145b 2851 * @uses HOURSECS
fbc21ae8 2852 * @param int $userid The id of the user as found in the 'user' table.
2853 * @param int $courseid The id of the course as found in the 'course' table.
2854 * @param string $daystart ?
7290c7fa 2855 * @return object
fbc21ae8 2856 * @todo Finish documenting this function
2857 */
9fa49e22 2858function get_logs_userday($userid, $courseid, $daystart) {
2859 global $CFG;
2860
7e4a6488 2861 if ($courseid) {
d4419d55 2862 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 2863 } else {
2864 $courseselect = '';
7e4a6488 2865 }
2866
1604a0fc 2867 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
9fa49e22 2868 FROM {$CFG->prefix}log
8f0cd6ef 2869 WHERE userid = '$userid'
1604a0fc 2870 AND time > '$daystart' $courseselect
9fa49e22 2871 GROUP BY hour ");
2872}
2873
b4bac9b6 2874/**
2875 * Returns an object with counts of failed login attempts
2876 *
8f0cd6ef 2877 * Returns information about failed login attempts. If the current user is
2878 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 2879 * number of accounts. For non-admins, only the attempts on the given user
2880 * are shown.
2881 *
fbc21ae8 2882 * @param string $mode Either 'admin', 'teacher' or 'everybody'
2883 * @param string $username The username we are searching for
2884 * @param string $lastlogin The date from which we are searching
2885 * @return int
b4bac9b6 2886 */
b4bac9b6 2887function count_login_failures($mode, $username, $lastlogin) {
2888
d4419d55 2889 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
b4bac9b6 2890
2891 if (isadmin()) { // Return information about all accounts
2892 if ($count->attempts = count_records_select('log', $select)) {
2893 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
2894 return $count;
2895 }
9407d456 2896 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
d4419d55 2897 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
b4bac9b6 2898 return $count;
2899 }
2900 }
2901 return NULL;
2902}
2903
2904
a3fb1c45 2905/// GENERAL HELPFUL THINGS ///////////////////////////////////
2906
18a97fd8 2907/**
fbc21ae8 2908 * Dump a given object's information in a PRE block.
2909 *
2910 * Mostly just used for debugging.
2911 *
2912 * @param mixed $object The data to be printed
2913 * @todo add example usage and example output
2914 */
a3fb1c45 2915function print_object($object) {
a3fb1c45 2916
d4419d55 2917 echo '<pre>';
2b051f1c 2918 print_r($object);
d4419d55 2919 echo '</pre>';
a3fb1c45 2920}
2921
29daf3a0 2922/**
2923 * Returns the proper SQL to do paging
2924 *
7290c7fa 2925 * @uses $CFG
2926 * @param string $page Offset page number
2927 * @param string $recordsperpage Number of records per page
2928 * @return string
29daf3a0 2929 */
2930function sql_paging_limit($page, $recordsperpage) {
2931 global $CFG;
2932
2933 switch ($CFG->dbtype) {
2934 case 'postgres7':
2935 return 'LIMIT '. $recordsperpage .' OFFSET '. $page;
2936 default:
2937 return 'LIMIT '. $page .','. $recordsperpage;
2938 }
2939}
2940
2941/**
2942 * Returns the proper SQL to do LIKE in a case-insensitive way
2943 *
7290c7fa 2944 * @uses $CFG
2945 * @return string
29daf3a0 2946 */
2947function sql_ilike() {
2948 global $CFG;
a3fb1c45 2949
29daf3a0 2950 switch ($CFG->dbtype) {
2951 case 'mysql':
2952 return 'LIKE';
2953 default:
2954 return 'ILIKE';
2955 }
2956}
2957
2958
2959/**
2960 * Returns the proper SQL to do LIKE in a case-insensitive way
2961 *
7290c7fa 2962 * @uses $CFG
2963 * @param string $firstname User's first name
2964 * @param string $lastname User's last name
2965 * @return string
29daf3a0 2966 */
7290c7fa 2967function sql_fullname($firstname='firstname', $lastname='lastname') {
29daf3a0 2968 global $CFG;
2969
2970 switch ($CFG->dbtype) {
2971 case 'mysql':
7290c7fa 2972 return ' CONCAT('. $firstname .'," ",'. $lastname .') ';
29daf3a0 2973 case 'postgres7':
7290c7fa 2974 return " ". $firstname ."||' '||". $lastname ." ";
29daf3a0 2975 default:
7290c7fa 2976 return ' '. $firstname .'||" "||'. $lastname .' ';
29daf3a0 2977 }
2978}
9fa49e22 2979
a0413b58 2980/**
2981 * Returns the proper SQL to do IS NULL
7290c7fa 2982 * @uses $CFG
2983 * @param string $fieldname The field to add IS NULL to
2984 * @return string
a0413b58 2985 */
2986function sql_isnull($fieldname) {
2987 global $CFG;
2988
2989 switch ($CFG->dbtype) {
2990 case 'mysql':
2991 return $fieldname.' IS NULL';
2992 default:
2993 return $fieldname.' IS NULL';
2994 }
2995}
2996
3ec22e35 2997/**
2998 * Checks for pg or mysql > 4
2999 */
3000
3001function check_db_compat() {
3002 global $CFG,$db;
3003
3004 if ($CFG->dbtype == 'postgres7') {
3005 return true;
3006 }
3007
3008 if (!$rs = $db->Execute("SELECT version();")) {
3009 return false;
3010 }
3011
3012 if (intval($rs->fields[0]) <= 3) {
3013 return false;
3014 }
3015
3016 return true;
3017}
3018
9d5b689c 3019// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f6f319f8 3020?>