Test Setup Failed
Push — release-2.1 ( 545d09...f28109 )
by Mathias
16:19 queued 10s
created

smf_db_connect_errno()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
rs 10
c 1
b 0
f 0
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 2020 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 RC3
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'                  => 'pg_last_error',
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(function($errno, $errstr) {
82
		throw new ErrorException($errstr, $errno);});
83
	try
84
	{
85
		if (!empty($db_options['persist']))
86
			$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'] . '\''));
87
		else
88
			$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'] . '\''));
89
	}
90
	catch (Exception $e)
91
	{
92
		// Make error info available to calling processes
93
		$pg_connect_error = $e->getMessage();
94
		$pg_connect_errno = $e->getCode();
95
		$connection = false;
96
	}
97
	restore_error_handler();
98
99
	// Something's wrong, show an error if its fatal (which we assume it is)
100
	if (!$connection)
0 ignored issues
show
introduced by
$connection is of type false|resource, thus it always evaluated to false.
Loading history...
101
	{
102
		if (!empty($db_options['non_fatal']))
103
		{
104
			return null;
105
		}
106
		else
107
		{
108
			display_db_error();
109
		}
110
	}
111
112
	if (!empty($db_options['db_mb4']))
113
		$smcFunc['db_mb4'] = (bool) $db_options['db_mb4'];
114
115
	return $connection;
116
}
117
118
/**
119
 * Extend the database functionality. It calls the respective file's init
120
 * to add the implementations in that file to $smcFunc array.
121
 *
122
 * @param string $type Indicates which additional file to load. ('extra', 'packages')
123
 */
124
function db_extend($type = 'extra')
125
{
126
	global $sourcedir, $db_type;
127
128
	require_once($sourcedir . '/Db' . strtoupper($type[0]) . substr($type, 1) . '-' . $db_type . '.php');
129
	$initFunc = 'db_' . $type . '_init';
130
	$initFunc();
131
}
132
133
/**
134
 * Fix the database prefix if necessary.
135
 * Does nothing on PostgreSQL
136
 *
137
 * @param string $db_prefix The database prefix
138
 * @param string $db_name The database name
139
 */
140
function db_fix_prefix(&$db_prefix, $db_name)
141
{
142
	return;
143
}
144
145
/**
146
 * Callback for preg_replace_callback on the query.
147
 * It allows to replace on the fly a few pre-defined strings, for convenience ('query_see_board', 'query_wanna_see_board', etc), with
148
 * their current values from $user_info.
149
 * In addition, it performs checks and sanitization on the values sent to the database.
150
 *
151
 * @param array $matches The matches from preg_replace_callback
152
 * @return string The appropriate string depending on $matches[1]
153
 */
154
function smf_db_replacement__callback($matches)
155
{
156
	global $db_callback, $user_info, $db_prefix, $smcFunc;
157
158
	list ($values, $connection) = $db_callback;
159
160
	if ($matches[1] === 'db_prefix')
161
		return $db_prefix;
162
163
	if (isset($user_info[$matches[1]]) && strpos($matches[1], 'query_') !== false)
164
		return $user_info[$matches[1]];
165
166
	if ($matches[1] === 'empty')
167
		return '\'\'';
168
169
	if (!isset($matches[2]))
170
		smf_db_error_backtrace('Invalid value inserted or no type specified.', '', E_USER_ERROR, __FILE__, __LINE__);
171
172
	if ($matches[1] === 'literal')
173
		return '\'' . pg_escape_string($matches[2]) . '\'';
0 ignored issues
show
Bug introduced by
The call to pg_escape_string() has too few arguments starting with data. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

173
		return '\'' . /** @scrutinizer ignore-call */ pg_escape_string($matches[2]) . '\'';

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
174
175
	if (!isset($values[$matches[2]]))
176
		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__);
177
178
	$replacement = $values[$matches[2]];
179
180
	switch ($matches[1])
