Issues (1027)

Sources/Subs-Db-postgresql.php (4 issues)

1
<?php
2
3
/**
4
 * This file has all the main functions in it that relate to the database.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines http://www.simplemachines.org
10
 * @copyright 2019 Simple Machines and individual contributors
11
 * @license http://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 RC2
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Maps the implementations in this file (smf_db_function_name)
21
 * to the $smcFunc['db_function_name'] variable.
22
 *
23
 * @see Subs-Db-mysql.php#smf_db_initiate
24
 *
25
 * @param string $db_server The database server
26
 * @param string $db_name The name of the database
27
 * @param string $db_user The database username
28
 * @param string $db_passwd The database password
29
 * @param string $db_prefix The table prefix
30
 * @param array $db_options An array of database options
31
 * @return null|resource Returns null on failure if $db_options['non_fatal'] is true or a PostgreSQL connection resource handle if the connection was successful.
32
 */
33
function smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, &$db_prefix, $db_options = array())
34
{
35
	global $smcFunc;
36
37
	// Map some database specific functions, only do this once.
38
	if (!isset($smcFunc['db_fetch_assoc']))
39
		$smcFunc += array(
40
			'db_query'                  => 'smf_db_query',
41
			'db_quote'                  => 'smf_db_quote',
42
			'db_insert'                 => 'smf_db_insert',
43
			'db_insert_id'              => 'smf_db_insert_id',
44
			'db_fetch_assoc'            => 'pg_fetch_assoc',
45
			'db_fetch_row'              => 'pg_fetch_row',
46
			'db_free_result'            => 'pg_free_result',
47
			'db_num_rows'               => 'pg_num_rows',
48
			'db_data_seek'              => 'pg_result_seek',
49
			'db_num_fields'             => 'pg_num_fields',
50
			'db_escape_string'          => 'smf_db_escape_string',
51
			'db_unescape_string'        => 'stripslashes',
52
			'db_server_info'            => 'smf_db_version',
53
			'db_affected_rows'          => 'smf_db_affected_rows',
54
			'db_transaction'            => 'smf_db_transaction',
55
			'db_error'                  => 'pg_last_error',
56
			'db_select_db'              => 'smf_db_select_db',
57
			'db_title'                  => 'PostgreSQL',
58
			'db_sybase'                 => true,
59
			'db_case_sensitive'         => true,
60
			'db_escape_wildcard_string' => 'smf_db_escape_wildcard_string',
61
			'db_is_resource'            => 'is_resource',
62
			'db_mb4'                    => true,
63
			'db_ping'                   => 'pg_ping',
64
			'db_fetch_all'              => 'smf_db_fetch_all',
65
			'db_error_insert'           => 'smf_db_error_insert',
66
			'db_custom_order'           => 'smf_db_custom_order',
67
			'db_native_replace'         => 'smf_db_native_replace',
68
			'db_cte_support'            => 'smf_db_cte_support',
69
		);
70
71
	// We are not going to make it very far without these.
72
	if (!function_exists('pg_pconnect'))
73
		display_db_error();
74
75
	// We need to escape ' and \
76
	$db_passwd = str_replace(array('\\','\''), array('\\\\','\\\''), $db_passwd);
77
78
	if (!empty($db_options['persist']))
79
		$connection = @pg_pconnect((empty($db_server) ? '' : 'host=' . $db_server . ' ') . 'dbname=' . $db_name . ' user=\'' . $db_user . '\' password=\'' . $db_passwd . '\'' . (empty($db_options['port']) ? '' : ' port=\'' . $db_options['port'] . '\''));
80
	else
81
		$connection = @pg_connect((empty($db_server) ? '' : 'host=' . $db_server . ' ') . 'dbname=' . $db_name . ' user=\'' . $db_user . '\' password=\'' . $db_passwd . '\'' . (empty($db_options['port']) ? '' : ' port=\'' . $db_options['port'] . '\''));
82
83
	// Something's wrong, show an error if its fatal (which we assume it is)
84
	if (!$connection)
85
	{
86
		if (!empty($db_options['non_fatal']))
87
		{
88
			return null;
89
		}
90
		else
91
		{
92
			display_db_error();
93
		}
94
	}
95
96
	if (!empty($db_options['db_mb4']))
97
		$smcFunc['db_mb4'] = (bool) $db_options['db_mb4'];
98
99
	return $connection;
100
}
101
102
/**
103
 * Extend the database functionality. It calls the respective file's init
104
 * to add the implementations in that file to $smcFunc array.
105
 *
106
 * @param string $type Indicates which additional file to load. ('extra', 'packages')
107
 */
