Adding of network advert types partly finished, hard-coded table type fixed to dynamic
[mailer.git] / inc / db / lib-mysql3.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/29/2004 *
4  * ===================                          Last change: 08/29/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : lib-mysql3.php                                   *
8  * -------------------------------------------------------------------- *
9  * Short description : Database layer for MySQL +3.x server             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Datenbankschicht fuer MySQL +3.x Server          *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // SQL queries
45 function SQL_QUERY ($sqlString, $F, $L) {
46         // Trim SQL string
47         $sqlString = trim($sqlString);
48
49         // Link is up?
50         if (!SQL_IS_LINK_UP()) {
51                 // We should not quietly ignore this!
52                 debug_report_bug(sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
53                         $sqlString,
54                         basename($F),
55                         $L
56                 ));
57
58                 // Return 'false' because it has failed
59                 return false;
60         } elseif (empty($sqlString)) {
61                 // Empty SQL string!
62                 debug_report_bug(sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
63                         basename($F),
64                         $L
65                 ));
66
67                 // This is invalid, of course
68                 return false;
69         }
70
71         // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
72         $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
73
74         // Replace {PER}
75         $sqlString = str_replace('{PER}', '%', $sqlString);
76
77         // Compile config entries out
78         $eval = "\$sqlString = \"".FILTER_COMPILE_CONFIG(escapeQuotes($sqlString))."\";";
79         eval($eval);
80
81         // Starting time
82         $querytimeBefore = microtime(true);
83
84         // Run SQL command
85         //* DEBUG: */ print('F=' . basename($F) . ',L=' . $L . 'sql=' . htmlentities($sqlString) . '<br />');
86         $result = mysql_query($sqlString, SQL_GET_LINK())
87                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error() . '<br />
88 Query string:<br />
89 ' . $sqlString);
90         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sqlString . ',numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS());
91
92         // Calculate query time
93         $queryTime = microtime(true) - $querytimeBefore;
94
95         // Add this query to array including timing
96         addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
97
98         // Save last successfull query
99         setConfigEntry('db_last_query', $sqlString);
100
101         // Count all query times
102         incrementConfigEntry('sql_time', $queryTime);
103
104         // Count this query
105         incrementConfigEntry('sql_count');
106
107         // Debug output
108         if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
109                 //
110                 // Debugging stuff...
111                 //
112                 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __LINE__, 'Cannot write mysql.log!');
113                 if (!isset($GLOBALS['sql_first_entry'])) {
114                         // Write first entry
115                         fwrite($fp, 'Module=' . getModule() . "\n");
116                         $GLOBALS['sql_first_entry'] = true;
117                 } // END - if
118                 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $sqlString)) . "\n");
119                 fclose($fp);
120         } // END - if
121
122         // Count DB hits
123         if (!isStatsEntrySet('db_hits')) {
124                 // Count in dummy variable
125                 setStatsEntry('db_hits', 1);
126         } else {
127                 // Count to config array
128                 incrementStatsEntry('db_hits');
129         }
130
131         // Return the result
132         return $result;
133 }
134
135 // SQL num rows
136 function SQL_NUMROWS ($result) {
137         // Link is not up, no rows by default
138         $lines = false;
139
140         // Is the result a valid resource?
141         if (is_resource($result)) {
142                 // Get the count of rows from database
143                 $lines = mysql_num_rows($result);
144
145                 // Is the result empty? Then we have an error!
146                 if (empty($lines)) $lines = '0';
147         } elseif (SQL_IS_LINK_UP()) {
148                 // No resource given, no lines found!
149                 $lines = '0';
150         }
151
152         // Return lines
153         return $lines;
154 }
155
156 // SQL affected rows
157 function SQL_AFFECTEDROWS() {
158         // Valid link resource?
159         if (!SQL_IS_LINK_UP()) return false;
160
161         // Get affected rows
162         $lines = mysql_affected_rows(SQL_GET_LINK());
163
164         // Return it
165         return $lines;
166 }
167
168 // SQL fetch row
169 function SQL_FETCHROW ($result) {
170         // Is a result resource set?
171         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) return false;
172
173         // Fetch the data and return it
174         return mysql_fetch_row($result);
175 }
176
177 // SQL fetch array
178 function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
179         // Is a result resource set?
180         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
181
182         // Initialize array
183         $row = array();
184
185         // Load row from database
186         $row = mysql_fetch_array($res);
187
188         // Return only arrays here
189         if (is_array($row)) {
190                 // Shall we remove numerical data here automatically?
191                 if ($remove_numerical) {
192                         // So let's remove all numerical elements to save memory!
193                         $max = count($row);
194                         for ($idx = '0'; $idx < ($max / 2); $idx++) {
195                                 // Remove entry
196                                 unset($row[$idx]);
197                         } // END - for
198                 } // END - if
199
200                 // Return row
201                 return $row;
202         } else {
203                 // Return a false here...
204                 return false;
205         }
206 }
207
208 // SQL result
209 function SQL_RESULT ($res, $row, $field = '0') {
210         // Is $res valid?
211         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
212
213         // Run the result command and return the result
214         $result = mysql_result($res, $row, $field);
215         return $result;
216 }
217
218 // SQL connect
219 function SQL_CONNECT ($host, $login, $password, $F, $L) {
220         // Try to connect
221         $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
222
223         // Set the link resource
224         SQL_SET_LINK($connect);
225
226         // Destroy cache
227         unset($GLOBALS['sql_link_res']);
228 }
229
230 // SQL select database
231 function SQL_SELECT_DB ($dbName, $F, $L) {
232         // Is there still a valid link? If not, skip it.
233         if (!SQL_IS_LINK_UP()) return false;
234
235         // Return the result
236         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
237 }
238
239 // SQL close link
240 function SQL_CLOSE ($F, $L) {
241         if (!SQL_IS_LINK_UP()) {
242                 // Skip double close
243                 return false;
244         } // END - if
245
246         // Close database link and forget the link
247         $close = mysql_close(SQL_GET_LINK())
248                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
249
250         // Close link
251         SQL_SET_LINK(null);
252
253         // Destroy cache
254         unset($GLOBALS['sql_link_res']);
255
256         // Return the result
257         return $close;
258 }
259
260 // SQL free result
261 function SQL_FREERESULT ($result) {
262         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) {
263                 // Abort here
264                 return false;
265         } // END - if
266
267         $res = mysql_free_result($result);
268         return $res;
269 }
270
271 // SQL string escaping
272 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
273         // Link is there?
274         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
275
276         // Escape all data
277         $dataSecured['__sql_string'] = $qstring;
278         foreach ($data as $key => $value) {
279                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
280         } // END - foreach
281
282         // Generate query
283         $query = call_user_func_array('sprintf', $dataSecured);
284
285         // Debugging
286         //
287         //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
288         //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", " ", $eval))."\n");
289         //* DEBUG: */ fclose($fp);
290
291         if ($run === true) {
292                 // Run SQL query (default)
293                 return SQL_QUERY($query, $F, $L);
294         } else {
295                 // Return secured string
296                 return $query;
297         }
298 }
299
300 // Get id from last INSERT command
301 function SQL_INSERTID () {
302         if (!SQL_IS_LINK_UP()) return false;
303         return mysql_insert_id();
304 }
305
306 // Escape a string for the database
307 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
308         // Do we have cache?
309         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
310                 // Secure string first? (which is the default behaviour!)
311                 if ($secureString === true) {
312                         // Then do it here
313                         $str = secureString($str, $strip);
314                 } // END - if
315
316                 if (!SQL_IS_LINK_UP()) {
317                         // Fall-back to escapeQuotes() when there is no link
318                         $ret = escapeQuotes($str);
319                 } elseif (function_exists('mysql_real_escape_string')) {
320                         // The new and improved version
321                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
322                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
323                 } elseif (function_exists('mysql_escape_string')) {
324                         // The obsolete function
325                         $ret = mysql_escape_string($str, SQL_GET_LINK());
326                 } else {
327                         // If nothing else works, fall back to escapeQuotes() again
328                         $ret = escapeQuotes($str);
329                 }
330
331                 // Cache result
332                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
333         } // END - if
334
335         // Return it
336         return $GLOBALS['sql_escapes'][''.$str.''];
337 }
338
339 // SELECT query string from table, columns and so on... ;-)
340 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
341         // Is columns an array?
342         if (!is_array($columns)) {
343                 // No array
344                 debug_report_bug(sprintf("columns is not an array. %s != array, file=%s, line=%s",
345                         gettype($columns),
346                         basename($F),
347                         $L
348                 ));
349
350                 // Abort here with 'false'
351                 return false;
352         } // END  - if
353
354         // Prepare the SQL statement
355         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
356
357         // Return the result
358         return SQL_QUERY_ESC($sql,
359                 array(
360                         $table,
361                         $idRow,
362                         bigintval($id),
363                 ), $F, $L
364         );
365 }
366
367 // ALTER TABLE wrapper function
368 function SQL_ALTER_TABLE ($sql, $F, $L) {
369         // Abort if link is down
370         if (!SQL_IS_LINK_UP()) return false;
371
372         // This is the default result...
373         $result = false;
374
375         // Determine index/fulltext/unique word
376         $noIndex = (
377         (
378                 strpos($sql, 'INDEX') === false
379         ) && (
380                 strpos($sql, 'KEY') === false
381         ) && (
382                 strpos($sql, 'FULLTEXT') === false
383         ) && (
384                 strpos($sql, 'UNIQUE') === false
385         )
386         );
387
388         // Extract table name
389         $tableArray = explode(' ', $sql);
390         $tableName = str_replace('`', '', $tableArray[2]);
391
392         // Shall we add/drop?
393         if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
394                 // Try two columns, one should fix
395                 foreach (array(4,5) as $idx) {
396                         // And column name as well
397                         $columnName = str_replace('`', '', $tableArray[$idx]);
398
399                         // Get column information
400                         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
401                                 array($tableName, $columnName), __FILE__, __LINE__);
402
403                         // Do we have no entry on ADD or an entry on DROP?
404                         // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
405                         if (((SQL_NUMROWS($result) == '0') && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
406                                 // Do the query
407                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
408                                 $result = SQL_QUERY($sql, $F, $L, false);
409
410                                 // Skip further attempt(s)
411                                 break;
412                         } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == '0') && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
413                                 // Abort here because it is alreay there
414                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
415                                 break;
416                         } elseif ($columnName != 'KEY') {
417                                 // Something didn't fit
418                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
419                         }
420                 } // END - foreach
421         } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
422                 // Skip this query silently
423                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
424         } elseif ($noIndex === false) {
425                 // And column name as well
426                 //* DEBUG: */ print __LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>';
427                 $keyName = str_replace('`', '', $tableArray[5]);
428
429                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
430                 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
431                         // Init loop
432                         $begin = 1; $keyName = ',';
433                         while (strpos($keyName, ',') !== false) {
434                                 // Use last
435                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
436                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
437
438                                 // Remove brackes
439                                 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
440                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
441
442                                 // Continue
443                                 $begin++;
444                         } // END while
445                 } // END - if
446
447                 // Show indexes
448                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FILE__, __LINE__);
449
450                 // Non-skipping is default for ADD
451                 $skip = false;
452
453                 // But should we DROP?
454                 if ($tableArray[3] == 'DROP') {
455                         // Then skip if nothing found!
456                         $skip = true;
457                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
458                 } // END - if
459
460                 // Walk through all
461                 while ($content = SQL_FETCHARRAY($result)) {
462                         // Is it found?
463                         //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
464                         if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
465                                 // Skip this query!
466                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
467                                 $skip = true;
468                                 break;
469                         } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
470                                 // Don't skip this!
471                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
472                                 $skip = false;
473                                 break;
474                         }
475                 } // END - while
476
477                 // Free result
478                 SQL_FREERESULT($result);
479
480                 // Shall we run it?
481                 if ($skip === false) {
482                         // Send it to the SQL_QUERY() function
483                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
484                         $result = SQL_QUERY($sql, $F, $L, false);
485                 } else {
486                         // Not executed
487                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
488                 }
489         } else {
490                 // Other ALTER TABLE query
491                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
492                 $result = SQL_QUERY($sql, $F, $L, false);
493         }
494
495         // Return result
496         return $result;
497 }
498
499 // Getter for SQL link
500 function SQL_GET_LINK () {
501         // Init link
502         $link = null;
503
504         // Is it in the globals?
505         if (isset($GLOBALS['sql_link'])) {
506                 // Then take it
507                 $link = $GLOBALS['sql_link'];
508         } // END - if
509
510         // Return it
511         return $link;
512 }
513
514 // Setter for link
515 function SQL_SET_LINK ($link) {
516         // Is this a resource or null?
517         if ((!is_resource($link)) && (!is_null($link))) {
518                 // This should never happen!
519                 debug_report_bug(sprintf("link is not resource or null. Type: %s", gettype($link)));
520         } // END - if
521
522         // Set it
523         $GLOBALS['sql_link'] = $link;
524 }
525
526 // Checks if the link is up
527 function SQL_IS_LINK_UP () {
528         // Default is not up
529         $linkUp = false;
530
531         // Do we have cached this?
532         if (isset($GLOBALS['sql_link_res'])) {
533                 // Then use this
534                 $linkUp = $GLOBALS['sql_link_res'];
535         } else {
536                 // Get it
537                 $linkUp = is_resource(SQL_GET_LINK());
538
539                 // And cache it
540                 $GLOBALS['sql_link_res'] = $linkUp;
541         }
542
543         // Return the result
544         return $linkUp;
545 }
546
547 // [EOF]
548 ?>