181
	{
182
		case 'int':
183
			if (!is_numeric($replacement) || (string) $replacement !== (string) (int) $replacement)
184
				smf_db_error_backtrace('Wrong value type sent to the database. Integer expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
185
			return (string) (int) $replacement;
186
			break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
187
188
		case 'string':
189
		case 'text':
190
			return sprintf('\'%1$s\'', pg_escape_string($replacement));
191
			break;
192
193
		case 'array_int':
194
			if (is_array($replacement))
195
			{
196
				if (empty($replacement))
197
					smf_db_error_backtrace('Database error, given array of integer values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
198
199
				foreach ($replacement as $key => $value)
200
				{
201
					if (!is_numeric($value) || (string) $value !== (string) (int) $value)
202
						smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
203
204
					$replacement[$key] = (string) (int) $value;
205
				}
206
207
				return implode(', ', $replacement);
208
			}
209
			else
210
				smf_db_error_backtrace('Wrong value type sent to the database. Array of integers expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
211
212
			break;
213
214
		case 'array_string':
215
			if (is_array($replacement))
216
			{
217
				if (empty($replacement))
218
					smf_db_error_backtrace('Database error, given array of string values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
219
220
				foreach ($replacement as $key => $value)
221
					$replacement[$key] = sprintf('\'%1$s\'', pg_escape_string($value));
222
223
				return implode(', ', $replacement);
224
			}
225
			else
226
				smf_db_error_backtrace('Wrong value type sent to the database. Array of strings expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
227
			break;
228
229
		case 'date':
230
			if (preg_match('~^(\d{4})-([0-1]?\d)-([0-3]?\d)$~', $replacement, $date_matches) === 1)
231
				return sprintf('\'%04d-%02d-%02d\'', $date_matches[1], $date_matches[2], $date_matches[3]) . '::date';
232
			else
233
				smf_db_error_backtrace('Wrong value type sent to the database. Date expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
234
			break;
235
236
		case 'time':
237
			if (preg_match('~^([0-1]?\d|2[0-3]):([0-5]\d):([0-5]\d)$~', $replacement, $time_matches) === 1)
238
				return sprintf('\'%02d:%02d:%02d\'', $time_matches[1], $time_matches[2], $time_matches[3]) . '::time';
239
			else
240
				smf_db_error_backtrace('Wrong value type sent to the database. Time expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
241
			break;
242
243
		case 'datetime':
244
			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)
245
				return 'to_timestamp(' .
246
					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]) .
247
					',\'YYYY-MM-DD HH24:MI:SS\')';
248
			else
249
				smf_db_error_backtrace('Wrong value type sent to the database. Datetime expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
250
			break;
251
252
		case 'float':
253
			if (!is_numeric($replacement))
254
				smf_db_error_backtrace('Wrong value type sent to the database. Floating point number expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
255
			return (string) (float) $replacement;
256
			break;
257
258
		case 'identifier':
259
			return '"' . strtr($replacement, array('`' => '', '.' => '"."')) . '"';
260
			break;
261
262
		case 'raw':
263
			return $replacement;
264
			break;
265
266
		case 'inet':
267
			if ($replacement == 'null' || $replacement == '')
268
				return 'null';
269
			if (inet_pton($replacement) === false)
270
				smf_db_error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
271
			return sprintf('\'%1$s\'::inet', pg_escape_string($replacement));
272
273
		case 'array_inet':
274
			if (is_array($replacement))
275
			{
276
				if (empty($replacement))
277
					smf_db_error_backtrace('Database error, given array of IPv4 or IPv6 values is empty. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
278
279
				foreach ($replacement as $key => $value)
280
				{
281
					if ($replacement == 'null' || $replacement == '')
282
						$replacement[$key] = 'null';
283
					if (!isValidIP($value))
284
						smf_db_error_backtrace('Wrong value type sent to the database. IPv4 or IPv6 expected.(' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
285
					$replacement[$key] = sprintf('\'%1$s\'::inet', pg_escape_string($value));
286
				}
287
288
				return implode(', ', $replacement);
289
			}
290
			else
291
				smf_db_error_backtrace('Wrong value type sent to the database. Array of IPv4 or IPv6 expected. (' . $matches[2] . ')', '', E_USER_ERROR, __FILE__, __LINE__);
292
			break;
293
294
		default:
295
			smf_db_error_backtrace('Undefined type used in the database query. (' . $matches[1] . ':' . $matches[2] . ')', '', false, __FILE__, __LINE__);
296
			break;
297
	}
298
}
299
300
/**
301
 * Just like the db_query, escape and quote a string, but not executing the query.
302
 *
303
 * @param string $db_string The database string
304
 * @param array $db_values An array of values to be injected into the string
305
 * @param resource $connection = null The connection to use (null to use $db_connection)
306
 * @return string The string with the values inserted
307
 */
308
function smf_db_quote($db_string, $db_values, $connection = null)
309
{
310
	global $db_callback, $db_connection;
311
312
	// Only bother if there's something to replace.
313
	if (strpos($db_string, '{') !== false)
314
	{
315
		// This is needed by the callback function.
316
		$db_callback = array($db_values, $connection === null ? $db_connection : $connection);
317
318
		// Do the quoting and escaping
319
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
320
321
		// Clear this global variable.
322
		$db_callback = array();
323
	}
324
325
	return $db_string;
326
}
327
328
/**
329
 * Do a query.  Takes care of errors too.
330
 * Special queries may need additional replacements to be appropriate
331
 * for PostgreSQL.
332
 *
333
 * @param string $identifier An identifier. Only used in Postgres when we need to do things differently...
334
 * @param string $db_string The database string
335
 * @param array $db_values = array() The values to be inserted into the string
336
 * @param resource $connection = null The connection to use (null to use $db_connection)
337
 * @return resource|bool Returns a MySQL result resource (for SELECT queries), true (for UPDATE queries) or false if the query failed
338
 */
339
function smf_db_query($identifier, $db_string, $db_values = array(), $connection = null)
340
{
341
	global $db_cache, $db_count, $db_connection, $db_show_debug;
342
	global $db_callback, $db_last_result, $db_replace_result, $modSettings;
343
344
	// Decide which connection to use.
345
	$connection = $connection === null ? $db_connection : $connection;
346
347
	// Special queries that need processing.
348
	$replacements = array(
349
		'insert_log_search_topics' => array(
350
			'~NOT RLIKE~' => '!~',
351
		),
352
		'insert_log_search_results_no_index' => array(
353
			'~NOT RLIKE~' => '!~',
354
		),
355
		'insert_log_search_results_subject' => array(
356
			'~NOT RLIKE~' => '!~',
357
		),
358
		'profile_board_stats' => array(
359
			'~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)',
360
		),
361
	);
362
363
	// Special optimizer Hints
364
	$query_opt = array(
365
		'load_board_info' => array(
366
			'join_collapse_limit' => 1,
367
		),
368
		'calendar_get_events' => array(
369
			'enable_seqscan' => 'off',
370
		),
371
	);
372
373
	if (isset($replacements[$identifier]))
374
		$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
375
376
	// Limits need to be a little different.
377
	$db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string);
378
379
	if (trim($db_string) == '')
380
		return false;
381
382
	// Comments that are allowed in a query are preg_removed.
383
	static $allowed_comments_from = array(
384
		'~\s+~s',
385
		'~/\*!40001 SQL_NO_CACHE \*/~',
386
		'~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
387
		'~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
388
	);
389
	static $allowed_comments_to = array(
390
		' ',
391
		'',
392
		'',
393
		'',
394
	);
395
396
	// One more query....
397
	$db_count = !isset($db_count) ? 1 : $db_count + 1;
398
	$db_replace_result = 0;
399
400
	if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
401
		smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
402
403
	if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
404
	{
405
		// Pass some values to the global space for use in the callback function.
406
		$db_callback = array($db_values, $connection);
407
408
		// Inject the values passed to this function.
409
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
410
411
		// This shouldn't be residing in global space any longer.
412
		$db_callback = array();
413
	}
414
415
	// First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
416
	if (empty($modSettings['disableQueryCheck']))
417
	{
418
		$clean = '';
419
		$old_pos = 0;
420
		$pos = -1;
421
		// Remove the string escape for better runtime
422
		$db_string_1 = str_replace('\'\'', '', $db_string);
423
		while (true)
424
		{
425
			$pos = strpos($db_string_1, '\'', $pos + 1);
426
			if ($pos === false)
427
				break;
428
			$clean .= substr($db_string_1, $old_pos, $pos - $old_pos);
429
430
			while (true)
431
			{
432
				$pos1 = strpos($db_string_1, '\'', $pos + 1);
433
				$pos2 = strpos($db_string_1, '\\', $pos + 1);
434
				if ($pos1 === false)
435
					break;
436
				elseif ($pos2 === false || $pos2 > $pos1)
437
				{
438
					$pos = $pos1;
439
					break;
440
				}
441
442
				$pos = $pos2 + 1;
443
			}
444
			$clean .= ' %s ';
445
446
			$old_pos = $pos + 1;
447
		}
448
		$clean .= substr($db_string_1, $old_pos);
449
		$clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
450
451
		// Comments?  We don't use comments in our queries, we leave 'em outside!
452
		if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
453
			$fail = true;
454
		// Trying to change passwords, slow us down, or something?
455
		elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
456
			$fail = true;
457
		elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
458
			$fail = true;
459
460
		if (!empty($fail) && function_exists('log_error'))
461
			smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
462
	}
463
464
	// Set optimize stuff
465
	if (isset($query_opt[$identifier]))
466
	{
467
		$query_hints = $query_opt[$identifier];
468
		$query_hints_set = '';
469
		if (isset($query_hints['join_collapse_limit']))
470
		{
471
			$query_hints_set .= 'SET LOCAL join_collapse_limit = ' . $query_hints['join_collapse_limit'] . ';';
472
		}
473
		if (isset($query_hints['enable_seqscan']))
474
		{
475
			$query_hints_set .= 'SET LOCAL enable_seqscan = ' . $query_hints['enable_seqscan'] . ';';
476
		}
477
478
		$db_string = $query_hints_set . $db_string;
479
	}
480
481
	// Debugging.
482
	if (isset($db_show_debug) && $db_show_debug === true)
483
	{
484
		// Get the file and line number this function was called.
485
		list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
486
487
		// Initialize $db_cache if not already initialized.
488
		if (!isset($db_cache))
489
			$db_cache = array();
490
491
		if (!empty($_SESSION['debug_redirect']))
492
		{
493
			$db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
494
			$db_count = count($db_cache) + 1;
495
			$_SESSION['debug_redirect'] = array();
496
		}
497
498
		// Don't overload it.
499
		$db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
500
		$db_cache[$db_count]['f'] = $file;
501
		$db_cache[$db_count]['l'] = $line;
502
		$db_cache[$db_count]['s'] = ($st = microtime(true)) - TIME_START;
503
	}
504
505
	$db_last_result = @pg_query($connection, $db_string);
506
507
	if ($db_last_result === false && empty($db_values['db_error_skip']))
508
		$db_last_result = smf_db_error($db_string, $connection);
0 ignored issues
show
Bug introduced by
It seems like $connection can also be of type resource; however, parameter $connection of smf_db_error() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

508
		$db_last_result = smf_db_error($db_string, /** @scrutinizer ignore-type */ $connection);
Loading history...
509
510
	// Debugging.
511
	if (isset($db_show_debug) && $db_show_debug === true)
512
		$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...
513
514
	return $db_last_result;
515
}
516
517
/**
518
 * Returns the amount of affected rows for a query.
519
 *
520
 * @param mixed $result
521
 *
522
 * @return int
523
 *
524
 */
525
function smf_db_affected_rows($result = null)
526
{
527
	global $db_last_result, $db_replace_result;
528
529
	if ($db_replace_result)
530
		return $db_replace_result;
531
	elseif ($result === null && !$db_last_result)
532
		return 0;
533
534
	return pg_affected_rows($result === null ? $db_last_result : $result);
535
}
536
537
/**
538
 * Gets the ID of the most recently inserted row.
539
 *
540
 * @param string $table The table (only used for Postgres)
541
 * @param string $field = null The specific field (not used here)
542
 * @param resource $connection = null The connection (if null, $db_connection is used) (not used here)
543
 * @return int The ID of the most recently inserted row
544
 */
545
function smf_db_insert_id($table, $field = null, $connection = null)
546
{
547
	global $smcFunc, $db_prefix;
548
549
	$table = str_replace('{db_prefix}', $db_prefix, $table);
550
551
	// Try get the last ID for the auto increment field.
552
	$request = $smcFunc['db_query']('', 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
553
		array(
554
		)
555
	);
556
	if (!$request)
557
		return false;
558
	list ($lastID) = $smcFunc['db_fetch_row']($request);
559
	$smcFunc['db_free_result']($request);
560
561
	return $lastID;
562
}
563
564
/**
565
 * Do a transaction.
566
 *
567
 * @param string $type The step to perform (i.e. 'begin', 'commit', 'rollback')
568
 * @param resource $connection The connection to use (if null, $db_connection is used)
569
 * @return bool True if successful, false otherwise
570
 */
571
function smf_db_transaction($type = 'commit', $connection = null)
572
{
573
	global $db_connection;
574
575
	// Decide which connection to use
576
	$connection = $connection === null ? $db_connection : $connection;
577
578
	if ($type == 'begin')
579
		return @pg_query($connection, 'BEGIN');
580
	elseif ($type == 'rollback')
581
		return @pg_query($connection, 'ROLLBACK');
582
	elseif ($type == 'commit')
583
		return @pg_query($connection, 'COMMIT');
584
585
	return false;
586
}
587
588
/**
589
 * Database error!
590
 * Backtrace, log, try to fix.
591
 *
592
 * @param string $db_string The DB string
593
 * @param resource $connection The connection to use (if null, $db_connection is used)
594
 */
595
function smf_db_error($db_string, $connection = null)
596
{
597
	global $txt, $context, $modSettings;
598
	global $db_connection;
599
	global $db_show_debug;
600
601
	// We'll try recovering the file and line number the original db query was called from.
602
	list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
603
604
	// Decide which connection to use
605
	$connection = $connection === null ? $db_connection : $connection;
606
607
	// This is the error message...
608
	$query_error = @pg_last_error($connection);
609
610
	// Log the error.
611
	if (function_exists('log_error'))
612
		log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" . $db_string : ''), 'database', $file, $line);
613
614
	// Nothing's defined yet... just die with it.
615
	if (empty($context) || empty($txt))
616
		die($query_error);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
617
618
	// Show an error message, if possible.
619
	$context['error_title'] = $txt['database_error'];
620
	if (allowedTo('admin_forum'))
621
		$context['error_message'] = nl2br($query_error) . '<br>' . $txt['file'] . ': ' . $file . '<br>' . $txt['line'] . ': ' . $line;
622
	else
623
		$context['error_message'] = $txt['try_again'];
624
625
	if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
626
	{
627
		$context['error_message'] .= '<br><br>' . nl2br($db_string);
628
	}
629
630
	// It's already been logged... don't log it again.
631
	fatal_error($context['error_message'], false);
632
}
633
634
/**
635
 * Inserts data into a table
636
 *
637
 * @param string $method The insert method - can be 'replace', 'ignore' or 'insert'
638
 * @param string $table The table we're inserting the data into
639
 * @param array $columns An array of the columns we're inserting the data into. Should contain 'column' => 'datatype' pairs
640
 * @param array $data The data to insert
641
 * @param array $keys The keys for the table, needs to be not empty on replace mode
642
 * @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
Bug introduced by
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...
643
 * @param resource $connection The connection to use (if null, $db_connection is used)
644
 * @return mixed value of the first key, behavior based on returnmode. null if no data.
645
 */
646
function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $returnmode = 0, $connection = null)
647
{
648
	global $smcFunc, $db_connection, $db_prefix;
649
650
	$connection = $connection === null ? $db_connection : $connection;
651
652
	$replace = '';
653
654
	if (empty($data))
655
		return;
656
657
	if (!is_array($data[array_rand($data)]))
658
		$data = array($data);
659
660
	// Replace the prefix holder with the actual prefix.
661
	$table = str_replace('{db_prefix}', $db_prefix, $table);
662
663
	// Sanity check for replace is key part of the columns array
664
	if ($method == 'replace')
665
	{
666
		if (empty($keys))
667
			smf_db_error_backtrace('When using the replace mode, the key column is a required entry.',
668
				'Change the method of db insert to insert or add the pk field to the key array', E_USER_ERROR, __FILE__, __LINE__);
669
		if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys))
670
			smf_db_error_backtrace('Primary Key field missing in insert call',
671
				'Change the method of db insert to insert or add the pk field to the columns array', E_USER_ERROR, __FILE__, __LINE__);
672
	}
673
674
	// PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead
675
	if ($method == 'replace' || $method == 'ignore')
676
	{
677
		$key_str = '';
678
		$col_str = '';
679
		$replace_support = $smcFunc['db_native_replace']();
680
681
		$count = 0;
682
		$where = '';
683
		$count_pk = 0;
684
685
		If ($replace_support)
686
		{
687
			foreach ($columns as $columnName => $type)
688
			{
689
				//check pk fiel
690
				IF (in_array($columnName, $keys))
691
				{
692
					$key_str .= ($count_pk > 0 ? ',' : '');
693
					$key_str .= $columnName;
694
					$count_pk++;
695
				}
696
				elseif ($method == 'replace') //normal field
697
				{
698
					$col_str .= ($count > 0 ? ',' : '');
699
					$col_str .= $columnName . ' = EXCLUDED.' . $columnName;
700
					$count++;
701
				}
702
			}
703
			if ($method == 'replace')
704
				$replace = ' ON CONFLICT (' . $key_str . ') DO UPDATE SET ' . $col_str;
705
			else
706
				$replace = ' ON CONFLICT (' . $key_str . ') DO NOTHING';
707
		}
708
		elseif ($method == 'replace')
709
		{
710
			foreach ($columns as $columnName => $type)
711
			{
712
				// Are we restricting the length?
713
				if (strpos($type, 'string-') !== false)
714
					$actualType = sprintf($columnName . ' = SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $count);
715
				else
716
					$actualType = sprintf($columnName . ' = {%1$s:%2$s}, ', $type, $count);
717
718
				// A key? That's what we were looking for.
719
				if (in_array($columnName, $keys))
720
					$where .= (empty($where) ? '' : ' AND ') . substr($actualType, 0, -2);
721
				$count++;
722
			}
723
724
			// Make it so.
725
			if (!empty($where) && !empty($data))
726
			{
727
				foreach ($data as $k => $entry)
728
				{
729
					$smcFunc['db_query']('', '
730
						DELETE FROM ' . $table .
731
						' WHERE ' . $where,
732
						$entry, $connection
733
					);
734
				}
735
			}
736
		}
737
	}
738
739
	$returning = '';
740
	$with_returning = false;
741
	// lets build the returning string, mysql allow only in normal mode
742
	if (!empty($keys) && (count($keys) > 0) && $returnmode > 0)
743
	{
744
		// we only take the first key
745
		$returning = ' RETURNING ' . $keys[0];
746
		$with_returning = true;
747
	}
748
749
	if (!empty($data))
750
	{
751
		// Create the mold for a single row insert.
752
		$insertData = '(';
753
		foreach ($columns as $columnName => $type)
754
		{
755
			// Are we restricting the length?
756
			if (strpos($type, 'string-') !== false)
757
				$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
758
			else
759
				$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
760
		}
761
		$insertData = substr($insertData, 0, -2) . ')';
762
763
		// Create an array consisting of only the columns.
764
		$indexed_columns = array_keys($columns);
765
766
		// Here's where the variables are injected to the query.
767
		$insertRows = array();
768
		foreach ($data as $dataRow)
769
			$insertRows[] = smf_db_quote($insertData, array_combine($indexed_columns, $dataRow), $connection);
0 ignored issues
show
Bug introduced by
It seems like array_combine($indexed_columns, $dataRow) can also be of type false; however, parameter $db_values of smf_db_quote() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

769
			$insertRows[] = smf_db_quote($insertData, /** @scrutinizer ignore-type */ array_combine($indexed_columns, $dataRow), $connection);
Loading history...
770
771
		// Do the insert.
772
		$request = $smcFunc['db_query']('', '
773
			INSERT INTO ' . $table . '("' . implode('", "', $indexed_columns) . '")
774
			VALUES
775
				' . implode(',
776
				', $insertRows) . $replace . $returning,
777
			array(
778
				'security_override' => true,
779
				'db_error_skip' => $method == 'ignore' || $table === $db_prefix . 'log_errors',
780
			),
781
			$connection
782
		);
783
784
		if ($with_returning && $request !== false)
785
		{
786
			if ($returnmode === 2)
787
				$return_var = array();
788
789
			while (($row = $smcFunc['db_fetch_row']($request)) && $with_returning)
790
			{
791
				if (is_numeric($row[0])) // try to emulate mysql limitation
792
				{
793
					if ($returnmode === 1)
794
						$return_var = $row[0];
795
					elseif ($returnmode === 2)
796
						$return_var[] = $row[0];
797
				}
798
				else
799
				{
800
					$with_returning = false;
801
					trigger_error('trying to returning ID Field which is not a Int field', E_USER_ERROR);
802
				}
803
			}
804
		}
805
	}
806
807
	if ($with_returning && !empty($return_var))
808
		return $return_var;
809
}
810
811
/**
812
 * Dummy function really. Doesn't do anything on PostgreSQL.
813
 *
814
 * @param string $db_name The database name
815
 * @param resource $db_connection The database connection
816
 * @return true Always returns true
817
 */
818
function smf_db_select_db($db_name, $db_connection)
819
{
820
	return true;
821
}
822
823
/**
824
 * Get the current version.
825
 *
826
 * @return string The client version
827
 */
828
function smf_db_version()
829
{
830
	$version = pg_version();
831
832
	return $version['client'];
833
}
834
835
/**
836
 * This function tries to work out additional error information from a back trace.
837
 *
838
 * @param string $error_message The error message
839
 * @param string $log_message The message to log
840
 * @param string|bool $error_type What type of error this is
841
 * @param string $file The file the error occurred in
842
 * @param int $line What line of $file the code which generated the error is on
843
 * @return void|array Returns an array with the file and line if $error_type is 'return'
844
 */
845
function smf_db_error_backtrace($error_message, $log_message = '', $error_type = false, $file = null, $line = null)
846
{
847
	if (empty($log_message))
848
		$log_message = $error_message;
849
850
	foreach (debug_backtrace() as $step)
851
	{
852
		// Found it?
853
		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)
854
		{
855
			$log_message .= '<br>Function: ' . $step['function'];
856
			break;
857
		}
858
859
		if (isset($step['line']))
860
		{
861
			$file = $step['file'];
862
			$line = $step['line'];
863
		}
864
	}
865
866
	// A special case - we want the file and line numbers for debugging.
867
	if ($error_type == 'return')
868
		return array($file, $line);
869
870
	// Is always a critical error.
871
	if (function_exists('log_error'))
872
		log_error($log_message, 'critical', $file, $line);
873
874
	if (function_exists('fatal_error'))
875
	{
876
		fatal_error($error_message, $error_type);
877
878
		// Cannot continue...
879
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
880
	}
881
	elseif ($error_type)
882
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), $error_type);
0 ignored issues
show
Bug introduced by
$error_type of type string|true is incompatible with the type integer expected by parameter $error_type of trigger_error(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

882
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), /** @scrutinizer ignore-type */ $error_type);
Loading history...
883
	else
884
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
885
}
886
887
/**
888
 * Escape the LIKE wildcards so that they match the character and not the wildcard.
889
 *
890
 * @param string $string The string to escape
891
 * @param bool $translate_human_wildcards If true, turns human readable wildcards into SQL wildcards.
892
 * @return string The escaped string
893
 */
