Issues (1065)

Sources/Subs-Db-postgresql.php (1 issue)

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 https://www.simplemachines.org
10
 * @copyright 2025 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.5
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, $pg_connect_error, $pg_connect_errno;
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'                  => 'smf_db_errormsg',
56
			'db_select_db'              => 'smf_db_select_db',
57
			'db_title'                  => POSTGRE_TITLE,
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
			'db_connect_error'          => 'smf_db_connect_error',
70
			'db_connect_errno'          => 'smf_db_connect_errno',
71
		);
72
73
	// We are not going to make it very far without these.
74
	if (!function_exists('pg_pconnect'))
75
		display_db_error();
76
77
	// We need to escape ' and \
78
	$db_passwd = str_replace(array('\\','\''), array('\\\\','\\\''), $db_passwd);
79
80
	// Since pg_connect doesn't feed error info to pg_last_error, we have to catch issues with a try/catch.
81
	set_error_handler(
82
		function($errno, $errstr)
83
		{
84
			throw new ErrorException($errstr, $errno);
85
		}
86
	);
87
	try
88
	{
89
		if (!empty($db_options['persist']))
90
			$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'] . '\''));
91
		else
92
			$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'] . '\''));
93
	}
94
	catch (Exception $e)
95
	{
96
		// Make error info available to calling processes
97
		$pg_connect_error = $e->getMessage();
98
		$pg_connect_errno = $e->getCode();
99
		$connection = false;
100
	}
101
	restore_error_handler();
102
103
	// Something's wrong, show an error if its fatal (which we assume it is)
104
	if (!$connection)
105
	{
106
		if (!empty($db_options['non_fatal']))
107
		{
108
			return null;
109
		}
110
		else
111
		{
112
			display_db_error();
113
		}
114
	}
115
116
	if (!empty($db_options['db_mb4']))
117
		$smcFunc['db_mb4'] = (bool) $db_options['db_mb4'];
118
119
	return $connection;
120
}
121
122
/**
123
 * Extend the database functionality. It calls the respective file's init
124
 * to add the implementations in that file to $smcFunc array.
125
 *
126
 * @param string $type Indicates which additional file to load. ('extra', 'packages')
127
 */
128
function db_extend($type = 'extra')
129
{
130
	global $sourcedir, $db_type;
131
132
	require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php');
133
	$initFunc = 'db_' . $type . '_init';
134
	$initFunc();
135
}
136
137
/**
138
 * Fix the database prefix if necessary.
139
 * Does nothing on PostgreSQL
140
 *
141
 * @param string $db_prefix The database prefix
142
 * @param string $db_name The database name
143
 */
144
function db_fix_prefix(&$db_prefix, $db_name)
145
{
146
	return;
147
}
148
149
/**
150
 * Callback for preg_replace_callback on the query.
151
 * It allows to replace on the fly a few pre-defined strings, for convenience ('query_see_board', 'query_wanna_see_board', etc), with
152
 * their current values from $user_info.
153
 * In addition, it performs checks and sanitization on the values sent to the database.
154
 *
155
 * @param array $matches The matches from preg_replace_callback
156
 * @return string The appropriate string depending on $matches[1]
157
 */
158
function smf_db_replacement__callback($matches)
159
{
160
	global $db_callback, $user_info, $db_prefix, $smcFunc;
161
162
	list ($values, $connection) = $db_callback;
163
164
	if ($matches[1] === 'db_prefix')
165
		return $db_prefix;
166
167
	if (isset($user_info[$matches[1]]) && strpos($matches[1], 'query_') !== false)
168
		return $user_info[$matches[1]];
169
170
	if ($matches[1] === 'empty')
171
		return '\'\'';
172
173
	if (!isset($matches[2]))
174
		smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
175
176
	if ($matches[1] === 'literal')
177
		return '\'' . pg_escape_string($connection, $matches[2]) . '\'';
178
179
	if (!isset($values[$matches[2]]))
180
		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__);
181
182
	$replacement = $values[$matches[2]];
183
184
	switch ($matches[1])
