GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( d80144...902697 )
by gyeong-won
12:23
created

DBMysql::queryPageLimit()   F

Complexity

Conditions 19
Paths 2304

Size

Total Lines 89
Code Lines 54

Duplication

Lines 31
Ratio 34.83 %

Importance

Changes 0
Metric Value
cc 19
eloc 54
nc 2304
nop 4
dl 31
loc 89
rs 2
c 0
b 0
f 0

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
/* Copyright (C) NAVER <http://www.navercorp.com> */
3
4
/**
5
 * Class to use MySQL DBMS
6
 * mysql handling class
7
 *
8
 * Does not use prepared statements, since mysql driver does not support them
9
 *
10
 * @author NAVER ([email protected])
11
 * @package /classes/db
12
 * @version 0.1
13
 */
14
class DBMysql extends DB
15
{
16
17
	/**
18
	 * prefix of a tablename (One or more XEs can be installed in a single DB)
19
	 * @var string
20
	 */
21
	var $prefix = 'xe_'; // / <
22
	var $comment_syntax = '/* %s */';
23
24
	/**
25
	 * Column type used in MySQL
26
	 *
27
	 * Becasue a common column type in schema/query xml is used for colum_type,
28
	 * it should be replaced properly for each DBMS
29
	 * @var array
30
	 */
31
	var $column_type = array(
32
		'bignumber' => 'bigint',
33
		'number' => 'bigint',
34
		'varchar' => 'varchar',
35
		'char' => 'char',
36
		'text' => 'text',
37
		'bigtext' => 'longtext',
38
		'date' => 'varchar(14)',
39
		'float' => 'float',
40
	);
41
42
	/**
43
	 * Constructor
44
	 * @return void
45
	 */
46
	function DBMysql()
0 ignored issues
show
Coding Style Best Practice introduced by
Please use __construct() instead of a PHP4-style constructor that is named after the class.
Loading history...
47
	{
48
		$this->_setDBInfo();
49
		$this->_connect();
50
	}
51
52
	/**
53
	 * Create an instance of this class
54
	 * @return DBMysql return DBMysql object instance
55
	 */
56
	function create()
57
	{
58
		return new DBMysql;
59
	}
60
61
	/**
62
	 * DB Connect
63
	 * this method is private
64
	 * @param array $connection connection's value is db_hostname, db_port, db_database, db_userid, db_password
65
	 * @return resource
66
	 */
67
	function __connect($connection)
68
	{
69
		// Ignore if no DB information exists
70
		if(strpos($connection["db_hostname"], ':') === false && $connection["db_port"])
71
		{
72
			$connection["db_hostname"] .= ':' . $connection["db_port"];
73
		}
74
75
		// Attempt to connect
76
		$result = @mysql_connect($connection["db_hostname"], $connection["db_userid"], $connection["db_password"]);
77
		if(!$result)
78
		{
79
			exit('XE cannot connect to DB.');
80
		}
81
82
		if(mysql_error())
83
		{
84
			$this->setError(mysql_errno(), mysql_error());
85
			return;
86
		}
87
		// Error appears if the version is lower than 4.1
88
		if(version_compare(mysql_get_server_info($result), '4.1', '<'))
89
		{
90
			$this->setError(-1, 'XE cannot be installed under the version of mysql 4.1. Current mysql version is ' . mysql_get_server_info());
91
			return;
92
		}
93
		// select db
94
		@mysql_select_db($connection["db_database"], $result);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
95
		if(mysql_error())
96
		{
97
			$this->setError(mysql_errno(), mysql_error());
98
			return;
99
		}
100
101
		return $result;
102
	}
103
104
	/**
105
	 * If have a task after connection, add a taks in this method
106
	 * this method is private
107
	 * @param resource $connection
108
	 * @return void
109
	 */
110
	function _afterConnect($connection)
111
	{
112
		// Set utf8 if a database is MySQL
113
		$this->_query("set names 'utf8'", $connection);
114
	}
115
116
	/**
117
	 * DB disconnection
118
	 * this method is private
119
	 * @param resource $connection
120
	 * @return void
121
	 */
122
	function _close($connection)
123
	{
124
		@mysql_close($connection);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
125
	}
126
127
	/**
128
	 * Handles quatation of the string variables from the query
129
	 * @param string $string
130
	 * @return string
131
	 */
132 View Code Duplication
	function addQuotes($string)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
	{
134
		if(version_compare(PHP_VERSION, "5.4.0", "<") && get_magic_quotes_gpc())
135
		{
136
			$string = stripslashes(str_replace("\\", "\\\\", $string));
137
		}
138
		if(!is_numeric($string))
139
		{
140
			$string = @mysql_real_escape_string($string);
141
		}
142
		return $string;
143
	}
144
145
	/**
146
	 * DB transaction start
147
	 * this method is private
148
	 * @return boolean
149
	 */
150
	function _begin($transactionLevel = 0)
151
	{
152
		return true;
153
	}
154
155
	/**
156
	 * DB transaction rollback
157
	 * this method is private
158
	 * @return boolean
159
	 */
160
	function _rollback($transactionLevel = 0)
161
	{
162
		return true;
163
	}
164
165
	/**
166
	 * DB transaction commit
167
	 * this method is private
168
	 * @return boolean
169
	 */
170
	function _commit()
171
	{
172
		return true;
173
	}
174
175
	/**
176
	 * Execute the query
177
	 * this method is private
178
	 * @param string $query
179
	 * @param resource $connection
180
	 * @return resource
181
	 */
182 View Code Duplication
	function __query($query, $connection)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
	{
184
		if(!$connection)
185
		{
186
			exit('XE cannot handle DB connection.');
187
		}
188
		// Run the query statement
189
		$result = mysql_query($query, $connection);
190
		// Error Check
191
		if(mysql_error($connection))
192
		{
193
			$this->setError(mysql_errno($connection), mysql_error($connection));
194
		}
195
		// Return result
196
		return $result;
197
	}
198
199
	/**
200
	 * Fetch the result
201
	 * @param resource $result
202
	 * @param int|NULL $arrayIndexEndValue
203
	 * @return array
204
	 */
205
	function _fetch($result, $arrayIndexEndValue = NULL)
206
	{
207
		$output = array();
208
		if(!$this->isConnected() || $this->isError() || !$result)
209
		{
210
			return $output;
211
		}
212
		while($tmp = $this->db_fetch_object($result))
213
		{
214
			if($arrayIndexEndValue)
0 ignored issues
show
Bug Best Practice introduced by
The expression $arrayIndexEndValue of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
215
			{
216
				$output[$arrayIndexEndValue--] = $tmp;
217
			}
218
			else
219
			{
220
				$output[] = $tmp;
221
			}
222
		}
223
		if(count($output) == 1)
224
		{
225
			if(isset($arrayIndexEndValue))
226
			{
227
				return $output;
228
			}
229
			else
230
			{
231
				return $output[0];
232
			}
233
		}
234
		$this->db_free_result($result);
235
		return $output;
236
	}
237
238
	/**
239
	 * Return the sequence value incremented by 1
240
	 * Auto_increment column only used in the sequence table
241
	 * @return int
242
	 */
243
	function getNextSequence()
244
	{
245
		$query = sprintf("insert into `%ssequence` (seq) values ('0')", $this->prefix);
246
		$this->_query($query);
247
		$sequence = $this->db_insert_id();
248
		if($sequence % 10000 == 0)
249
		{
250
			$query = sprintf("delete from  `%ssequence` where seq < %d", $this->prefix, $sequence);
251
			$this->_query($query);
252
		}
253
254
		return $sequence;
255
	}
256
257
	/**
258
	 * Function to obtain mysql old password(mysql only)
259
	 * @param string $password input password
260
	 * @param string $saved_password saved password in DBMS
261
	 * @return boolean
262
	 */
263
	function isValidOldPassword($password, $saved_password)
264
	{
265
		$query = sprintf("select password('%s') as password, old_password('%s') as old_password", $this->addQuotes($password), $this->addQuotes($password));
266
		$result = $this->_query($query);
267
		$tmp = $this->_fetch($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->_query($query) on line 266 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
268
		if($tmp->password === $saved_password || $tmp->old_password === $saved_password)
269
		{
270
			return true;
271
		}
272
		return false;
273
	}
274
275
	/**
276
	 * Check a table exists status
277
	 * @param string $target_name
278
	 * @return boolean
279
	 */
280
	function isTableExists($target_name)
281
	{
282
		$query = sprintf("show tables like '%s%s'", $this->prefix, $this->addQuotes($target_name));
283
		$result = $this->_query($query);
284
		$tmp = $this->_fetch($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->_query($query) on line 283 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
285
		if(!$tmp)
0 ignored issues
show
Bug Best Practice introduced by
The expression $tmp of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
286
		{
287
			return false;
288
		}
289
		return true;
290
	}
291
292
	/**
293
	 * Add a column to the table
294
	 * @param string $table_name table name
295
	 * @param string $column_name column name
296
	 * @param string $type column type, default value is 'number'
297
	 * @param int $size column size
298
	 * @param string|int $default default value
299
	 * @param boolean $notnull not null status, default value is false
300
	 * @return void
301
	 */
302 View Code Duplication
	function addColumn($table_name, $column_name, $type = 'number', $size = '', $default = null, $notnull = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
303
	{
304
		$type = $this->column_type[$type];
305
		if(strtoupper($type) == 'INTEGER')
306
		{
307
			$size = '';
308
		}
309
310
		$query = sprintf("alter table `%s%s` add `%s` ", $this->prefix, $table_name, $column_name);
311
		if($size)
312
		{
313
			$query .= sprintf(" %s(%s) ", $type, $size);
314
		}
315
		else
316
		{
317
			$query .= sprintf(" %s ", $type);
318
		}
319
		if(isset($default))
320
		{
321
			$query .= sprintf(" default '%s' ", $default);
322
		}
323
		if($notnull)
324
		{
325
			$query .= " not null ";
326
		}
327
328
		return $this->_query($query);
329
	}
330
331
	/**
332
	 * Drop a column from the table
333
	 * @param string $table_name table name
334
	 * @param string $column_name column name
335
	 * @return void
336
	 */
337
	function dropColumn($table_name, $column_name)
338
	{
339
		$query = sprintf("alter table `%s%s` drop `%s` ", $this->prefix, $table_name, $column_name);
340
		$this->_query($query);
341
	}
342
343
	/**
344
	 * Check column exist status of the table
345
	 * @param string $table_name table name
346
	 * @param string $column_name column name
347
	 * @return boolean
348
	 */
349
	function isColumnExists($table_name, $column_name)
350
	{
351
		$query = sprintf("show fields from `%s%s`", $this->prefix, $table_name);
352
		$result = $this->_query($query);
353
		if($this->isError())
354
		{
355
			return;
356
		}
357
		$output = $this->_fetch($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->_query($query) on line 352 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
358
		if($output)
0 ignored issues
show
Bug Best Practice introduced by
The expression $output of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
359
		{
360
			$column_name = strtolower($column_name);
361
			foreach($output as $key => $val)
362
			{
363
				$name = strtolower($val->Field);
364
				if($column_name == $name)
365
				{
366
					return true;
367
				}
368
			}
369
		}
370
		return false;
371
	}
372
373
	/**
374
	 * Add an index to the table
375
	 * $target_columns = array(col1, col2)
376
	 * $is_unique? unique : none
377
	 * @param string $table_name table name
378
	 * @param string $index_name index name
379
	 * @param string|array $target_columns target column or columns
380
	 * @param boolean $is_unique
381
	 * @return void
382
	 */
383 View Code Duplication
	function addIndex($table_name, $index_name, $target_columns, $is_unique = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
384
	{
385
		if(!is_array($target_columns))
386
		{
387
			$target_columns = array($target_columns);
388
		}
389
390
		$query = sprintf("alter table `%s%s` add %s index `%s` (%s);", $this->prefix, $table_name, $is_unique ? 'unique' : '', $index_name, implode(',', $target_columns));
391
		$this->_query($query);
392
	}
393
394
	/**
395
	 * Drop an index from the table
396
	 * @param string $table_name table name
397
	 * @param string $index_name index name
398
	 * @param boolean $is_unique
399
	 * @return void
400
	 */
401
	function dropIndex($table_name, $index_name, $is_unique = false)
0 ignored issues
show
Unused Code introduced by
The parameter $is_unique is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
402
	{
403
		$query = sprintf("alter table `%s%s` drop index `%s`", $this->prefix, $table_name, $index_name);
404
		$this->_query($query);
405
	}
406
407
	/**
408
	 * Check index status of the table
409
	 * @param string $table_name table name
410
	 * @param string $index_name index name
411
	 * @return boolean
412
	 */
413
	function isIndexExists($table_name, $index_name)
414
	{
415
		//$query = sprintf("show indexes from %s%s where key_name = '%s' ", $this->prefix, $table_name, $index_name);
416
		$query = sprintf("show indexes from `%s%s`", $this->prefix, $table_name);
417
		$result = $this->_query($query);
418
		if($this->isError())
419
		{
420
			return;
421
		}
422
		$output = $this->_fetch($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->_query($query) on line 417 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
423
		if(!$output)
0 ignored issues
show
Bug Best Practice introduced by
The expression $output of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
424
		{
425
			return;
426
		}
427
		if(!is_array($output))
428
		{
429
			$output = array($output);
430
		}
431
432
		for($i = 0; $i < count($output); $i++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
433
		{
434
			if($output[$i]->Key_name == $index_name)
435
			{
436
				return true;
437
			}
438
		}
439
		return false;
440
	}
441
442
	/**
443
	 * Creates a table by using xml contents
444
	 * @param string $xml_doc xml schema contents
445
	 * @return void|object
446
	 */
447
	function createTableByXml($xml_doc)
448
	{
449
		return $this->_createTable($xml_doc);
450
	}
451
452
	/**
453
	 * Creates a table by using xml file path
454
	 * @param string $file_name xml schema file path
455
	 * @return void|object
456
	 */
457
	function createTableByXmlFile($file_name)
458
	{
459
		if(!file_exists($file_name))
460
		{
461
			return;
462
		}
463
		// read xml file
464
		$buff = FileHandler::readFile($file_name);
465
		return $this->_createTable($buff);
466
	}
467
468
	/**
469
	 * Create table by using the schema xml
470
	 *
471
	 * type : number, varchar, tinytext, text, bigtext, char, date, \n
472
	 * opt : notnull, default, size\n
473
	 * index : primary key, index, unique\n
474
	 * @param string $xml_doc xml schema contents
475
	 * @return void|object
476
	 */
477
	function _createTable($xml_doc)
478
	{
479
		// xml parsing
480
		$oXml = new XmlParser();
481
		$xml_obj = $oXml->parse($xml_doc);
482
		// Create a table schema
483
		$table_name = $xml_obj->table->attrs->name;
484
		if($this->isTableExists($table_name))
485
		{
486
			return;
487
		}
488
		$table_name = $this->prefix . $table_name;
489
490
		if(!is_array($xml_obj->table->column))
491
		{
492
			$columns[] = $xml_obj->table->column;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$columns was never initialized. Although not strictly required by PHP, it is generally a good practice to add $columns = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
493
		}
494
		else
495
		{
496
			$columns = $xml_obj->table->column;
497
		}
498
499
		$primary_list = array();
500
		$unique_list = array();
501
		$index_list = array();
502
503
		foreach($columns as $column)
504
		{
505
			$name = $column->attrs->name;
506
			$type = $column->attrs->type;
507
			$size = $column->attrs->size;
508
			$notnull = $column->attrs->notnull;
509
			$primary_key = $column->attrs->primary_key;
510
			$index = $column->attrs->index;
511
			$unique = $column->attrs->unique;
512
			$default = $column->attrs->default;
513
			$auto_increment = $column->attrs->auto_increment;
514
515
			$column_schema[] = sprintf('`%s` %s%s %s %s %s', $name, $this->column_type[$type], $size ? '(' . $size . ')' : '', isset($default) ? "default '" . $default . "'" : '', $notnull ? 'not null' : '', $auto_increment ? 'auto_increment' : '');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$column_schema was never initialized. Although not strictly required by PHP, it is generally a good practice to add $column_schema = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
516
517
			if($primary_key)
518
			{
519
				$primary_list[] = $name;
520
			}
521
			else if($unique)
522
			{
523
				$unique_list[$unique][] = $name;
524
			}
525
			else if($index)
526
			{
527
				$index_list[$index][] = $name;
528
			}
529
		}
530
531
		if(count($primary_list))
532
		{
533
			$column_schema[] = sprintf("primary key (%s)", '`' . implode($primary_list, '`,`') . '`');
0 ignored issues
show
Bug introduced by
The variable $column_schema does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
534
		}
535
536
		if(count($unique_list))
537
		{
538
			foreach($unique_list as $key => $val)
539
			{
540
				$column_schema[] = sprintf("unique %s (%s)", $key, '`' . implode($val, '`,`') . '`');
541
			}
542
		}
543
544
		if(count($index_list))
545
		{
546
			foreach($index_list as $key => $val)
547
			{
548
				$column_schema[] = sprintf("index %s (%s)", $key, '`' . implode($val, '`,`') . '`');
549
			}
550
		}
551
552
		$schema = sprintf('create table `%s` (%s%s) %s;', $this->addQuotes($table_name), "\n", implode($column_schema, ",\n"), "ENGINE = MYISAM  CHARACTER SET utf8 COLLATE utf8_general_ci");
553
554
		$output = $this->_query($schema);
555
		if(!$output)
556
			return false;
557
	}
558
559
	/**
560
	 * Handles insertAct
561
	 * @param Object $queryObject
562
	 * @param boolean $with_values
563
	 * @return resource
564
	 */
565 View Code Duplication
	function _executeInsertAct($queryObject, $with_values = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
566
	{
567
		$query = $this->getInsertSql($queryObject, $with_values, true);
568
		$query .= (__DEBUG_QUERY__ & 1 && $this->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : '';
0 ignored issues
show
Bug introduced by
The property query_id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
569
		if(is_a($query, 'Object'))
570
		{
571
			return;
572
		}
573
		return $this->_query($query);
574
	}
575
576
	/**
577
	 * Handles updateAct
578
	 * @param Object $queryObject
579
	 * @param boolean $with_values
580
	 * @return resource
581
	 */
582 View Code Duplication
	function _executeUpdateAct($queryObject, $with_values = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
583
	{
584
		$query = $this->getUpdateSql($queryObject, $with_values, true);
585
		if(is_a($query, 'Object'))
586
		{
587
			if(!$query->toBool()) return $query;
588
			else return;
589
		}
590
591
		$query .= (__DEBUG_QUERY__ & 1 && $this->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : '';
592
593
594
		return $this->_query($query);
595
	}
596
597
	/**
598
	 * Handles deleteAct
599
	 * @param Object $queryObject
600
	 * @param boolean $with_values
601
	 * @return resource
602
	 */
603 View Code Duplication
	function _executeDeleteAct($queryObject, $with_values = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
604
	{
605
		$query = $this->getDeleteSql($queryObject, $with_values, true);
606
		$query .= (__DEBUG_QUERY__ & 1 && $this->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : '';
607
		if(is_a($query, 'Object'))
608
		{
609
			return;
610
		}
611
		return $this->_query($query);
612
	}
613
614
	/**
615
	 * Handle selectAct
616
	 * In order to get a list of pages easily when selecting \n
617
	 * it supports a method as navigation
618
	 * @param Object $queryObject
619
	 * @param resource $connection
620
	 * @param boolean $with_values
621
	 * @return Object
622
	 */
623
	function _executeSelectAct($queryObject, $connection = null, $with_values = true)
624
	{
625
		$limit = $queryObject->getLimit();
626
		$result = NULL;
627
		if($limit && $limit->isPageHandler())
628
		{
629
			return $this->queryPageLimit($queryObject, $result, $connection, $with_values);
0 ignored issues
show
Documentation introduced by
$result is of type null, but the function expects a resource.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Bug introduced by
It seems like $connection defined by parameter $connection on line 623 can also be of type null; however, DBMysql::queryPageLimit() does only seem to accept resource, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
630
		}
631
		else
632
		{
633
			$query = $this->getSelectSql($queryObject, $with_values);
634
			if(is_a($query, 'Object'))
635
			{
636
				return;
637
			}
638
			$query .= (__DEBUG_QUERY__ & 1 && $queryObject->queryID) ? sprintf(' ' . $this->comment_syntax, $queryObject->queryID) : '';
639
640
			$result = $this->_query($query, $connection);
641
			if($this->isError())
642
			{
643
				return $this->queryError($queryObject);
644
			}
645
646
			$data = $this->_fetch($result);
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->_query($query, $connection) on line 640 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
647
			$buff = new Object ();
648
			$buff->data = $data;
0 ignored issues
show
Bug introduced by
The property data does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
649
650
			if($queryObject->usesClickCount())
651
			{
652
				$update_query = $this->getClickCountQuery($queryObject);
653
				$this->_executeUpdateAct($update_query, $with_values);
654
			}
655
656
			return $buff;
657
		}
658
	}
659
660
	/**
661
	 * Get the ID generated in the last query
662
	 * Return next sequence from sequence table
663
	 * This method use only mysql
664
	 * @return int
665
	 */
666
	function db_insert_id()
667
	{
668
		$connection = $this->_getConnection('master');
669
		return mysql_insert_id($connection);
670
	}
671
672
	/**
673
	 * Fetch a result row as an object
674
	 * @param resource $result
675
	 * @return object
676
	 */
677
	function db_fetch_object(&$result)
678
	{
679
		return mysql_fetch_object($result);
680
	}
681
682
	/**
683
	 * Free result memory
684
	 * @param resource $result
685
	 * @return boolean Returns TRUE on success or FALSE on failure.
686
	 */
687
	function db_free_result(&$result)
688
	{
689
		return mysql_free_result($result);
690
	}
691
692
	/**
693
	 * Return the DBParser
694
	 * @param boolean $force
695
	 * @return DBParser
696
	 */
697
	function &getParser($force = FALSE)
698
	{
699
		$dbParser = new DBParser('`', '`', $this->prefix);
700
		return $dbParser;
701
	}
702
703
	/**
704
	 * If have a error, return error object
705
	 * @param Object $queryObject
706
	 * @return Object
707
	 */
708 View Code Duplication
	function queryError($queryObject)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
709
	{
710
		$limit = $queryObject->getLimit();
711
		if($limit && $limit->isPageHandler())
712
		{
713
			$buff = new Object ();
714
			$buff->total_count = 0;
0 ignored issues
show
Bug introduced by
The property total_count does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
715
			$buff->total_page = 0;
0 ignored issues
show
Bug introduced by
The property total_page does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
716
			$buff->page = 1;
0 ignored issues
show
Bug introduced by
The property page does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
717
			$buff->data = array();
0 ignored issues
show
Bug introduced by
The property data does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
718
			$buff->page_navigation = new PageHandler(/* $total_count */0, /* $total_page */1, /* $page */1, /* $page_count */10); //default page handler values
0 ignored issues
show
Bug introduced by
The property page_navigation does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
719
			return $buff;
720
		}
721
		else
722
		{
723
			return;
724
		}
725
	}
726
727
	/**
728
	 * If select query execute, return page info
729
	 * @param Object $queryObject
730
	 * @param resource $result
731
	 * @param resource $connection
732
	 * @param boolean $with_values
733
	 * @return Object Object with page info containing
734
	 */
735
	function queryPageLimit($queryObject, $result, $connection, $with_values = true)
0 ignored issues
show
Unused Code introduced by
The parameter $result is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
736
	{
737
		$limit = $queryObject->getLimit();
738
		// Total count
739
		$temp_where = $queryObject->getWhereString($with_values, false);
740
		$count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString($with_values), ($temp_where === '' ? '' : ' WHERE ' . $temp_where));
741
742
		// Check for distinct query and if found update count query structure
743
		$temp_select = $queryObject->getSelectString($with_values);
744
		$uses_distinct = stripos($temp_select, "distinct") !== false;
745
		$uses_groupby = $queryObject->getGroupByString() != '';
746 View Code Duplication
		if($uses_distinct || $uses_groupby)
747
		{
748
			$count_query = sprintf('select %s %s %s %s'
749
					, $temp_select == '*' ? '1' : $temp_select
750
					, 'FROM ' . $queryObject->getFromString($with_values)
751
					, ($temp_where === '' ? '' : ' WHERE ' . $temp_where)
752
					, ($uses_groupby ? ' GROUP BY ' . $queryObject->getGroupByString() : '')
753
			);
754
755
			// If query uses grouping or distinct, count from original select
756
			$count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query);
757
		}
758
759
		$count_query .= (__DEBUG_QUERY__ & 1 && $queryObject->queryID) ? sprintf(' ' . $this->comment_syntax, $queryObject->queryID) : '';
760
		$result_count = $this->_query($count_query, $connection);
761
		$count_output = $this->_fetch($result_count);
0 ignored issues
show
Bug introduced by
It seems like $result_count defined by $this->_query($count_query, $connection) on line 760 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
762
		$total_count = (int) (isset($count_output->count) ? $count_output->count : NULL);
763
764
		$list_count = $limit->list_count->getValue();
765
		if(!$list_count)
766
		{
767
			$list_count = 20;
768
		}
769
		$page_count = $limit->page_count->getValue();
770
		if(!$page_count)
771
		{
772
			$page_count = 10;
773
		}
774
		$page = $limit->page->getValue();
775
		if(!$page || $page < 1)
776
		{
777
			$page = 1;
778
		}
779
780
		// total pages
781 View Code Duplication
		if($total_count)
782
		{
783
			$total_page = (int) (($total_count - 1) / $list_count) + 1;
784
		}
785
		else
786
		{
787
			$total_page = 1;
788
		}
789
790
		// check the page variables
791 View Code Duplication
		if($page > $total_page)
792
		{
793
			// If requested page is bigger than total number of pages, return empty list
794
			$buff = new Object ();
795
			$buff->total_count = $total_count;
0 ignored issues
show
Bug introduced by
The property total_count does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
796
			$buff->total_page = $total_page;
0 ignored issues
show
Bug introduced by
The property total_page does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
797
			$buff->page = $page;
0 ignored issues
show
Bug introduced by
The property page does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
798
			$buff->data = array();
0 ignored issues
show
Bug introduced by
The property data does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
799
			$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count);
0 ignored issues
show
Bug introduced by
The property page_navigation does not seem to exist in Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
800
			return $buff;
801
		}
802
		$start_count = ($page - 1) * $list_count;
803
804
		$query = $this->getSelectPageSql($queryObject, $with_values, $start_count, $list_count);
805
806
		$query .= (__DEBUG_QUERY__ & 1 && $queryObject->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : '';
807
		$result = $this->_query($query, $connection);
808
		if($this->isError())
809
		{
810
			return $this->queryError($queryObject);
811
		}
812
813
		$virtual_no = $total_count - ($page - 1) * $list_count;
814
		$data = $this->_fetch($result, $virtual_no);
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->_query($query, $connection) on line 807 can also be of type null; however, DBMysql::_fetch() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
815
816
		$buff = new Object ();
817
		$buff->total_count = $total_count;
818
		$buff->total_page = $total_page;
819
		$buff->page = $page;
820
		$buff->data = $data;
821
		$buff->page_navigation = new PageHandler($total_count, $total_page, $page, $page_count);
822
		return $buff;
823
	}
824
825
	/**
826
	 * If select query execute, return paging sql
827
	 * @param object $query
828
	 * @param boolean $with_values
829
	 * @param int $start_count
830
	 * @param int $list_count
831
	 * @return string select paging sql
832
	 */
833 View Code Duplication
	function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
834
	{
835
		$select = $query->getSelectString($with_values);
836
		if($select == '')
837
		{
838
			return new Object(-1, "Invalid query");
839
		}
840
		$select = 'SELECT ' . $select;
841
842
		$from = $query->getFromString($with_values);
843
		if($from == '')
844
		{
845
			return new Object(-1, "Invalid query");
846
		}
847
		$from = ' FROM ' . $from;
848
849
		$where = $query->getWhereString($with_values);
850
		if($where != '')
851
		{
852
			$where = ' WHERE ' . $where;
853
		}
854
855
		$groupBy = $query->getGroupByString();
856
		if($groupBy != '')
857
		{
858
			$groupBy = ' GROUP BY ' . $groupBy;
859
		}
860
861
		$orderBy = $query->getOrderByString();
862
		if($orderBy != '')
863
		{
864
			$orderBy = ' ORDER BY ' . $orderBy;
865
		}
866
867
		$limit = $query->getLimitString();
868
		if($limit != '')
869
		{
870
			$limit = sprintf(' LIMIT %d, %d', $start_count, $list_count);
871
		}
872
873
		return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit;
874
	}
875
876
}
877
878
DBMysql::$isSupported = function_exists('mysql_connect');
0 ignored issues
show
Bug introduced by
The property isSupported cannot be accessed from this context as it is declared private in class DB.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
879
880
/* End of file DBMysql.class.php */
881
/* Location: ./classes/db/DBMysql.class.php */
882