108
function db_extend($type = 'extra')
109
{
110
	global $sourcedir, $db_type;
111
112
	require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php');
113
	$initFunc = 'db_' . $type . '_init';
114
	$initFunc();
115
}
116
117
/**
118
 * Fix the database prefix if necessary.
119
 * Does nothing on PostgreSQL
120
 *
121
 * @param string $db_prefix The database prefix
122
 * @param string $db_name The database name
123
 */
124
function db_fix_prefix(&$db_prefix, $db_name)
125
{
126
	return;
127
}
128
129
/**
130
 * Callback for preg_replace_callback on the query.
131
 * It allows to replace on the fly a few pre-defined strings, for convenience ('query_see_board', 'query_wanna_see_board', etc), with
132
 * their current values from $user_info.
133
 * In addition, it performs checks and sanitization on the values sent to the database.
134
 *
135
 * @param array $matches The matches from preg_replace_callback
136
 * @return string The appropriate string depending on $matches[1]
137
 */
138
function smf_db_replacement__callback($matches)
139
{
140
	global $db_callback, $user_info, $db_prefix, $smcFunc;
141
142
	list ($values, $connection) = $db_callback;
143
144
	if ($matches[1] === 'db_prefix')
145
		return $db_prefix;
146
147
	if (isset($user_info[$matches[1]]) && strpos($matches[1], 'query_') !== false)
148
		return $user_info[$matches[1]];
149
150
	if ($matches[1] === 'empty')
151
		return '\'\'';
152
153
	if (!isset($matches[2]))
154
		smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
155
156
	if ($matches[1] === 'literal')
157
		return '\'' . pg_escape_string($matches[2]) . '\'';
158
159
	if (!isset($values[$matches[2]]))
160
		smf_db_error_backtrace('The database value you\'re trying to insert does not exist: ' . (isset($smcFunc['htmlspecialchars']) ? $smcFunc['htmlspecialchars']($matches[2]) : htmlspecialchars($matches[2])), '', E_USER_ERROR, __FILE__, __LINE__);
161
162
	$replacement = $values[$matches[2]];
163
164
	switch ($matches[1])
165
	{
166
		case 'int':
167
			if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
168
				smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
169
			return (string) (int) $replacement;
170
			break;
171
172
		case 'string':
173
		case 'text':
174
			return sprintf('\'%1$s\'', pg_escape_string($replacement));
175
			break;
176
177
		case 'array_int':
178
			if (is_array($replacement))
179
			{
180
				if (empty($replacement))
181
					smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
182
183
				foreach ($replacement as $key => $value)
184
				{
185
					if (!is_numeric($value) || (string) $value !== (string) (int) $value)
186
						smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
187
188
					$replacement[$key] = (string) (int) $value;
189
				}
190
191
				return implode(', ', $replacement);
192
			}
193
			else
194
				smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
195
196
			break;
197
198
		case 'array_string':
199
			if (is_array($replacement))
200
			{
201
				if (empty($replacement))
202
					smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
203
204
				foreach ($replacement as $key => $value)
205
					$replacement[$key] = sprintf('\'%1$s\'', pg_escape_string($value));
206
207
				return implode(', ', $replacement);
208
			}
209
			else
210
				smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
211
			break;
212
213
		case 'date':
214
			if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
215
				return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]) . '::date';
216
			else
217
				smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
218
			break;
219
220
		case 'time':
221
			if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1)
222
				return sprintf('\'%02d:%02d:%02d\'', $time_matches[1], $time_matches[2], $time_matches[3]) . '::time';
223
			else
224
				smf_db_error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
225
			break;
226
227
		case 'datetime':
228
			if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d) ([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $datetime_matches) === 1)
229
				return 'to_timestamp(' .