185
	{
186
		case 'int':
187
			if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
188
				smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
189
			return (string) (int) $replacement;
190
			break;
191
192
		case 'string':
193
		case 'text':
194
			return sprintf('\'%1$s\'', pg_escape_string($connection, $replacement));
195
			break;
196
197
		case 'array_int':
198
			if (is_array($replacement))
199
			{
200
				if (empty($replacement))
201
					smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
202
203
				foreach ($replacement as $key => $value)
204
				{
205
					if (!is_numeric($value) || (string) $value !== (string) (int) $value)
206
						smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
207
208
					$replacement[$key] = (string) (int) $value;
209
				}
210
211
				return implode(', ', $replacement);
212
			}
213
			else
214
				smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
215
216
			break;
217
218
		case 'array_string':
219
			if (is_array($replacement))
220
			{
221
				if (empty($replacement))
222
					smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
223
224
				foreach ($replacement as $key => $value)
225
					$replacement[$key] = sprintf('\'%1$s\'', pg_escape_string($connection, $value));
226
227
				return implode(', ', $replacement);
228
			}
229
			else
230
				smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
231
			break;
232
233
		case 'date':
234
			if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
235
				return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]) . '::date';
236
			else
237
				smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
238
			break;
239
240
		case 'time':
241
			if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1)
242
				return sprintf('\'%02d:%02d:%02d\'', $time_matches[1], $time_matches[2], $time_matches[3]) . '::time';
243
			else
244
				smf_db_error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
245
			break;
246
247
		case 'datetime':
248
			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)
249
				return 'to_timestamp(' .
250
					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]) .
251
					',\'YYYY-MM-DD HH24:MI:SS\')';
252
			else
253
				smf_db_error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
254
			break;
255
256
		case 'float':
257
			if (!is_numeric($replacement))
258
				smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
259
			return (string) (float) $replacement;
260
			break;
261
262
		case 'identifier':
263
			return '"' . implode('"."', array_filter(explode('.', strtr($replacement, array('`' => ''))), 'strlen')) . '"';
264
			break;
265
266
		case 'raw':
267
			return $replacement;
268
			break;
269
270
		case 'inet':
271
			if ($replacement == 'null' || $replacement == '')
272
				return 'null';
273
			if (inet_pton($replacement) === false)
274
				smf_db_error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
275
			return sprintf('\'%1$s\'::inet', pg_escape_string($connection, $replacement));
276
277
		case 'array_inet':
278
			if (is_array($replacement))
279
			{
280
				if (empty($replacement))
281
					smf_db_error_backtrace('Database error, given array of IPv4 or IPv6 values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
282
283
				foreach ($replacement as $key => $value)
284
				{
285
					if ($replacement == 'null' || $replacement == '')
286
						$replacement[$key] = 'null';
287
					if (!isValidIP($value))
288
						smf_db_error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
289
					$replacement[$key] = sprintf('\'%1$s\'::inet', pg_escape_string($connection, $value));
290
				}
291
292
				return implode(', ', $replacement);
293
			}
294
			else
295
				smf_db_error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
296
			break;
297
298
		default:
299
			smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
300
			break;
301
	}
302
}
303
304
/**
305
 * Just like the db_query, escape and quote a string, but not executing the query.
306
 *
307
 * @param string $db_string The database string
308
 * @param array $db_values An array of values to be injected into the string
309
 * @param resource $connection = null The connection to use (null to use $db_connection)
310
 * @return string The string with the values inserted
311
 */
312
function smf_db_quote($db_string, $db_values, $connection = null)
313
{
314
	global $db_callback, $db_connection;
315
316
	// Only bother if there's something to replace.
317
	if (strpos($db_string, '{') !== false)
318
	{
319
		// This is needed by the callback function.
320
		$db_callback = array($db_values, $connection === null ? $db_connection : $connection);
321
322
		// Do the quoting and escaping
323
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
324
325
		// Clear this global variable.
326
		$db_callback = array();
327
	}
328
329
	return $db_string;
330
}
331
332
/**
333
 * Do a query.  Takes care of errors too.
334
 * Special queries may need additional replacements to be appropriate
335
 * for PostgreSQL.
336
 *
337
 * @param string $identifier An identifier. Only used in Postgres when we need to do things differently...
338
 * @param string $db_string The database string
339
 * @param array $db_values = array() The values to be inserted into the string
340
 * @param resource $connection = null The connection to use (null to use $db_connection)
341
 * @return resource|bool Returns a MySQL result resource (for SELECT queries), true (for UPDATE queries) or false if the query failed
342
 */
