Passed
Pull Request — release-2.1 (#6262)
by Jeremy
04:04
created

smf_db_initiate()   B

Complexity

Conditions 11
Paths 40

Size

Total Lines 67
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 47
c 1
b 0
f 0
nc 40
nop 6
dl 0
loc 67
rs 7.3166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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;
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
		);
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)
0 ignored issues
show
introduced by
$connection is of type resource, thus it always evaluated to false.
Loading history...
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]) . '\'';
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

157
		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...
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;
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...
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;
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
		'insert_log_search_topics' => array(
334
			'~NOT RLIKE~' => '!~',
335
		),
336
		'insert_log_search_results_no_index' => array(
337
			'~NOT RLIKE~' => '!~',
338
		),
339
		'insert_log_search_results_subject' => array(
340
			'~NOT RLIKE~' => '!~',
341
		),
342
		'profile_board_stats' => array(
343
			'~COUNT\(\*\) \/ MAX\(b.num_posts\)~' => 'CAST(COUNT(*) AS DECIMAL) / CAST(b.num_posts AS DECIMAL)',
344
		),
345
	);
346
347
	// Special optimizer Hints
348
	$query_opt = array(
349
		'load_board_info' => array(
350
			'join_collapse_limit' => 1,
351
		),
352
		'calendar_get_events' => array(
353
			'enable_seqscan' => 'off',
354
		),
355
	);
356
357
	if (isset($replacements[$identifier]))
358
		$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
359
360
	// Limits need to be a little different.
361
	$db_string = preg_replace('~\sLIMIT\s(\d+|{int:.+}),\s*(\d+|{int:.+})\s*$~i', 'LIMIT $2 OFFSET $1', $db_string);
362
363
	if (trim($db_string) == '')
364
		return false;
365
366
	// Comments that are allowed in a query are preg_removed.
367
	static $allowed_comments_from = array(
368
		'~\s+~s',
369
		'~/\*!40001 SQL_NO_CACHE \*/~',
370
		'~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~',
371
		'~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~',
372
	);
373
	static $allowed_comments_to = array(
374
		' ',
375
		'',
376
		'',
377
		'',
378
	);
379
380
	// One more query....
381
	$db_count = !isset($db_count) ? 1 : $db_count + 1;
382
	$db_replace_result = 0;
383
384
	if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override']))
385
		smf_db_error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__);
386
387
	if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false))
388
	{
389
		// Pass some values to the global space for use in the callback function.
390
		$db_callback = array($db_values, $connection);
391
392
		// Inject the values passed to this function.
393
		$db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', 'smf_db_replacement__callback', $db_string);
394
395
		// This shouldn't be residing in global space any longer.
396
		$db_callback = array();
397
	}
398
399
	// First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over.
400
	if (empty($modSettings['disableQueryCheck']))
401
	{
402
		$clean = '';
403
		$old_pos = 0;
404
		$pos = -1;
405
		// Remove the string escape for better runtime
406
		$db_string_1 = str_replace('\'\'', '', $db_string);
407
		while (true)
408
		{
409
			$pos = strpos($db_string_1, '\'', $pos + 1);
410
			if ($pos === false)
411
				break;
412
			$clean .= substr($db_string_1, $old_pos, $pos - $old_pos);
413
414
			while (true)
415
			{
416
				$pos1 = strpos($db_string_1, '\'', $pos + 1);
417
				$pos2 = strpos($db_string_1, '\\', $pos + 1);
418
				if ($pos1 === false)
419
					break;
420
				elseif ($pos2 === false || $pos2 > $pos1)
421
				{
422
					$pos = $pos1;
423
					break;
424
				}
425
426
				$pos = $pos2 + 1;
427
			}
428
			$clean .= ' %s ';
429
430
			$old_pos = $pos + 1;
431
		}
432
		$clean .= substr($db_string_1, $old_pos);
433
		$clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean)));
434
435
		// Comments?  We don't use comments in our queries, we leave 'em outside!
436
		if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false)
437
			$fail = true;
438
		// Trying to change passwords, slow us down, or something?
439
		elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0)
440
			$fail = true;
441
		elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0)