230
					sprintf('\'%04d-%02d-%02d %02d:%02d:%02d\'', $datetime_matches[1], $datetime_matches[2], $datetime_matches[3], $datetime_matches[4], $datetime_matches[5], $datetime_matches[6]) .
231
					',\'YYYY-MM-DD HH24:MI:SS\')';
232
			else
233
				smf_db_error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
234
			break;
235
236
		case 'float':
237
			if (!is_numeric($replacement))
238
				smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
239
			return (string) (float) $replacement;
240
			break;
241
242
		case 'identifier':
243
			return '"' . strtr($replacement, array('`' => '', '.' => '"."')) . '"';
244
			break;
245
246
		case 'raw':
247
			return $replacement;
248
			break;
249
250
		case 'inet':
251
			if ($replacement == 'null' || $replacement == '')
252
				return 'null';
253
			if (inet_pton($replacement) === false)
254
				smf_db_error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
255
			return sprintf('\'%1$s\'::inet', pg_escape_string($replacement));
256
257
		case 'array_inet':
258
			if (is_array($replacement))
259
			{
260
				if (empty($replacement))
261
					smf_db_error_backtrace('Database error, given array of IPv4 or IPv6 values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
262
263
				foreach ($replacement as $key => $value)
264
				{
265
					if ($replacement == 'null' || $replacement == '')
266
						$replacement[$key] = 'null';
267
					if (!isValidIP($value))
268
						smf_db_error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
269
					$replacement[$key] = sprintf('\'%1$s\'::inet', pg_escape_string($value));
270
				}
271
272
				return implode(', ', $replacement);
273
			}
274
			else
275
				smf_db_error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
276
			break;
277
278
		default:
279
			smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
280
			break;
281
	}
282
}
283
284
/**
285
 * Just like the db_query, escape and quote a string, but not executing the query.
286
 *
287
 * @param string $db_string The database string
288
 * @param array $db_values An array of values to be injected into the string
289
 * @param resource $connection = null The connection to use (null to use $db_connection)
290
 * @return string The string with the values inserted
291
 */
292
function smf_db_quote($db_string, $db_values, $connection = null)
293
{
294
	global $db_callback, $db_connection;
295
296
	// Only bother if there's something to replace.
297
	if (strpos($db_string, '{') !== false)
298
	{
299
		// This is needed by the callback function.
300
		$db_callback = array($db_values, $connection === null ? $db_connection : $connection);
301
302
		// Do the quoting and escaping
303
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
304
305
		// Clear this global variable.
306
		$db_callback = array();
307
	}
308
309
	return $db_string;
310
}
311
312
/**
313
 * Do a query.  Takes care of errors too.
314
 * Special queries may need additional replacements to be appropriate
315
 * for PostgreSQL.
316
 *
317
 * @param string $identifier An identifier. Only used in Postgres when we need to do things differently...
318
 * @param string $db_string The database string
319
 * @param array $db_values = array() The values to be inserted into the string
320
 * @param resource $connection = null The connection to use (null to use $db_connection)
321
 * @return resource|bool Returns a MySQL result resource (for SELECT queries), true (for UPDATE queries) or false if the query failed
322
 */
323
function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
324
{
325
	global $db_cache, $db_count, $db_connection, $db_show_debug, $time_start;
326
	global $db_callback, $db_last_result, $db_replace_result, $modSettings;
327
328
	// Decide which connection to use.
329
	$connection = $connection === null ? $db_connection : $connection;
330
331
	// Special queries that need processing.
332
	$replacements = array(
333
		'consolidate_spider_stats' => array(
334
			'~MONTH\(log_time\), DAYOFMONTH\(log_time\)~' => 'MONTH(CAST(CAST(log_time AS abstime) AS timestamp)), DAYOFMONTH(CAST(CAST(log_time AS abstime) AS timestamp))',
335
		),
336
		'get_random_number' => array(
337
			'~RAND~' => 'RANDOM',
338
		),
339
		'insert_log_search_topics' => array(
340
			'~NOT RLIKE~' => '!~',
341
		),
342
		'insert_log_search_results_no_index' => array(
343
			'~NOT RLIKE~' => '!~',
344
		),
345
		'insert_log_search_results_subject' => array(
346
			'~NOT RLIKE~' => '!~',
347
		),
348
		'profile_board_stats' => array(
349
			'~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)',
350
		),
351
	);
352
353
	// Special optimizer Hints
354
	$query_opt = array(
355
		'load_board_info' => array(
356
			'join_collapse_limit' => 1,
357
		),
358
		'calendar_get_events' => array(
359
			'enable_seqscan' => 'off',
360
		),
361
	);
362
363
	if (isset($replacements[$identifier]))
364
		$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
365
366
	// Limits need to be a little different.
367
	$db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string);