343
function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
344
{
345
	global $db_cache, $db_count, $db_connection, $db_show_debug;
346
	global $db_callback, $db_last_result, $db_replace_result, $modSettings;
347
348
	// Decide which connection to use.
349
	$connection = $connection === null ? $db_connection : $connection;
350
351
	// Special queries that need processing.
352
	$replacements = array(
353
		'profile_board_stats' => array(
354
			'~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)',
355
		),
356
	);
357
358
	// Special optimizer Hints
359
	$query_opt = array(
360
		'load_board_info' => array(
361
			'join_collapse_limit' => 1,
362
		),
363
		'calendar_get_events' => array(
364
			'enable_seqscan' => 'off',
365
		),
366
	);
367
368
	if (isset($replacements[$identifier]))
369
		$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
370
371
	// Limits need to be a little different.
372
	$db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string);
373
374
	if (trim($db_string) == '')
375
		return false;
376
377
	// Comments that are allowed in a query are preg_removed.
378
	static $allowed_comments_from = array(
379
		'~\s+~s',
380
		'~/\*!40001 SQL_NO_CACHE \*/~',
381
		'~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
382
		'~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
383
	);
384
	static $allowed_comments_to = array(
385
		' ',
386
		'',
387
		'',
388
		'',
389
	);
390
391
	// One more query....
392
	$db_count = !isset($db_count) ? 1 : $db_count + 1;
393
	$db_replace_result = 0;
394
395
	if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