442
			$fail = true;
443
444
		if (!empty($fail) && function_exists('log_error'))
445
			smf_db_error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__);
446
	}
447
448
	// Set optimize stuff
449
	if (isset($query_opt[$identifier]))
450
	{
451
		$query_hints = $query_opt[$identifier];
452
		$query_hints_set = '';
453
		if (isset($query_hints['join_collapse_limit']))
454
		{
455
			$query_hints_set .= 'SET LOCAL join_collapse_limit = ' . $query_hints['join_collapse_limit'] . ';';
456
		}
457
		if (isset($query_hints['enable_seqscan']))
458
		{
459
			$query_hints_set .= 'SET LOCAL enable_seqscan = ' . $query_hints['enable_seqscan'] . ';';
460
		}
461
462
		$db_string = $query_hints_set . $db_string;
463
	}
464
465
	// Debugging.
466
	if (isset($db_show_debug) && $db_show_debug === true)
467
	{
468
		// Get the file and line number this function was called.
469
		list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
470
471
		// Initialize $db_cache if not already initialized.
472
		if (!isset($db_cache))
473
			$db_cache = array();
474
475
		if (!empty($_SESSION['debug_redirect']))
476
		{
477
			$db_cache = array_merge($_SESSION['debug_redirect'], $db_cache);
478
			$db_count = count($db_cache) + 1;
479
			$_SESSION['debug_redirect'] = array();
480
		}
481
482
		// Don't overload it.
483
		$db_cache[$db_count]['q'] = $db_count < 50 ? $db_string : '...';
484
		$db_cache[$db_count]['f'] = $file;
485
		$db_cache[$db_count]['l'] = $line;
486
		$db_cache[$db_count]['s'] = ($st = microtime(true)) - TIME_START;
487
	}
488
489
	$db_last_result = @pg_query($connection, $db_string);
490
491
	if ($db_last_result === false && empty($db_values['db_error_skip']))
492
		$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

492
		$db_last_result = smf_db_error($db_string, /** @scrutinizer ignore-type */ $connection);
Loading history...
493
494
	// Debugging.
495
	if (isset($db_show_debug) && $db_show_debug === true)
496
		$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...
497
498
	return $db_last_result;
499
}
500
501
/**
502
 * Returns the amount of affected rows for a query.
503
 *
504
 * @param mixed $result
505
 *
506
 * @return int
507
 *
508
 */
509
function smf_db_affected_rows($result = null)
510
{
511
	global $db_last_result, $db_replace_result;
512
513
	if ($db_replace_result)
514
		return $db_replace_result;
515
	elseif ($result === null && !$db_last_result)
516
		return 0;
517
518
	return pg_affected_rows($result === null ? $db_last_result : $result);
519
}
520
521
/**
522
 * Gets the ID of the most recently inserted row.
523
 *
524
 * @param string $table The table (only used for Postgres)
525
 * @param string $field = null The specific field (not used here)
526
 * @param resource $connection = null The connection (if null, $db_connection is used) (not used here)
527
 * @return int The ID of the most recently inserted row
528
 */
529
function smf_db_insert_id($table, $field = null, $connection = null)
530
{
531
	global $smcFunc, $db_prefix;
532
533
	$table = str_replace('{db_prefix}', $db_prefix, $table);
534
535
	// Try get the last ID for the auto increment field.
536
	$request = $smcFunc['db_query']('', 'SELECT CURRVAL(\'' . $table . '_seq\') AS insertID',
537
		array(
538
		)
539
	);
540
	if (!$request)
541
		return false;
542
	list ($lastID) = $smcFunc['db_fetch_row']($request);
543
	$smcFunc['db_free_result']($request);
544
545
	return $lastID;
546
}
547
548
/**
549
 * Do a transaction.
550
 *
551
 * @param string $type The step to perform (i.e. 'begin', 'commit', 'rollback')
552
 * @param resource $connection The connection to use (if null, $db_connection is used)
553
 * @return bool True if successful, false otherwise
554
 */
