Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Database_MySQL often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Database_MySQL, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
28 | class Database_MySQL extends Database_Abstract |
||
29 | { |
||
30 | /** |
||
31 | * Holds current instance of the class |
||
32 | * |
||
33 | * @var Database_MySQL |
||
34 | */ |
||
35 | private static $_db = null; |
||
36 | |||
37 | /** |
||
38 | * Initializes a database connection. |
||
39 | * It returns the connection, if successful. |
||
40 | * |
||
41 | * @param string $db_server |
||
42 | * @param string $db_name |
||
43 | * @param string $db_user |
||
44 | * @param string $db_passwd |
||
45 | * @param string $db_prefix |
||
46 | * @param mixed[] $db_options |
||
47 | * |
||
48 | * @return mysqli|null |
||
49 | * @throws Elk_Exception |
||
50 | */ |
||
51 | public static function initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $db_options = array()) |
||
|
|||
52 | { |
||
53 | global $mysql_set_mode; |
||
54 | |||
55 | // Initialize the instance... if not done already! |
||
56 | if (self::$_db === null) |
||
57 | self::$_db = new self(); |
||
58 | |||
59 | // Non-standard port |
||
60 | View Code Duplication | if (!empty($db_options['port'])) |
|
61 | $db_port = (int) $db_options['port']; |
||
62 | else |
||
63 | $db_port = 0; |
||
64 | |||
65 | // Select the database. Maybe. |
||
66 | if (empty($db_options['dont_select_db'])) |
||
67 | $connection = @mysqli_connect((!empty($db_options['persist']) ? 'p:' : '') . $db_server, $db_user, $db_passwd, $db_name, $db_port); |
||
68 | else |
||
69 | $connection = @mysqli_connect((!empty($db_options['persist']) ? 'p:' : '') . $db_server, $db_user, $db_passwd, '', $db_port); |
||
70 | |||
71 | // Something's wrong, show an error if its fatal (which we assume it is) |
||
72 | View Code Duplication | if (!$connection) |
|
73 | { |
||
74 | if (!empty($db_options['non_fatal'])) |
||
75 | return null; |
||
76 | else |
||
77 | Errors::instance()->display_db_error(); |
||
78 | } |
||
79 | |||
80 | self::$_db->_connection = $connection; |
||
81 | |||
82 | // This makes it possible to automatically change the sql_mode and autocommit if needed. |
||
83 | if (isset($mysql_set_mode) && $mysql_set_mode === true) |
||
84 | self::$_db->query('', 'SET sql_mode = \'\', AUTOCOMMIT = 1', |
||
85 | array(), |
||
86 | false |
||
87 | ); |
||
88 | |||
89 | // Few databases still have not set UTF-8 as their default input charset |
||
90 | self::$_db->query('', ' |
||
91 | SET NAMES UTF8', |
||
92 | array( |
||
93 | ) |
||
94 | ); |
||
95 | |||
96 | return $connection; |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * Fix up the prefix so it doesn't require the database to be selected. |
||
101 | * |
||
102 | * @param string $db_prefix |
||
103 | * @param string $db_name |
||
104 | * |
||
105 | * @return string |
||
106 | */ |
||
107 | public function fix_prefix($db_prefix, $db_name) |
||
113 | |||
114 | /** |
||
115 | * Do a query. Takes care of errors too. |
||
116 | * |
||
117 | * @param string $identifier |
||
118 | * @param string $db_string |
||
119 | * @param mixed[]|false $db_values = array() |
||
120 | * @param mysqli_result|false|null $connection = null |
||
121 | * @throws Elk_Exception |
||
122 | */ |
||
123 | 39 | public function query($identifier, $db_string, $db_values = array(), $connection = null) |
|
124 | { |
||
125 | 39 | global $db_show_debug, $time_start, $modSettings; |
|
126 | |||
127 | // Comments that are allowed in a query are preg_removed. |
||
128 | static $allowed_comments_from = array( |
||
129 | '~\s+~s', |
||
130 | '~/\*!40001 SQL_NO_CACHE \*/~', |
||
131 | '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~', |
||
132 | '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~', |
||
133 | 39 | ); |
|
134 | static $allowed_comments_to = array( |
||
135 | ' ', |
||
136 | '', |
||
137 | '', |
||
138 | '', |
||
139 | 39 | ); |
|
140 | |||
141 | // Decide which connection to use. |
||
142 | 39 | $connection = $connection === null ? $this->_connection : $connection; |
|
143 | |||
144 | // One more query.... |
||
145 | 39 | $this->_query_count++; |
|
146 | |||
147 | 39 | View Code Duplication | if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) |
148 | 39 | $this->error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__); |
|
149 | |||
150 | // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By |
||
151 | 39 | if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false) |
|
152 | 39 | { |
|
153 | // Add before LIMIT |
||
154 | 7 | if ($pos = strpos($db_string, 'LIMIT ')) |
|
155 | 7 | $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string)); |
|
156 | else |
||
157 | // Append it. |
||
158 | 6 | $db_string .= "\n\t\t\tORDER BY null"; |
|
159 | 7 | } |
|
160 | |||
161 | 39 | View Code Duplication | if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) |
162 | 39 | { |
|
163 | // Store these values for use in the callback function. |
||
164 | 39 | $this->_db_callback_values = $db_values; |
|
165 | 39 | $this->_db_callback_connection = $connection; |
|
166 | |||
167 | // Inject the values passed to this function. |
||
168 | 39 | $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string); |
|
169 | |||
170 | // No need for them any longer. |
||
171 | 39 | $this->_db_callback_values = array(); |
|
172 | 39 | $this->_db_callback_connection = null; |
|
173 | 39 | } |
|
174 | |||
175 | // Debugging. |
||
176 | 39 | View Code Duplication | if ($db_show_debug === true) |
177 | 39 | { |
|
178 | $debug = Debug::instance(); |
||
179 | |||
180 | // Get the file and line number this function was called. |
||
181 | list ($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__); |
||
182 | |||
183 | if (!empty($_SESSION['debug_redirect'])) |
||
184 | { |
||
185 | $debug->merge_db($_SESSION['debug_redirect']); |
||
186 | // @todo this may be off by 1 |
||
187 | $this->_query_count += count($_SESSION['debug_redirect']); |
||
188 | $_SESSION['debug_redirect'] = array(); |
||
189 | } |
||
190 | |||
191 | // Don't overload it. |
||
192 | $st = microtime(true); |
||
193 | $db_cache = array(); |
||
194 | $db_cache['q'] = $this->_query_count < 50 ? $db_string : '...'; |
||
195 | $db_cache['f'] = $file; |
||
196 | $db_cache['l'] = $line; |
||
197 | $db_cache['s'] = $st - $time_start; |
||
198 | } |
||
199 | |||
200 | // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over. |
||
201 | 39 | if (empty($modSettings['disableQueryCheck'])) |
|
202 | 39 | { |
|
203 | 39 | $clean = ''; |
|
204 | 39 | $old_pos = 0; |
|
205 | 39 | $pos = -1; |
|
206 | 39 | View Code Duplication | while (true) |
207 | { |
||
208 | 39 | $pos = strpos($db_string, '\'', $pos + 1); |
|
209 | 39 | if ($pos === false) |
|
210 | 39 | break; |
|
211 | 33 | $clean .= substr($db_string, $old_pos, $pos - $old_pos); |
|
212 | |||
213 | 33 | while (true) |
|
214 | { |
||
215 | 33 | $pos1 = strpos($db_string, '\'', $pos + 1); |
|
216 | 33 | $pos2 = strpos($db_string, '\\', $pos + 1); |
|
217 | 33 | if ($pos1 === false) |
|
218 | 33 | break; |
|
219 | 33 | elseif ($pos2 === false || $pos2 > $pos1) |
|
220 | { |
||
221 | 33 | $pos = $pos1; |
|
222 | 33 | break; |
|
223 | } |
||
224 | |||
225 | 3 | $pos = $pos2 + 1; |
|
226 | 3 | } |
|
227 | |||
228 | 33 | $clean .= ' %s '; |
|
229 | 33 | $old_pos = $pos + 1; |
|
230 | 33 | } |
|
231 | |||
232 | 39 | $clean .= substr($db_string, $old_pos); |
|
233 | 39 | $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean))); |
|
234 | |||
235 | // Comments? We don't use comments in our queries, we leave 'em outside! |
||
236 | 39 | View Code Duplication | if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) |
237 | 39 | $fail = true; |
|
238 | // Trying to change passwords, slow us down, or something? |
||
239 | 39 | elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) |
|
240 | $fail = true; |
||
241 | 39 | elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) |
|
242 | $fail = true; |
||
243 | |||
244 | 39 | if (!empty($fail) && function_exists('log_error')) |
|
245 | 39 | $this->error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__); |
|
246 | 39 | } |
|
247 | |||
248 | 39 | if ($this->_unbuffered === false) |
|
249 | 39 | $ret = @mysqli_query($connection, $db_string); |
|
250 | else |
||
251 | $ret = @mysqli_query($connection, $db_string, MYSQLI_USE_RESULT); |
||
252 | |||
253 | // @deprecated since 1.1 - use skip_next_error method |
||
254 | 39 | if (!empty($db_values['db_error_skip'])) |
|
255 | 39 | { |
|
256 | 11 | $this->_skip_error = true; |
|
257 | 11 | } |
|
258 | |||
259 | 39 | if ($ret === false && $this->_skip_error === false) |
|
260 | 39 | { |
|
261 | $ret = $this->error($db_string, $connection); |
||
262 | } |
||
263 | |||
264 | // Revert not to skip errors |
||
265 | 39 | if ($this->_skip_error === true) |
|
266 | 39 | { |
|
267 | 11 | $this->_skip_error = false; |
|
268 | 11 | } |
|
269 | |||
270 | // Debugging. |
||
271 | 39 | View Code Duplication | if ($db_show_debug === true) |
272 | 39 | { |
|
273 | $db_cache['t'] = microtime(true) - $st; |
||
274 | $debug->db_query($db_cache); |
||
275 | } |
||
276 | |||
277 | 39 | return $ret; |
|
278 | } |
||
279 | |||
280 | /** |
||
281 | * Checks if the string contains any 4byte chars and if so, |
||
282 | * converts them into HTML entities. |
||
283 | * |
||
284 | * This is necessary because MySQL utf8 doesn't know how to store such |
||
285 | * characters and would generate an error any time one is used. |
||
286 | * The 4byte chars are used by emoji |
||
287 | * |
||
288 | * @param string $string |
||
289 | * @return string |
||
290 | */ |
||
291 | 33 | private function _clean_4byte_chars($string) |
|
292 | { |
||
293 | 33 | global $modSettings; |
|
294 | |||
295 | 33 | if (!empty($modSettings['using_utf8mb4'])) |
|
296 | 33 | return $string; |
|
297 | |||
298 | 33 | $result = $string; |
|
299 | 33 | $ord = array_map('ord', str_split($string)); |
|
300 | |||
301 | // If we are in the 4-byte range |
||
302 | 33 | if (max($ord) >= 240) |
|
303 | 33 | { |
|
304 | // Byte length |
||
305 | $length = strlen($string); |
||
306 | $result = ''; |
||
307 | |||
308 | // Look for a 4byte marker |
||
309 | for ($i = 0; $i < $length; $i++) |
||
310 | { |
||
311 | // The first byte of a 4-byte character encoding starts with the bytes 0xF0-0xF4 (240 <-> 244) |
||
312 | // but look all the way to 247 for safe measure |
||
313 | $ord1 = $ord[$i]; |
||
314 | if ($ord1 >= 240 && $ord1 <= 247) |
||
315 | { |
||
316 | // Replace it with the corresponding html entity |
||
317 | $entity = $this->_uniord(chr($ord[$i]) . chr($ord[$i + 1]) . chr($ord[$i + 2]) . chr($ord[$i + 3])); |
||
318 | if ($entity === false) |
||
319 | $result .= "\xEF\xBF\xBD"; |
||
320 | else |
||
321 | $result .= '&#x' . dechex($entity) . ';'; |
||
322 | $i += 3; |
||
323 | } |
||
324 | else |
||
325 | $result .= $string[$i]; |
||
326 | } |
||
327 | } |
||
328 | |||
329 | 33 | return $result; |
|
330 | } |
||
331 | |||
332 | /** |
||
333 | * Converts a 4byte char into the corresponding HTML entity code. |
||
334 | * |
||
335 | * This function is derived from: |
||
336 | * http://www.greywyvern.com/code/php/utf8_html.phps |
||
337 | * |
||
338 | * @param string $c |
||
339 | * @return integer|false |
||
340 | */ |
||
341 | private function _uniord($c) |
||
342 | { |
||
343 | View Code Duplication | if (ord($c[0]) >= 0 && ord($c[0]) <= 127) |
|
344 | return ord($c[0]); |
||
345 | if (ord($c[0]) >= 192 && ord($c[0]) <= 223) |
||
346 | return (ord($c[0]) - 192) * 64 + (ord($c[1]) - 128); |
||
347 | if (ord($c[0]) >= 224 && ord($c[0]) <= 239) |
||
348 | return (ord($c[0]) - 224) * 4096 + (ord($c[1]) - 128) * 64 + (ord($c[2]) - 128); |
||
349 | if (ord($c[0]) >= 240 && ord($c[0]) <= 247) |
||
350 | return (ord($c[0]) - 240) * 262144 + (ord($c[1]) - 128) * 4096 + (ord($c[2]) - 128) * 64 + (ord($c[3]) - 128); |
||
351 | if (ord($c[0]) >= 248 && ord($c[0]) <= 251) |
||
352 | return (ord($c[0]) - 248) * 16777216 + (ord($c[1]) - 128) * 262144 + (ord($c[2]) - 128) * 4096 + (ord($c[3]) - 128) * 64 + (ord($c[4]) - 128); |
||
353 | if (ord($c[0]) >= 252 && ord($c[0]) <= 253) |
||
354 | return (ord($c[0]) - 252) * 1073741824 + (ord($c[1]) - 128) * 16777216 + (ord($c[2]) - 128) * 262144 + (ord($c[3]) - 128) * 4096 + (ord($c[4]) - 128) * 64 + (ord($c[5]) - 128); |
||
355 | View Code Duplication | if (ord($c[0]) >= 254 && ord($c[0]) <= 255) |
|
356 | return false; |
||
357 | } |
||
358 | |||
359 | /** |
||
360 | * Affected rows from previous operation. |
||
361 | * |
||
362 | * @param mysqli|null $connection |
||
363 | */ |
||
364 | 9 | public function affected_rows($connection = null) |
|
365 | { |
||
366 | 9 | return mysqli_affected_rows($connection === null ? $this->_connection : $connection); |
|
367 | } |
||
368 | |||
369 | /** |
||
370 | * Last inserted id. |
||
371 | * |
||
372 | * @param string $table |
||
373 | * @param string|null $field = null |
||
374 | * @param mysqli|null $connection = null |
||
375 | */ |
||
376 | 15 | public function insert_id($table, $field = null, $connection = null) |
|
381 | |||
382 | /** |
||
383 | * Fetch a row from the result set given as parameter. |
||
384 | * MySQL implementation doesn't use $counter parameter. |
||
385 | * |
||
386 | * @param mysqli_result $result |
||
387 | * @param integer|bool $counter = false |
||
388 | */ |
||
389 | 16 | public function fetch_row($result, $counter = false) |
|
394 | |||
395 | /** |
||
396 | * Free the resultset. |
||
397 | * |
||
398 | * @param mysqli_result $result |
||
399 | */ |
||
400 | 37 | public function free_result($result) |
|
405 | |||
406 | /** |
||
407 | * Get the number of rows in the result. |
||
408 | * |
||
409 | * @param mysqli_result $result |
||
410 | */ |
||
411 | 19 | public function num_rows($result) |
|
416 | |||
417 | /** |
||
418 | * Get the number of fields in the result set. |
||
419 | * |
||
420 | * @param mysqli_result $request |
||
421 | */ |
||
422 | public function num_fields($request) |
||
426 | |||
427 | /** |
||
428 | * Reset the internal result pointer. |
||
429 | * |
||
430 | * @param mysqli_result $request |
||
431 | * @param integer $counter |
||
432 | */ |
||
433 | public function data_seek($request, $counter) |
||
438 | |||
439 | /** |
||
440 | * Do a transaction. |
||
441 | * |
||
442 | * @param string $type - the step to perform (i.e. 'begin', 'commit', 'rollback') |
||
443 | * @param mysqli|null $connection = null |
||
444 | */ |
||
445 | public function db_transaction($type = 'commit', $connection = null) |
||
459 | |||
460 | /** |
||
461 | * Return last error string from the database server |
||
462 | * |
||
463 | * @param mysqli|null $connection = null |
||
464 | */ |
||
465 | public function last_error($connection = null) |
||
473 | |||
474 | /** |
||
475 | * Database error. |
||
476 | * Backtrace, log, try to fix. |
||
477 | * |
||
478 | * @param string $db_string |
||
479 | * @param mysqli|null $connection = null |
||
480 | * |
||
481 | * @return bool |
||
482 | * @throws Elk_Exception |
||
483 | */ |
||
484 | public function error($db_string, $connection = null) |
||
686 | |||
687 | /** |
||
688 | * Insert data. |
||
689 | * |
||
690 | * @param string $method - options 'replace', 'ignore', 'insert' |
||
691 | * @param string $table |
||
692 | * @param mixed[] $columns |
||
693 | * @param mixed[] $data |
||
694 | * @param mixed[] $keys |
||
695 | * @param bool $disable_trans = false |
||
696 | * @param mysqli|null $connection = null |
||
697 | * @throws Elk_Exception |
||
698 | */ |
||
699 | 24 | public function insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null) |
|
755 | |||
756 | /** |
||
757 | * Unescape an escaped string! |
||
758 | * |
||
759 | * @param string $string |
||
760 | */ |
||
761 | public function unescape_string($string) |
||
765 | |||
766 | /** |
||
767 | * Returns whether the database system supports ignore. |
||
768 | * |
||
769 | * @return boolean |
||
770 | */ |
||
771 | public function support_ignore() |
||
775 | |||
776 | /** |
||
777 | * Gets all the necessary INSERTs for the table named table_name. |
||
778 | * It goes in 250 row segments. |
||
779 | * |
||
780 | * @param string $tableName - the table to create the inserts for. |
||
781 | * @param bool $new_table |
||
782 | * |
||
783 | * @return string the query to insert the data back in, or an empty string if the table was empty. |
||
784 | * @throws Elk_Exception |
||
785 | */ |
||
786 | public function insert_sql($tableName, $new_table = false) |
||
854 | |||
855 | /** |
||
856 | * Dumps the schema (CREATE) for a table. |
||
857 | * |
||
858 | * @param string $tableName - the table |
||
859 | * |
||
860 | * @return string - the CREATE statement as string |
||
861 | * @throws Elk_Exception |
||
862 | */ |
||
863 | public function db_table_sql($tableName) |
||
967 | |||
968 | /** |
||
969 | * {@inheritdoc} |
||
970 | */ |
||
971 | 1 | public function db_list_tables($db_name_str = false, $filter = false) |
|
997 | |||
998 | /** |
||
999 | * Backup $table_name to $backup_table. |
||
1000 | * |
||
1001 | * @param string $table_name |
||
1002 | * @param string $backup_table |
||
1003 | * |
||
1004 | * @return resource - the request handle to the table creation query |
||
1005 | * @throws Elk_Exception |
||
1006 | */ |
||
1007 | public function db_backup_table($table_name, $backup_table) |
||
1130 | |||
1131 | /** |
||
1132 | * Get the version number. |
||
1133 | * |
||
1134 | * @return string - the version |
||
1135 | * @throws Elk_Exception |
||
1136 | */ |
||
1137 | View Code Duplication | public function db_server_version() |
|
1149 | |||
1150 | /** |
||
1151 | * Get the name (title) of the database system. |
||
1152 | * |
||
1153 | * @return string |
||
1154 | */ |
||
1155 | public function db_title() |
||
1159 | |||
1160 | /** |
||
1161 | * Whether the database system is case sensitive. |
||
1162 | * |
||
1163 | * @return false |
||
1164 | */ |
||
1165 | public function db_case_sensitive() |
||
1169 | |||
1170 | /** |
||
1171 | * Escape string for the database input |
||
1172 | * |
||
1173 | * @param string $string |
||
1174 | */ |
||
1175 | 33 | public function escape_string($string) |
|
1181 | |||
1182 | /** |
||
1183 | * Fetch next result as association. |
||
1184 | * The mysql implementation simply delegates to mysqli_fetch_assoc(). |
||
1185 | * It ignores $counter parameter. |
||
1186 | * |
||
1187 | * @param mysqli_result $request |
||
1188 | * @param int|bool $counter = false |
||
1189 | */ |
||
1190 | 31 | public function fetch_assoc($request, $counter = false) |
|
1194 | |||
1195 | /** |
||
1196 | * Return server info. |
||
1197 | * |
||
1198 | * @param mysqli|null $connection |
||
1199 | * |
||
1200 | * @return string |
||
1201 | */ |
||
1202 | public function db_server_info($connection = null) |
||
1209 | |||
1210 | /** |
||
1211 | * Get the version number. |
||
1212 | * |
||
1213 | * @return string - the version |
||
1214 | * @throws Elk_Exception |
||
1215 | */ |
||
1216 | View Code Duplication | public function db_client_version() |
|
1228 | |||
1229 | /** |
||
1230 | * Select database. |
||
1231 | * |
||
1232 | * @param string|null $dbName = null |
||
1233 | * @param mysqli|null $connection = null |
||
1234 | */ |
||
1235 | public function select_db($dbName = null, $connection = null) |
||
1242 | |||
1243 | /** |
||
1244 | * Returns a reference to the existing instance |
||
1245 | */ |
||
1246 | 59 | public static function db() |
|
1250 | |||
1251 | /** |
||
1252 | * Finds out if the connection is still valid. |
||
1253 | * |
||
1254 | * @param mysqli|null $connection = null |
||
1255 | */ |
||
1256 | 39 | public function validConnection($connection = null) |
|
1260 | } |
||
1261 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.