396
		smf_db_error_backtrace('No direct access...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
397
398
	if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
399
	{
400
		// Pass some values to the global space for use in the callback function.
401
		$db_callback = array($db_values, $connection);
402
403
		// Inject the values passed to this function.
404
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
405
406
		// This shouldn't be residing in global space any longer.
407
		$db_callback = array();
408
	}
409
410
	// First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
411
	if (empty($modSettings['disableQueryCheck']))
412
	{
413
		$clean = '';
414
		$old_pos = 0;
415
		$pos = -1;
416
		// Remove the string escape for better runtime
417
		$db_string_1 = str_replace('\'\'', '', $db_string);
418
		while (true)
419
		{
420
			$pos = strpos($db_string_1, '\'', $pos + 1);
421
			if ($pos === false)
422
				break;
423
			$clean .= substr($db_string_1, $old_pos, $pos - $old_pos);
424
425
			while (true)
426
			{
427
				$pos1 = strpos($db_string_1, '\'', $pos + 1);
428
				$pos2 = strpos($db_string_1, '\\', $pos + 1);
429
				if ($pos1 === false)
430
					break;
431
				elseif ($pos2 === false || $pos2 > $pos1)
432
				{
433
					$pos = $pos1;
434
					break;
435
				}
436
437
				$pos = $pos2 + 1;
438
			}
439
			$clean .= ' %s ';
440
441
			$old_pos = $pos + 1;
442
		}
443
		$clean .= substr($db_string_1, $old_pos);
444
		$clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
445
446
		// Comments?  We don't use comments in our queries, we leave 'em outside!
447
		if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
448
			$fail = true;
449
		// Trying to change passwords, slow us down, or something?
450
		elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
451
			$fail = true;
452
		elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
453
			$fail = true;
454
455
		if (!empty($fail) && function_exists('log_error'))
456
			smf_db_error_backtrace('No direct access...', 'No direct access...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
457
	}
458
459
	// Set optimize stuff
460
	if (isset($query_opt[$identifier]))
461
	{
462
		$query_hints = $query_opt[$identifier];
463
		$query_hints_set = '';
464
		if (isset($query_hints['join_collapse_limit']))
465
		{
466
			$query_hints_set .= 'SET LOCAL join_collapse_limit = ' . $query_hints['join_collapse_limit'] . ';';
467
		}
468
		if (isset($query_hints['enable_seqscan']))
469
		{
470
			$query_hints_set .= 'SET LOCAL enable_seqscan = ' . $query_hints['enable_seqscan'] . ';';
471
		}
472
473
		$db_string = $query_hints_set . $db_string;
474
	}
475
476
	// Debugging.
477
	if (isset($db_show_debug) && $db_show_debug === true)
478
	{
479
		// Get the file and line number this function was called.
480
		list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
481
482
		// Initialize $db_cache if not already initialized.
483
		if (!isset($db_cache))
484
			$db_cache = array();
485
486
		if (!empty($_SESSION['debug_redirect']))
487
		{
488
			$db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
489
			$db_count = count($db_cache) + 1;
490
			$_SESSION['debug_redirect'] = array();
491
		}
492
493
		// Don't overload it.
494
		$db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
495
		$db_cache[$db_count]['f'] = $file;
496
		$db_cache[$db_count]['l'] = $line;
497
		$db_cache[$db_count]['s'] = ($st = microtime(true)) - TIME_START;
498
	}
499
500
	$db_last_result = @pg_query($connection, $db_string);
501
502
	if ($db_last_result === false && empty($db_values['db_error_skip']))
503
		$db_last_result = smf_db_error($db_string, $connection);
504
505
	// Debugging.
506
	if (isset($db_show_debug) && $db_show_debug === true)
507
		$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...
508
509
	return $db_last_result;
510
}
511
512
/**
513
 * Returns the amount of affected rows for a query.
514
 *
515
 * @param mixed $result
516
 *
517
 * @return int
518
 *
519
 */
520
function smf_db_affected_rows($result = null)
521
{
522
	global $db_last_result, $db_replace_result;
523
524
	if ($db_replace_result)
525
		return $db_replace_result;
526
	elseif ($result === null && !$db_last_result)
527
		return 0;
528
529
	return pg_affected_rows($result === null ? $db_last_result : $result);
530
}
531
532
/**
533
 * Gets the ID of the most recently inserted row.
534
 *
535
 * @param string $table The table (only used for Postgres)
536
 * @param string $field = null The specific field (not used here)
537
 * @param resource $connection = null The connection (if null, $db_connection is used) (not used here)
538
 * @return int The ID of the most recently inserted row
539
 */
540
function smf_db_insert_id($table, $field = null, $connection = null)
541
{
542
	global $smcFunc, $db_prefix;
543
544
	$table = str_replace('{db_prefix}', $db_prefix, $table);
545
546
	// Try get the last ID for the auto increment field.
547
	$request = $smcFunc['db_query']('', 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
548
		array(
549
		)
550
	);
551
	if (!$request)
552
		return false;
553
	list ($lastID) = $smcFunc['db_fetch_row']($request);
554
	$smcFunc['db_free_result']($request);
555
556
	return $lastID;
557
}
558
559
/**
560
 * Do a transaction.
561
 *
562
 * @param string $type The step to perform (i.e. 'begin', 'commit', 'rollback')
563
 * @param resource $connection The connection to use (if null, $db_connection is used)
564
 * @return bool True if successful, false otherwise
565
 */
566
function smf_db_transaction($type = 'commit', $connection = null)
567
{
568
	global $db_connection, $inTransaction;
569
570
	// Decide which connection to use
571
	$connection = $connection === null ? $db_connection : $connection;
572
573
	if ($type == 'begin')
574
	{
575
		$inTransaction = true;
576
		return @pg_query($connection, 'BEGIN');
577
	}
578
	elseif ($type == 'rollback')
579
	{
580
		$inTransaction = false;
581
		return @pg_query($connection, 'ROLLBACK');
582
	}
583
	elseif ($type == 'commit')
584
	{
585
		$inTransaction = false;
586
		return @pg_query($connection, 'COMMIT');
587
	}
588
589
	return false;
590
}
591
592
/**
593
 * Database error!
594
 * Backtrace, log, try to fix.
595
 *
596
 * @param string $db_string The DB string
597
 * @param resource $connection The connection to use (if null, $db_connection is used)
598
 */
599
function smf_db_error($db_string, $connection = null)
600
{
601
	global $txt, $context, $modSettings;
602
	global $db_connection;
603
	global $db_show_debug;
604
605
	// We'll try recovering the file and line number the original db query was called from.
606
	list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
607
608
	// Decide which connection to use
609
	$connection = $connection === null ? $db_connection : $connection;
610
611
	// This is the error message...
612
	$query_error = @pg_last_error($connection);
613
614
	// Log the error.
615
	if (function_exists('log_error'))
616
		log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" . $db_string : ''), 'database', $file, $line);
617
618
	// Nothing's defined yet... just die with it.
619
	if (empty($context) || empty($txt))
620
		die($query_error);
621
622
	// Show an error message, if possible.
623
	$context['error_title'] = $txt['database_error'];
624
	if (allowedTo('admin_forum'))
625
		$context['error_message'] = nl2br($query_error) . '<br>' . $txt['file'] . ': ' . $file . '<br>' . $txt['line'] . ': ' . $line;
626
	else
627
		$context['error_message'] = $txt['try_again'];
628
629
	if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
630
	{
631
		$context['error_message'] .= '<br><br>' . nl2br($db_string);
632
	}
633
634
	// It's already been logged... don't log it again.
635
	fatal_error($context['error_message'], false);
636
}
637
638
/**
639
 * Inserts data into a table
640
 *
641
 * @param string $method The insert method - can be 'replace', 'ignore' or 'insert'
642
 * @param string $table The table we're inserting the data into
643
 * @param array $columns An array of the columns we're inserting the data into. Should contain 'column' => 'datatype' pairs
644
 * @param array $data The data to insert
645
 * @param array $keys The keys for the table, needs to be not empty on replace mode
646
 * @param int returnmode 0 = nothing(default), 1 = last row id, 2 = all rows id as array; every mode runs only with method != 'ignore'
647
 * @param resource $connection The connection to use (if null, $db_connection is used)
648
 * @return mixed value of the first key, behavior based on returnmode. null if no data.
649
 */
650
function smf_db_insert($method, $table, $columns, $data, $keys, $returnmode = 0, $connection = null)
651
{
652
	global $smcFunc, $db_connection, $db_prefix, $txt;
653
654
	$connection = $connection === null ? $db_connection : $connection;
655
656
	$replace = '';
657
658
	if (empty($table) || empty($data))
659
		return;
660
661
	// Force method to lower case
662
	$method = strtolower($method);
663
664
	if (!is_array($data[array_rand($data)]))
665
		$data = array($data);
666
667
	// Replace the prefix holder with the actual prefix.
668
	$table = str_replace('{db_prefix}', $db_prefix, $table);
669
670
	// Sanity check for replace is key part of the columns array
671
	if ($method == 'replace')
672
	{
673
		if (empty($keys))
674
			smf_db_error_backtrace('When using the replace mode, the key column is a required entry.',
675
				'Change the method of db insert to insert or add the pk field to the key array', E_USER_ERROR, __FILE__, __LINE__);
676
		if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys))
677
			smf_db_error_backtrace('Primary Key field missing in insert call',
678
				'Change the method of db insert to insert or add the pk field to the columns array', E_USER_ERROR, __FILE__, __LINE__);
679
	}