555
function smf_db_transaction($type = 'commit', $connection = null)
556
{
557
	global $db_connection;
558
559
	// Decide which connection to use
560
	$connection = $connection === null ? $db_connection : $connection;
561
562
	if ($type == 'begin')
563
		return @pg_query($connection, 'BEGIN');
564
	elseif ($type == 'rollback')
565
		return @pg_query($connection, 'ROLLBACK');
566
	elseif ($type == 'commit')
567
		return @pg_query($connection, 'COMMIT');
568
569
	return false;
570
}
571
572
/**
573
 * Database error!
574
 * Backtrace, log, try to fix.
575
 *
576
 * @param string $db_string The DB string
577
 * @param resource $connection The connection to use (if null, $db_connection is used)
578
 */
579
function smf_db_error($db_string, $connection = null)
580
{
581
	global $txt, $context, $modSettings;
582
	global $db_connection;
583
	global $db_show_debug;
584
585
	// We'll try recovering the file and line number the original db query was called from.
586
	list ($file, $line) = smf_db_error_backtrace('', '', 'return', __FILE__, __LINE__);
587
588
	// Decide which connection to use
589
	$connection = $connection === null ? $db_connection : $connection;
590
591
	// This is the error message...
592
	$query_error = @pg_last_error($connection);
593
594
	// Log the error.
595
	if (function_exists('log_error'))
596
		log_error($txt['database_error'] . ': ' . $query_error . (!empty($modSettings['enableErrorQueryLogging']) ? "\n\n" . $db_string : ''), 'database', $file, $line);
597
598
	// Nothing's defined yet... just die with it.
599
	if (empty($context) || empty($txt))
600
		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...
601
602
	// Show an error message, if possible.
603
	$context['error_title'] = $txt['database_error'];
604
	if (allowedTo('admin_forum'))
605
		$context['error_message'] = nl2br($query_error) . '<br>' . $txt['file'] . ': ' . $file . '<br>' . $txt['line'] . ': ' . $line;
606
	else
607
		$context['error_message'] = $txt['try_again'];
608
609
	if (allowedTo('admin_forum') && isset($db_show_debug) && $db_show_debug === true)
610
	{
611
		$context['error_message'] .= '<br><br>' . nl2br($db_string);
612
	}
613
614
	// It's already been logged... don't log it again.
615
	fatal_error($context['error_message'], false);
616
}
617
618
/**
619
 * Inserts data into a table
620
 *
621
 * @param string $method The insert method - can be 'replace', 'ignore' or 'insert'
622
 * @param string $table The table we're inserting the data into
623
 * @param array $columns An array of the columns we're inserting the data into. Should contain 'column' => 'datatype' pairs
624
 * @param array $data The data to insert
625
 * @param array $keys The keys for the table, needs to be not empty on replace mode
626
 * @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...
627
 * @param resource $connection The connection to use (if null, $db_connection is used)
628
 * @return mixed value of the first key, behavior based on returnmode. null if no data.
629
 */