368
369
	if (trim($db_string) == '')
370
		return false;
371
372
	// Comments that are allowed in a query are preg_removed.
373
	static $allowed_comments_from = array(
374
		'~\s+~s',
375
		'~/\*!40001 SQL_NO_CACHE \*/~',
376
		'~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
377
		'~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
378
	);
379
	static $allowed_comments_to = array(
380
		' ',
381
		'',
382
		'',
383
		'',
384
	);
385
386
	// One more query....
387
	$db_count = !isset($db_count) ? 1 : $db_count + 1;
388
	$db_replace_result = 0;
389
390
	if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
391
		smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
392
393
	if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
394
	{
395
		// Pass some values to the global space for use in the callback function.
396
		$db_callback = array($db_values, $connection);
397
398
		// Inject the values passed to this function.
399
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
400
401
		// This shouldn't be residing in global space any longer.
402
		$db_callback = array();
403
	}
404
405
	// First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
406
	if (empty($modSettings['disableQueryCheck']))
407
	{
408
		$clean = '';
409
		$old_pos = 0;
410
		$pos = -1;
411
		// Remove the string escape for better runtime
412
		$db_string_1 = str_replace('\'\'', '', $db_string);
413
		while (true)
414
		{
415
			$pos = strpos($db_string_1, '\'', $pos + 1);
416
			if ($pos === false)
417
				break;
418
			$clean .= substr($db_string_1, $old_pos, $pos - $old_pos);
419
420
			while (true)
421
			{
422
				$pos1 = strpos($db_string_1, '\'', $pos + 1);
423
				$pos2 = strpos($db_string_1, '\\', $pos + 1);
424
				if ($pos1 === false)
425
					break;
426
				elseif ($pos2 === false || $pos2 > $pos1)
427
				{
428
					$pos = $pos1;
429
					break;
430
				}
431
432
				$pos = $pos2 + 1;
433
			}
434
			$clean .= ' %s ';
435
436
			$old_pos = $pos + 1;
437
		}
438
		$clean .= substr($db_string_1, $old_pos);
439
		$clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
440
441
		// Comments?  We don't use comments in our queries, we leave 'em outside!
442
		if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
443
			$fail = true;
444
		// Trying to change passwords, slow us down, or something?
445
		elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
446
			$fail = true;
447
		elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
448
			$fail = true;
449
450
		if (!empty($fail) && function_exists('log_error'))
451
			smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
452
	}
453
454
	// Set optimize stuff
455
	if (isset($query_opt[$identifier]))
456
	{
457
		$query_hints = $query_opt[$identifier];
458
		$query_hints_set = '';
459
		if (isset($query_hints['join_collapse_limit']))
460
		{
461
			$query_hints_set .= 'SET LOCAL join_collapse_limit = ' . $query_hints['join_collapse_limit'] . ';';
462
		}
463
		if (isset($query_hints['enable_seqscan']))
464
		{
465
			$query_hints_set .= 'SET LOCAL enable_seqscan = ' . $query_hints['enable_seqscan'] . ';';
466
		}
467
468
		$db_string = $query_hints_set . $db_string;
469
	}
470
471
	// Debugging.
472
	if (isset($db_show_debug) && $db_show_debug === true)
473
	{
474
		// Get the file and line number this function was called.
475
		list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
476
477
		// Initialize $db_cache if not already initialized.
478
		if (!isset($db_cache))
479
			$db_cache = array();
480
481
		if (!empty($_SESSION['debug_redirect']))
482
		{
483
			$db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
484
			$db_count = count($db_cache) + 1;
485
			$_SESSION['debug_redirect'] = array();
486
		}
487
488
		// Don't overload it.
489
		$db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
490
		$db_cache[$db_count]['f'] = $file;
491
		$db_cache[$db_count]['l'] = $line;
492
		$db_cache[$db_count]['s'] = ($st = microtime(true)) - $time_start;
493
	}