680
681
	// PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead
682
	if ($method == 'replace' || $method == 'ignore')
683
	{
684
		$key_str = '';
685
		$col_str = '';
686
687
		$count = 0;
688
		$count_pk = 0;
689
690
		foreach ($columns as $columnName => $type)
691
		{
692
			//check pk fiel
693
			IF (in_array($columnName, $keys))
694
			{
695
				$key_str .= ($count_pk > 0 ? ',' : '');
696
				$key_str .= $columnName;
697
				$count_pk++;
698
			}
699
			elseif ($method == 'replace') //normal field
700
			{
701
				$col_str .= ($count > 0 ? ',' : '');
702
				$col_str .= $columnName . ' = EXCLUDED.' . $columnName;
703
				$count++;
704
			}
705
		}
706
		if ($method == 'replace')
707
			$replace = ' ON CONFLICT (' . $key_str . ') DO UPDATE SET ' . $col_str;
708
		else
709
			$replace = ' ON CONFLICT (' . $key_str . ') DO NOTHING';
710
711
	}
712
713
	$returning = '';
714
	$with_returning = false;
715
	// lets build the returning string, mysql allow only in normal mode
716
	if (!empty($keys) && (count($keys) > 0) && $returnmode > 0)
717
	{
718
		// we only take the first key
719
		$returning = ' RETURNING ' . $keys[0];
720
		$with_returning = true;
721
	}
722
723
	if (!empty($data))