630
function smf_db_insert($method = 'replace', $table, $columns, $data, $keys, $returnmode = 0, $connection = null)
631
{
632
	global $smcFunc, $db_connection, $db_prefix;
633
634
	$connection = $connection === null ? $db_connection : $connection;
635
636
	$replace = '';
637
638
	if (empty($data))
639
		return;
640
641
	if (!is_array($data[array_rand($data)]))
642
		$data = array($data);
643
644
	// Replace the prefix holder with the actual prefix.
645
	$table = str_replace('{db_prefix}', $db_prefix, $table);
646
647
	// Sanity check for replace is key part of the columns array
648
	if ($method == 'replace')
649
	{
650
		if (empty($keys))
651
			smf_db_error_backtrace('When using the replace mode, the key column is a required entry.',
652
				'Change the method of db insert to insert or add the pk field to the key array', E_USER_ERROR, __FILE__, __LINE__);
653
		if (count(array_intersect_key($columns, array_flip($keys))) !== count($keys))
654
			smf_db_error_backtrace('Primary Key field missing in insert call',
655
				'Change the method of db insert to insert or add the pk field to the columns array', E_USER_ERROR, __FILE__, __LINE__);
656
	}
657
658
	// PostgreSQL doesn't support replace: we implement a MySQL-compatible behavior instead
659
	if ($method == 'replace' || $method == 'ignore')
660
	{
661
		$key_str = '';
662
		$col_str = '';
663
		$replace_support = $smcFunc['db_native_replace']();
664
665
		$count = 0;
666
		$where = '';
667
		$count_pk = 0;
668
669
		If ($replace_support)
670
		{
671
			foreach ($columns as $columnName => $type)
672
			{
673
				//check pk fiel
674
				IF (in_array($columnName, $keys))
675
				{
676
					$key_str .= ($count_pk > 0 ? ',' : '');
677
					$key_str .= $columnName;
678
					$count_pk++;
679
				}
680
				elseif ($method == 'replace') //normal field
681
				{
682
					$col_str .= ($count > 0 ? ',' : '');
683
					$col_str .= $columnName . ' = EXCLUDED.' . $columnName;
684
					$count++;
685
				}
686
			}
687
			if ($method == 'replace')
688
				$replace = ' ON CONFLICT (' . $key_str . ') DO UPDATE SET ' . $col_str;
689
			else
690
				$replace = ' ON CONFLICT (' . $key_str . ') DO NOTHING';
691
		}
692
		elseif ($method == 'replace')
693
		{
694
			foreach ($columns as $columnName => $type)
695
			{
696
				// Are we restricting the length?
697
				if (strpos($type, 'string-') !== false)
698
					$actualType = sprintf($columnName . ' = SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $count);
699
				else
700
					$actualType = sprintf($columnName . ' = {%1$s:%2$s}, ', $type, $count);
701
702
				// A key? That's what we were looking for.
703
				if (in_array($columnName, $keys))
704
					$where .= (empty($where) ? '' : ' AND ') . substr($actualType, 0, -2);
705
				$count++;
706
			}
707
708
			// Make it so.
709
			if (!empty($where) && !empty($data))
710
			{
711
				foreach ($data as $k => $entry)
712
				{
713
					$smcFunc['db_query']('', '
714
						DELETE FROM ' . $table .
715
						' WHERE ' . $where,
716
						$entry, $connection
717
					);
718
				}
719
			}
720
		}
721
	}
722
723
	$returning = '';
724
	$with_returning = false;
725
	// lets build the returning string, mysql allow only in normal mode
726
	if (!empty($keys) && (count($keys) > 0) && $returnmode > 0)
727
	{
728
		// we only take the first key
729
		$returning = ' RETURNING ' . $keys[0];
730
		$with_returning = true;
731
	}
732
733
	if (!empty($data))
734
	{
735
		// Create the mold for a single row insert.
736
		$insertData = '(';
737
		foreach ($columns as $columnName => $type)
738
		{
739
			// Are we restricting the length?
740
			if (strpos($type, 'string-') !== false)
741
				$insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName);
742
			else
743
				$insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName);
744
		}
745
		$insertData = substr($insertData, 0, -2) . ')';
746
747
		// Create an array consisting of only the columns.
748
		$indexed_columns = array_keys($columns);
749
750
		// Here's where the variables are injected to the query.
751
		$insertRows = array();
752
		foreach ($data as $dataRow)
753
			$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

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

866
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''), /** @scrutinizer ignore-type */ $error_type);
Loading history...
867
	else
868
		trigger_error($error_message . ($line !== null ? '<em>(' . basename($file) . '-' . $line . ')</em>' : ''));
869
}
870
871
/**
872
 * Escape the LIKE wildcards so that they match the character and not the wildcard.
873
 *
874
 * @param string $string The string to escape
875
 * @param bool $translate_human_wildcards If true, turns human readable wildcards into SQL wildcards.
876
 * @return string The escaped string
877
 */
878
function smf_db_escape_wildcard_string($string, $translate_human_wildcards = false)
879
{
880
	$replacements = array(
881
		'%' => '\%',
882
		'_' => '\_',
883
		'\\' => '\\\\',
884
	);
885
886
	if ($translate_human_wildcards)
887
		$replacements += array(
888
			'*' => '%',
889
		);
890
891
	return strtr($string, $replacements);
892
}
893
894
/**
895
 * Fetches all rows from a result as an array
896
 *
897
 * @param resource $request A PostgreSQL result resource
898
 * @return array An array that contains all rows (records) in the result resource
899
 */