494
495
	$db_last_result = @pg_query($connection, $db_string);
496
497
	if ($db_last_result === false && empty($db_values['db_error_skip']))
498
		$db_last_result = smf_db_error($db_string, $connection);
499
500
	// Debugging.
501
	if (isset($db_show_debug) && $db_show_debug === true)
502
		$db_cache[$db_count]['t'] = microtime(true) - $st;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $st does not seem to be defined for all execution paths leading up to this point.
Loading history...
503
504
	return $db_last_result;
505
}
506
507
/**
508
 * Returns the amount of affected rows for a query.
509
 *
510
 * @param mixed $result
511
 *
512
 * @return int
513
 *
514
 */
515
function smf_db_affected_rows($result = null)
516
{
517
	global $db_last_result, $db_replace_result;
518
519
	if ($db_replace_result)
520
		return $db_replace_result;
521
	elseif ($result === null && !$db_last_result)
522
		return 0;
523
524
	return pg_affected_rows($result === null ? $db_last_result : $result);
525
}
526
527
/**
528
 * Gets the ID of the most recently inserted row.
529
 *
530
 * @param string $table The table (only used for Postgres)
531
 * @param string $field = null The specific field (not used here)
532
 * @param resource $connection = null The connection (if null, $db_connection is used) (not used here)
533
 * @return int The ID of the most recently inserted row
534
 */
535
function smf_db_insert_id($table, $field = null, $connection = null)
536
{
537
	global $smcFunc, $db_prefix;
538
539
	$table = str_replace('{db_prefix}', $db_prefix, $table);
540
541
	// Try get the last ID for the auto increment field.
542
	$request = $smcFunc['db_query']('', 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
543
		array(
544
		)
545
	);
546
	if (!$request)
547
		return false;
548
	list ($lastID) = $smcFunc['db_fetch_row']($request);
549
	$smcFunc['db_free_result']($request);
550
551
	return $lastID;
552
}
553
554
/**
555
 * Do a transaction.
556
 *
557
 * @param string $type The step to perform (i.e. 'begin', 'commit', 'rollback')
558
 * @param resource $connection The connection to use (if null, $db_connection is used)
559
 * @return bool True if successful, false otherwise
560
 */
561
function smf_db_transaction($type = 'commit', $connection = null)
562
{
563
	global $db_connection;
564
565
	// Decide which connection to use
566
	$connection = $connection === null ? $db_connection : $connection;
567
568
	if ($type == 'begin')
569
		return @pg_query($connection, 'BEGIN');
570
	elseif ($type == 'rollback')
571
		return @pg_query($connection, 'ROLLBACK');
572
	elseif ($type == 'commit')
573
		return @pg_query($connection, 'COMMIT');
574
575
	return false;
576
}
577
578
/**
579
 * Database error!
580
 * Backtrace, log, try to fix.
581
 *
582
 * @param string $db_string The DB string
583
 * @param resource $connection The connection to use (if null, $db_connection is used)
584
 */
585
function smf_db_error($db_string, $connection = null)
586
{
587
	global $txt, $context, $modSettings;
588
	global $db_connection;
589
	global $db_show_debug;
590
591
	// We'll try recovering the file and line number the original db query was called from.
592
	list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
593
594
	// Decide which connection to use
595
	$connection = $connection === null ? $db_connection : $connection;
596
597
	// This is the error message...
598
	$query_error = @pg_last_error($connection);
599
600
	// Log the error.
601
	if (function_exists('log_error'))
602
		log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" . $db_string : ''), 'database', $file, $line);
603
604
	// Nothing's defined yet... just die with it.
605
	if (empty($context) || empty($txt))
606
		die($query_error);
607
608
	// Show an error message, if possible.
609
	$context['error_title'] = $txt['database_error'];
610
	if (allowedTo('admin_forum'))
611
		$context['error_message'] = nl2br($query_error) . '<br>' . $txt['file'] . ': ' . $file . '<br>' . $txt['line'] . ': ' . $line;
612
	else
613
		$context['error_message'] = $txt['try_again'];
614
615
	if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
616
	{
617
		$context['error_message'] .= '<br><br>' . nl2br($db_string);
618
	}
619
620
	// It's already been logged... don't log it again.
621
	fatal_error($context['error_message'], false);
622
}
623
624
/**
625
 * Inserts data into a table
626
 *
627
 * @param string $method The insert method - can be 'replace', 'ignore' or 'insert'
628
 * @param string $table The table we're inserting the data into
629
 * @param array $columns An array of the columns we're inserting the data into. Should contain 'column' => 'datatype' pairs
630
 * @param array $data The data to insert
631
 * @param array $keys The keys for the table, needs to be not empty on replace mode
632
 * @param int returnmode 0 = nothing(default), 1 = last row id, 2 = all rows id as array; every mode runs only with method != 'ignore'
0 ignored issues
show
The type returnmode was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
633
 * @param resource $connection The connection to use (if null, $db_connection is used)
634
 * @return mixed value of the first key, behavior based on returnmode. null if no data.
635
 */