724
	{
725
		// Create the mold for a single row insert.
726
		$insertData = '(';
727
		foreach ($columns as $columnName => $type)
728
		{
729
			// Are we restricting the length?
730
			if (strpos($type, 'string-') !== false)
731
				$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
732
			else
733
				$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
734
		}
735
		$insertData = substr($insertData, 0, -2) . ')';
736
737
		// Create an array consisting of only the columns.
738
		$indexed_columns = array_keys($columns);
739
740
		// Here's where the variables are injected to the query.
741
		$insertRows = array();
742
		foreach ($data as $dataRow)
743
			$insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
744
745
		// Do the insert.
746
		$request = $smcFunc['db_query']('', '
747
			INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '")
748
			VALUES
749
				' . implode(',
750
				', $insertRows) . $replace . $returning,
751
			array(
752
				'security_override' => true,
753
				'db_error_skip' => $method == 'ignore' || $table === $db_prefix . 'log_errors',
754
			),
755
			$connection
756
		);
757
758
		if ($with_returning && $request !== false)
759
		{
760
			if ($returnmode === 2)
761
				$return_var = array();
762
763
			while (($row = $smcFunc['db_fetch_row']($request)) && $with_returning)
764
			{
765
				if (is_numeric($row[0])) // try to emulate mysql limitation
766
				{
767
					if ($returnmode === 1)
768
						$return_var = $row[0];
769
					elseif ($returnmode === 2)
770
						$return_var[] = $row[0];
771
				}
772
				else
773
				{
774
					$with_returning = false;
775
					loadLanguage('Errors');
776
					throw new \TypeError('postgres_id_not_int');
777
				}
778
			}
779
		}
780
	}
781
782
	if ($with_returning && !empty($return_var))
783
		return $return_var;
784
}
785
786
/**
787
 * Dummy function really. Doesn't do anything on PostgreSQL.
788
 *
789
 * @param string $db_name The database name
790
 * @param resource $db_connection The database connection
791
 * @return true Always returns true
792
 */
793
function smf_db_select_db($db_name, $db_connection)
794
{
795
	return true;
796
}
797
798
/**
799
 * Get the current version.
800
 *
801
 * @return string The client version
802
 */
803
function smf_db_version()
804
{
805
	$version = pg_version();
806
807
	return $version['client'];
808
}
809
810
/**
811
 * This function tries to work out additional error information from a back trace.
812
 *
813
 * @param string $error_message The error message
814
 * @param string $log_message The message to log
815
 * @param string|bool $error_type What type of error this is
816
 * @param string $file The file the error occurred in
817
 * @param int $line What line of $file the code which generated the error is on
818
 * @return void|array Returns an array with the file and line if $error_type is 'return'
819
 */
820
function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
821
{
822
	if (empty($log_message))
823
		$log_message = $error_message;
824
825
	foreach (debug_backtrace() as $step)
826
	{
827
		// Found it?
828
		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)
829
		{
830
			$log_message .= '<br>Function: ' . $step['function'];
831
			break;
832
		}
833
834
		if (isset($step['line']))
835
		{
836
			$file = $step['file'];
837
			$line = $step['line'];
838
		}
839
	}
840
841
	// A special case - we want the file and line numbers for debugging.
842
	if ($error_type == 'return')
843
		return array($file, $line);
844
845
	// Is always a critical error.
846
	if (function_exists('log_error'))
847
		log_error($log_message, 'critical', $file, $line);
848
849
	if (function_exists('fatal_error'))
850
	{
851
		fatal_error($error_message, $error_type);
852
853
		// Cannot continue...
854
		exit;
855
	}
856
	elseif ($error_type)
857
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
858
	else
859
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
860
}
861
862
/**
863
 * Escape the LIKE wildcards so that they match the character and not the wildcard.
864
 *
865
 * @param string $string The string to escape
866
 * @param bool $translate_human_wildcards If true, turns human readable wildcards into SQL wildcards.
867
 * @return string The escaped string
868
 */
869
function smf_db_escape_wildcard_string($string, $translate_human_wildcards = false)
870
{
871
	$replacements = array(
872
		'%' => '\%',
873
		'_' => '\_',
874
		'\\' => '\\\\',
875
	);
876
877
	if ($translate_human_wildcards)
878
		$replacements += array(
879
			'*' => '%',
880
		);
881
882
	return strtr($string, $replacements);
883
}
884
885
/**
886
 * Fetches all rows from a result as an array
887
 *
888
 * @param resource $request A PostgreSQL result resource
889
 * @return array An array that contains all rows (records) in the result resource
890
 */
891
function smf_db_fetch_all($request)
892
{
893
	// Return the right row.
894
	$return = @pg_fetch_all($request);
895
	return !empty($return) ? $return : array();
896
}
897
898
/**
899
 * Function to save errors in database in a safe way
900
 *
901
 * @param array with keys in this order id_member, log_time, ip, url, message, session, error_type, file, line
902
 * @return void
903
 */