900
function smf_db_fetch_all($request)
901
{
902
	// Return the right row.
903
	$return = @pg_fetch_all($request);
904
	return !empty($return) ? $return : array();
905
}
906
907
/**
908
 * Function to save errors in database in a safe way
909
 *
910
 * @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...
911
 * @return void
912
 */
913
function smf_db_error_insert($error_array)
914
{
915
	global $db_prefix, $db_connection, $db_persist;
916
	static $pg_error_data_prep;
917
918
	// without database we can't do anything
919
	if (empty($db_connection))
920
		return;
921
922
	if (filter_var($error_array[2], FILTER_VALIDATE_IP) === false)
923
		$error_array[2] = null;
924
925
	if(empty($db_persist))
926
	{ // without pooling
927
		if (empty($pg_error_data_prep))
928
			$pg_error_data_prep = pg_prepare($db_connection, 'smf_log_errors',
929
				'INSERT INTO ' . $db_prefix . 'log_errors
930
					(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
931
				VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
932
			);
933
934
		pg_execute($db_connection, 'smf_log_errors', $error_array);
935
	}
936
	else
937
	{ //with pooling
938
		$pg_error_data_prep = pg_prepare($db_connection, '',
939
			'INSERT INTO ' . $db_prefix . 'log_errors
940
				(id_member, log_time, ip, url, message, session, error_type, file, line, backtrace)
941
			VALUES( $1, $2, $3, $4, $5, $6, $7, $8,	$9, $10)'
942
		);
943
944
		pg_execute($db_connection, '', $error_array);
945
	}
946
947
}
948
949
/**
950
 * Function which constructs an optimize custom order string
951
 * as an improved alternative to find_in_set()
952
 *
953
 * @param string $field name
954
 * @param array $array_values Field values sequenced in array via order priority. Must cast to int.
955
 * @param boolean $desc default false
956
 * @return string case field when ... then ... end
957
 */
958
function smf_db_custom_order($field, $array_values, $desc = false)
959
{
960
	$return = 'CASE ' . $field . ' ';
961
	$count = count($array_values);
962
	$then = ($desc ? ' THEN -' : ' THEN ');
963
964
	for ($i = 0; $i < $count; $i++)
965
		$return .= 'WHEN ' . (int) $array_values[$i] . $then . $i . ' ';
966
967
	$return .= 'END';
968
	return $return;
969
}
970
971
/**
972
 * Function which return the information if the database supports native replace inserts
973
 *
974
 * @return boolean true or false
975
 */
976
function smf_db_native_replace()
977
{
978
	global $smcFunc;
979
	static $pg_version;
980
	static $replace_support;
981
982
	if (empty($pg_version))
983
	{
984
		db_extend();
985
		//pg 9.5 got replace support
986
		$pg_version = $smcFunc['db_get_version']();
987
		// if we got a Beta Version
988
		if (stripos($pg_version, 'beta') !== false)
989
			$pg_version = substr($pg_version, 0, stripos($pg_version, 'beta')) . '.0';
990
		// or RC
991
		if (stripos($pg_version, 'rc') !== false)
992
			$pg_version = substr($pg_version, 0, stripos($pg_version, 'rc')) . '.0';
993
994
		$replace_support = (version_compare($pg_version, '9.5.0', '>=') ? true : false);
995
	}
996
997
	return $replace_support;
998
}
999
1000
/**
1001
 * Function which return the information if the database supports cte with recursive
1002
 *
1003
 * @return boolean true or false
1004
 */
1005
function smf_db_cte_support()
1006
{
1007
	return true;
1008
}
1009
1010
/**
1011
 * Function which return the escaped string
1012
 *
1013
 * @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...
1014
 * @param resource $connection = null The connection to use (null to use $db_connection)
1015
 * @return string escaped string
1016
 */
1017
function smf_db_escape_string($string, $connection = null)
1018
{
1019
	global $db_connection;
1020
1021
	return pg_escape_string($connection === null ? $db_connection : $connection, $string);
1022
}
1023
1024
?>