636
function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $returnmode = 0, $connection = null)
637
{
638
	global $smcFunc, $db_connection, $db_prefix;
639
640
	$connection = $connection === null ? $db_connection : $connection;
641
642
	$replace = '';
643
644
	if (empty($data))
645
		return;
646
647
	if (!is_array($data[array_rand($data)]))
648
		$data = array($data);
649
650
	// Replace the prefix holder with the actual prefix.
651
	$table = str_replace('{db_prefix}', $db_prefix, $table);
652
653
	// Sanity check for replace is key part of the columns array
654
	if ($method == 'replace')
655
	{
656
		if (empty($keys))
657
			smf_db_error_backtrace('When using the replace mode, the key column is a required entry.',
658
				'Change the method of db insert to insert or add the pk field to the key array', E_USER_ERROR, __FILE__, __LINE__);
659
		if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys))
660
			smf_db_error_backtrace('Primary Key field missing in insert call',
661
				'Change the method of db insert to insert or add the pk field to the columns array', E_USER_ERROR, __FILE__, __LINE__);
662
	}			
663
664
	// PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead
665
	if ($method == 'replace' || $method == 'ignore')
666
	{
667
		$key_str = '';
668
		$col_str = '';
669
		$replace_support = $smcFunc['db_native_replace']();
670
671
		$count = 0;
672
		$where = '';
673
		$count_pk = 0;
674
675
		If ($replace_support)
676
		{
677
			foreach ($columns as $columnName => $type)
678
			{
679
				//check pk fiel
680
				IF (in_array($columnName, $keys))
681
				{
682
					$key_str .= ($count_pk > 0 ? ',' : '');
683
					$key_str .= $columnName;
684
					$count_pk++;
685
				}
686
				elseif ($method == 'replace') //normal field
687
				{
688
					$col_str .= ($count > 0 ? ',' : '');
689
					$col_str .= $columnName . ' = EXCLUDED.' . $columnName;
690
					$count++;
691
				}
692
			}
693
			if ($method == 'replace')
694
				$replace = ' ON CONFLICT (' . $key_str . ') DO UPDATE SET ' . $col_str;
695
			else
696
				$replace = ' ON CONFLICT (' . $key_str . ') DO NOTHING';
697
		}
698
		elseif ($method == 'replace')
699
		{
700
			foreach ($columns as $columnName => $type)
701
			{
702
				// Are we restricting the length?
703
				if (strpos($type, 'string-') !== false)
704
					$actualType = sprintf($columnName . ' = SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $count);
705
				else
706
					$actualType = sprintf($columnName . ' = {%1$s:%2$s}, ', $type, $count);
707
708
				// A key? That's what we were looking for.
709
				if (in_array($columnName, $keys))
710
					$where .= (empty($where) ? '' : ' AND ') . substr($actualType, 0, -2);
711
				$count++;
712
			}
713
714
			// Make it so.
715
			if (!empty($where) && !empty($data))
716
			{
717
				foreach ($data as $k => $entry)
718
				{
719
					$smcFunc['db_query']('', '
720
						DELETE FROM ' . $table .
721
						' WHERE ' . $where,
722
						$entry, $connection
723
					);
724
				}
725
			}
726
		}
727
	}
728
729
	$returning = '';
730
	$with_returning = false;
731
	// lets build the returning string, mysql allow only in normal mode
732
	if (!empty($keys) && (count($keys) > 0) && $returnmode > 0)
733
	{
734
		// we only take the first key
735
		$returning = ' RETURNING ' . $keys[0];
736
		$with_returning = true;
737
	}
738
739
	if (!empty($data))
740
	{
741
		// Create the mold for a single row insert.
742
		$insertData = '(';
743
		foreach ($columns as $columnName => $type)
744
		{
745
			// Are we restricting the length?
746
			if (strpos($type, 'string-') !== false)
747
				$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
748
			else
749
				$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
750
		}
751
		$insertData = substr($insertData, 0, -2) . ')';
752
753
		// Create an array consisting of only the columns.
754
		$indexed_columns = array_keys($columns);
755
756
		// Here's where the variables are injected to the query.
757
		$insertRows = array();
758
		foreach ($data as $dataRow)
759
			$insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
760
761
		// Do the insert.
762
		$request = $smcFunc['db_query']('', '
763
			INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '")
764
			VALUES
765
				' . implode(',
766
				', $insertRows) . $replace . $returning,
767
			array(
768
				'security_override' => true,
769
				'db_error_skip' => $method == 'ignore' || $table === $db_prefix . 'log_errors',
770
			),
771
			$connection
772
		);
773
774
		if ($with_returning && $request !== false)
775
		{
776
			if ($returnmode === 2)
777
				$return_var = array();
778
779
			while (($row = $smcFunc['db_fetch_row']($request)) && $with_returning)
780
			{
781
				if (is_numeric($row[0])) // try to emulate mysql limitation
782
				{
783
					if ($returnmode === 1)
784
						$return_var = $row[0];
785
					elseif ($returnmode === 2)
786
						$return_var[] = $row[0];
787
				}
788
				else
789
				{
790
					$with_returning = false;
791
					trigger_error('trying to returning ID Field which is not a Int field', E_USER_ERROR);
792
				}
793
			}
794
		}
795
	}
796
797
	if ($with_returning && !empty($return_var))
798
		return $return_var;
799
}
800
801
/**
802
 * Dummy function really. Doesn't do anything on PostgreSQL.
803
 *
804
 * @param string $db_name The database name
805
 * @param resource $db_connection The database connection
806
 * @return true Always returns true
807
 */