894
function smf_db_escape_wildcard_string($string, $translate_human_wildcards = false)
895
{
896
	$replacements = array(
897
		'%' => '\%',
898
		'_' => '\_',
899
		'\\' => '\\\\',
900
	);
901
902
	if ($translate_human_wildcards)
903
		$replacements += array(
904
			'*' => '%',
905
		);
906
907
	return strtr($string, $replacements);
908
}
909
910
/**
911
 * Fetches all rows from a result as an array
912
 *
913
 * @param resource $request A PostgreSQL result resource
914
 * @return array An array that contains all rows (records) in the result resource
915
 */
916
function smf_db_fetch_all($request)
917
{
918
	// Return the right row.
919
	$return = @pg_fetch_all($request);
920
	return !empty($return) ? $return : array();
921
}
922
923
/**
924
 * Function to save errors in database in a safe way
925
 *
926
 * @param array with keys in this order id_member, log_time, ip, url, message, session, error_type, file, line
0 ignored issues
show
Bug introduced by
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...
927
 * @return void
928
 */
929
function smf_db_error_insert($error_array)
930
{
931
	global $db_prefix, $db_connection, $db_persist;
932
	static $pg_error_data_prep;
933
934
	// without database we can't do anything
935
	if (empty($db_connection))
936
		return;
937
938
	if (filter_var($error_array[2], FILTER_VALIDATE_IP) === false)
939
		$error_array[2] = null;
940
941
	if(empty($db_persist))
942
	{ // without pooling
943
		if (empty($pg_error_data_prep))
944
			$pg_error_data_prep = pg_prepare($db_connection, 'smf_log_errors',
945
				'INSERT INTO ' . $db_prefix . 'log_errors
946
					(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
947
				VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
948
			);
949
950
		pg_execute($db_connection, 'smf_log_errors', $error_array);
951
	}
952
	else
953
	{ //with pooling
954
		$pg_error_data_prep = pg_prepare($db_connection, '',
955
			'INSERT INTO ' . $db_prefix . 'log_errors
956
				(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
957
			VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
958
		);
959
960
		pg_execute($db_connection, '', $error_array);
961
	}
962
963
}
964
965
/**
966
 * Function which constructs an optimize custom order string
967
 * as an improved alternative to find_in_set()
968
 *
969
 * @param string $field name
970
 * @param array $array_values Field values sequenced in array via order priority. Must cast to int.
971
 * @param boolean $desc default false
972
 * @return string case field when ... then ... end
973
 */
974
function smf_db_custom_order($field, $array_values, $desc = false)
975
{
976
	$return = 'CASE ' . $field . ' ';
977
	$count = count($array_values);
978
	$then = ($desc ? ' THEN -' : ' THEN ');
979
980
	for ($i = 0; $i < $count; $i++)
981
		$return .= 'WHEN ' . (int) $array_values[$i] . $then . $i . ' ';
982
983
	$return .= 'END';
984
	return $return;
985
}
986
987
/**
988
 * Function which return the information if the database supports native replace inserts
989
 *
990
 * @return boolean true or false
991
 */
992
function smf_db_native_replace()
993
{
994
	global $smcFunc;
995
	static $pg_version;
996
	static $replace_support;
997
998
	if (empty($pg_version))
999
	{
1000
		db_extend();
1001
		//pg 9.5 got replace support
1002
		$pg_version = $smcFunc['db_get_version']();
1003
		// if we got a Beta Version
1004
		if (stripos($pg_version, 'beta') !== false)
1005
			$pg_version = substr($pg_version, 0, stripos($pg_version, 'beta')) . '.0';
1006
		// or RC
1007
		if (stripos($pg_version, 'rc') !== false)
1008
			$pg_version = substr($pg_version, 0, stripos($pg_version, 'rc')) . '.0';
1009
1010
		$replace_support = (version_compare($pg_version, '9.5.0', '>=') ? true : false);
1011
	}
1012
1013
	return $replace_support;
1014
}
1015
1016
/**
1017
 * Function which return the information if the database supports cte with recursive
1018
 *
1019
 * @return boolean true or false
1020
 */
1021
function smf_db_cte_support()
1022
{
1023
	return true;
1024
}
1025
1026
/**
1027
 * Function which return the escaped string
1028
 *
1029
 * @param string the unescaped text
0 ignored issues
show
Bug introduced by
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...
1030
 * @param resource $connection = null The connection to use (null to use $db_connection)
1031
 * @return string escaped string
1032
 */
1033
function smf_db_escape_string($string, $connection = null)
1034
{
1035
	global $db_connection;
1036
1037
	return pg_escape_string($connection === null ? $db_connection : $connection, $string);
1038
}
1039
1040
/**
1041
 * Function to return the pg connection error message.
1042
 * Emulating mysqli_connect_error.
1043
 * Since pg_connect() doesn't feed info to pg_last_error, we need to
1044
 * use a try/catch & preserve error info.
1045
 *
1046
 * @return string connection error message
1047
 */
1048
function smf_db_connect_error()
1049
{
1050
	global $pg_connect_error;
1051
1052
	if (empty($pg_connect_error))
1053
		$pg_connect_error = '';
1054
1055
	return $pg_connect_error;
1056
}
1057
1058
/**
1059
 * Function to return the pg connection error number.
1060
 * Emulating mysqli_connect_errno.
1061
 * Since pg_connect() doesn't feed info to pg_last_error, we need to
1062
 * use a try/catch & preserve error info.
1063
 *
1064
 * @return string connection error number
1065
 */
1066
function smf_db_connect_errno()
1067
{
1068
	global $pg_connect_errno;
1069
1070
	if (empty($pg_connect_errno))
1071
		$pg_connect_errno = '';
1072
1073
	return $pg_connect_errno;
1074
}
1075
1076
?>