904
function smf_db_error_insert($error_array)
905
{
906
	global $db_prefix, $db_connection, $db_persist, $smcFunc, $inTransaction;
907
	static $pg_error_data_prep;
908
909
	// without database we can't do anything
910
	if (empty($db_connection))
911
		return;
912
913
	if (filter_var($error_array[2], FILTER_VALIDATE_IP) === false)
914
		$error_array[2] = null;
915
916
	// If we are in a transaction, abort.
917
	if (!empty($inTransaction))
918
		smf_db_transaction('rollback');
919
920
	if(empty($db_persist))
921
	{ // without pooling
922
		if (empty($pg_error_data_prep))
923
			$pg_error_data_prep = pg_prepare($db_connection, 'smf_log_errors',
924
				'INSERT INTO ' . $db_prefix . 'log_errors
925
					(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
926
				VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
927
			);
928
929
		pg_execute($db_connection, 'smf_log_errors', $error_array);
930
	}
931
	else
932
	{ //with pooling
933
		$pg_error_data_prep = pg_prepare($db_connection, '',
934
			'INSERT INTO ' . $db_prefix . 'log_errors
935
				(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
936
			VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
937
		);
938
939
		pg_execute($db_connection, '', $error_array);
940
	}
941
942
}
943
944
/**
945
 * Function which constructs an optimize custom order string
946
 * as an improved alternative to find_in_set()
947
 *
948
 * @param string $field name
949
 * @param array $array_values Field values sequenced in array via order priority. Must cast to int.
950
 * @param boolean $desc default false
951
 * @return string case field when ... then ... end
952
 */
953
function smf_db_custom_order($field, $array_values, $desc = false)
954
{
955
	$return = 'CASE ' . $field . ' ';
956
	$count = count($array_values);
957
	$then = ($desc ? ' THEN -' : ' THEN ');
958
959
	for ($i = 0; $i < $count; $i++)
960
		$return .= 'WHEN ' . (int) $array_values[$i] . $then . $i . ' ';
961
962
	$return .= 'END';
963
	return $return;
964
}
965
966
/**
967
 * Function which return the information if the database supports native replace inserts
968
 *
969
 * @return boolean true or false
970
 */
971
function smf_db_native_replace()
972
{
973
	return true;
974
}
975
976
/**
977
 * Function which return the information if the database supports cte with recursive
978
 *
979
 * @return boolean true or false
980
 */
981
function smf_db_cte_support()
982
{
983
	return true;
984
}
985
986
/**
987
 * Function which return the escaped string
988
 *
989
 * @param string the unescaped text
990
 * @param resource $connection = null The connection to use (null to use $db_connection)
991
 * @return string escaped string
992
 */
993
function smf_db_escape_string($string, $connection = null)
994
{
995
	global $db_connection;
996
997
	return pg_escape_string($connection === null ? $db_connection : $connection, $string);
998
}
999
1000
/**
1001
 * Function to return the pg connection error message.
1002
 * Emulating mysqli_connect_error.
1003
 * Since pg_connect() doesn't feed info to pg_last_error, we need to
1004
 * use a try/catch & preserve error info.
1005
 *
1006
 * @return string connection error message
1007
 */
1008
function smf_db_connect_error()
1009
{
1010
	global $pg_connect_error;
1011
1012
	if (empty($pg_connect_error))
1013
		$pg_connect_error = '';
1014
1015
	return $pg_connect_error;
1016
}
1017
1018
/**
1019
 * Function to return the pg connection error number.
1020
 * Emulating mysqli_connect_errno.
1021
 * Since pg_connect() doesn't feed info to pg_last_error, we need to
1022
 * use a try/catch & preserve error info.
1023
 *
1024
 * @return string connection error number
1025
 */
1026
function smf_db_connect_errno()
1027
{
1028
	global $pg_connect_errno;
1029
1030
	if (empty($pg_connect_errno))
1031
		$pg_connect_errno = '';
1032
1033
	return $pg_connect_errno;
1034
}
1035
1036
/**
1037
 * Wrapper to handle null errors
1038
 *
1039
 * @param null|PgSql\Connection $connection = null The connection to use (null to use $db_connection)
1040
 * @return string escaped string
1041
 */
1042
function smf_db_errormsg($connection = null)
1043
{
1044
	global $db_connection;
1045
1046
	if ($connection === null && $db_connection === null)
1047
		return '';
1048
1049
	return pg_last_error($connection === null ? $db_connection : $connection);
1050
}
1051
1052
?>