808
function smf_db_select_db($db_name, $db_connection)
809
{
810
	return true;
811
}
812
813
/**
814
 * Get the current version.
815
 *
816
 * @return string The client version
817
 */
818
function smf_db_version()
819
{
820
	$version = pg_version();
821
822
	return $version['client'];
823
}
824
825
/**
826
 * This function tries to work out additional error information from a back trace.
827
 *
828
 * @param string $error_message The error message
829
 * @param string $log_message The message to log
830
 * @param string|bool $error_type What type of error this is
831
 * @param string $file The file the error occurred in
832
 * @param int $line What line of $file the code which generated the error is on
833
 * @return void|array Returns an array with the file and line if $error_type is 'return'
834
 */
835
function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
836
{
837
	if (empty($log_message))
838
		$log_message = $error_message;
839
840
	foreach (debug_backtrace() as $step)
841
	{
842
		// Found it?
843
		if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), array('smf_db_', 'preg_re', 'db_erro', 'call_us')) && strpos($step['function'], '__') !== 0)
844
		{
845
			$log_message .= '<br>Function: ' . $step['function'];
846
			break;
847
		}
848
849
		if (isset($step['line']))
850
		{
851
			$file = $step['file'];
852
			$line = $step['line'];
853
		}
854
	}
855
856
	// A special case - we want the file and line numbers for debugging.
857
	if ($error_type == 'return')
858
		return array($file, $line);
859
860
	// Is always a critical error.
861
	if (function_exists('log_error'))
862
		log_error($log_message, 'critical', $file, $line);
863
864
	if (function_exists('fatal_error'))
865
	{
866
		fatal_error($error_message, $error_type);
867
868
		// Cannot continue...
869
		exit;
870
	}
871
	elseif ($error_type)
872
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
873
	else
874
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
875
}
876
877
/**
878
 * Escape the LIKE wildcards so that they match the character and not the wildcard.
879
 *
880
 * @param string $string The string to escape
881
 * @param bool $translate_human_wildcards If true, turns human readable wildcards into SQL wildcards.
882
 * @return string The escaped string
883
 */
884
function smf_db_escape_wildcard_string($string, $translate_human_wildcards = false)
885
{
886
	$replacements = array(
887
		'%' => '\%',
888
		'_' => '\_',
889
		'\\' => '\\\\',
890
	);
891
892
	if ($translate_human_wildcards)
893
		$replacements += array(
894
			'*' => '%',
895
		);
896
897
	return strtr($string, $replacements);
898
}
899
900
/**
901
 * Fetches all rows from a result as an array
902
 *
903
 * @param resource $request A PostgreSQL result resource
904
 * @return array An array that contains all rows (records) in the result resource
905
 */
906
function smf_db_fetch_all($request)
907
{
908
	// Return the right row.
909
	$return = @pg_fetch_all($request);
910
	return !empty($return) ? $return : array();
911
}
912
913
/**
914
 * Function to save errors in database in a safe way
915
 *
916
 * @param array with keys in this order id_member, log_time, ip, url, message, session, error_type, file, line
0 ignored issues
show
The type with was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
917
 * @return void
918
 */
919
function smf_db_error_insert($error_array)
920
{
921
	global $db_prefix, $db_connection;
922
	static $pg_error_data_prep;
923
924
	// without database we can't do anything
925
	if (empty($db_connection))
926
		return;
927
928
	if (empty($pg_error_data_prep))
929
		$pg_error_data_prep = pg_prepare($db_connection, 'smf_log_errors',
930
			'INSERT INTO ' . $db_prefix . 'log_errors
931
				(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
932
			VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
933
		);
934
935
	pg_execute($db_connection, 'smf_log_errors', $error_array);
936
}
937
938
/**
939
 * Function which constructs an optimize custom order string
940
 * as an improved alternative to find_in_set()
941
 *
942
 * @param string $field name
943
 * @param array $array_values Field values sequenced in array via order priority. Must cast to int.
944
 * @param boolean $desc default false
945
 * @return string case field when ... then ... end
946
 */
947
function smf_db_custom_order($field, $array_values, $desc = false)
948
{
949
	$return = 'CASE ' . $field . ' ';
950
	$count = count($array_values);
951
	$then = ($desc ? ' THEN -' : ' THEN ');
952
953
	for ($i = 0; $i < $count; $i++)
954
		$return .= 'WHEN ' . (int) $array_values[$i] . $then . $i . ' ';
955
956
	$return .= 'END';
957
	return $return;
958
}
959
960
/**
961
 * Function which return the information if the database supports native replace inserts
962
 *
963
 * @return boolean true or false
964
 */
965
function smf_db_native_replace()
966
{
967
	global $smcFunc;
968
	static $pg_version;
969
	static $replace_support;
970
971
	if (empty($pg_version))
972
	{
973
		db_extend();
974
		//pg 9.5 got replace support
975
		$pg_version = $smcFunc['db_get_version']();
976
		// if we got a Beta Version
977
		if (stripos($pg_version, 'beta') !== false)
978
			$pg_version = substr($pg_version, 0, stripos($pg_version, 'beta')) . '.0';
979
		// or RC
980
		if (stripos($pg_version, 'rc') !== false)
981
			$pg_version = substr($pg_version, 0, stripos($pg_version, 'rc')) . '.0';
982
983
		$replace_support = (version_compare($pg_version, '9.5.0', '>=') ? true : false);
984
	}
985
986
	return $replace_support;
987
}
988
989
/**
990
 * Function which return the information if the database supports cte with recursive
991
 *
992
 * @return boolean true or false
993
 */
994
function smf_db_cte_support()
995
{
996
	return true;
997
}
998
999
/**
1000
 * Function which return the escaped string
1001
 *
1002
 * @param string the unescaped text
0 ignored issues
show
The type the was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1003
 * @param resource $connection = null The connection to use (null to use $db_connection)
1004
 * @return string escaped string
1005
 */
1006
function smf_db_escape_string($string, $connection = null)
1007
{
1008
	global $db_connection;
1009
1010
	return pg_escape_string($connection === null ? $db_connection : $connection, $string);
1011
}
1012
1013
?>