Fix for wrong SERVER_NAME usage (may cause trouble)
[mailer.git] / inc / sql-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/23/2009 *
4  * ===================                          Last change: 10/23/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : sql-functions.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : SQL functions to handle queries                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : SQL-Funktionen fuer Queries                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Init SQLs array
44 function initSqls () {
45         // Init generic array
46         setSqlsArray(array('generic' => array()));
47 }
48
49 // Checks whether the sqls array is initialized
50 function isSqlsInitialized () {
51         return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
52 }
53
54 // Setter for SQLs array
55 function setSqlsArray ($SQLs) {
56         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count()='.count($SQLs));
57         $GLOBALS['sqls'] = (array) $SQLs;
58 }
59
60 // Remover for SQLs array
61 function unsetSqls () {
62         unset($GLOBALS['sqls']);
63 }
64
65 // Getter for SQLs array
66 function getSqls () {
67         return $GLOBALS['sqls'];
68 }
69
70 // Add an SQL to the list
71 function addSql ($sql) {
72         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("sql=%s, count=%d", $sql, countSqls()));
73         array_push($GLOBALS['sqls']['generic'], $sql);
74 }
75
76 // Merge SQLs together
77 function mergeSqls ($SQLs, $type = '') {
78         // Should we merge full array or partial?
79         if (empty($type)) {
80                 // Merge full array (may kill entries)
81                 setSqlsArray(merge_array(getSqls(), $SQLs));
82         } else {
83                 // Merge sub array, so get it
84                 $array = getSqls();
85
86                 // Is the sub array there?
87                 if (isset($array[$type])) {
88                         // Then get it and merge it with the new one
89                         $array[$type] = merge_array($array[$type], $SQLs);
90                 } else {
91                         // Use new array
92                         $array[$type] = $SQLs;
93                 }
94
95                 // Call again..
96                 mergeSqls($array);
97         }
98 }
99
100 // Counter for SQLs array
101 function countSqls () {
102         // Default is false
103         $count = '0';
104
105         // Is the array there?
106         if (isSqlsInitialized()) {
107                 // Then count it
108                 $count = count($GLOBALS['sqls']);
109                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
110         } // END - if
111
112         // Return it
113         return $count;
114 }
115
116 // Checks whether the SQLs array is filled
117 function isSqlsValid () {
118         //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . intval(isSqlsInitialized()) . '/' . countSqls() . '/' . getCurrentExtensionName());
119         return (
120                 (
121                         isSqlsInitialized()
122                 ) && (
123                         countSqls() > 0
124                 )
125         );
126 }
127
128 // Generates an updating SQL query from given array
129 function getUpdateSqlFromArray ($array, $tableName, $whereColumn, $whereData, $excludedFields, $multiDimId = NULL) {
130         // Begin SQL query
131         $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_' . $tableName . '` SET ';
132
133         // Insert all data
134         foreach ($array as $entry => $value) {
135                 // Skip login/id entry
136                 if (in_array($entry, $excludedFields)) {
137                         continue;
138                 } // END - if
139
140                 // Is there a non-string (e.g. number, NULL, SQL function or back-tick at the beginning?
141                 if (is_null($multiDimId)) {
142                         // Handle one-dimensional data
143                         if (is_null($value)) {
144                                 // NULL detected
145                                 $SQL .= '`' . $entry . '`=NULL,';
146                         } elseif ((substr($value, -2, 2) == '()') || (substr($value, 0, 1) == '`')) {
147                                 // SQL function needs no ticks (')
148                                 $SQL .= '`' . $entry . '`=' . SQL_ESCAPE($value) . ',';
149                         } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '')  {
150                                 // No need for ticks (')
151                                 $SQL .= '`' . $entry . '`=' . $value . ',';
152                         } else {
153                                 // Strings need ticks (') around them
154                                 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value) . "',";
155                         }
156                 } else {
157                         // Handle multi-dimensional data
158                         if (is_null($value[$multiDimId])) {
159                                 // NULL detected
160                                 $SQL .= '`' . $entry . '`=NULL,';
161                         } elseif ((substr($value[$multiDimId], -2, 2) == '()') || (substr($value[$multiDimId], 0, 1) == '`')) {
162                                 // SQL function needs no ticks (')
163                                 $SQL .= '`' . $entry . '`=' . SQL_ESCAPE($value[$multiDimId]) . ',';
164                         } elseif (('' . bigintval($value[$multiDimId], TRUE, FALSE) . '' == '' . $value[$multiDimId] . ''))  {
165                                 // No need for ticks (')
166                                 $SQL .= '`' . $entry . '`=' . $value[$multiDimId] . ',';
167                         } else {
168                                 // Strings need ticks (') around them
169                                 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$multiDimId]) . "',";
170                         }
171                 }
172         } // END - foreach
173
174         // Remove last 2 chars and finish query
175         $SQL = substr($SQL, 0, -1) . ' WHERE `' . $whereColumn . '`=' . $whereData . ' LIMIT 1';
176
177         // Return SQL query
178         return $SQL;
179 }
180
181 // "Getter" for an "INSERT INTO" SQL query
182 function getInsertSqlFromArray ($array, $tableName) {
183         // Init SQL
184         $SQL = 'INSERT INTO
185 `{?_MYSQL_PREFIX?}_' . $tableName . '`
186 (
187 `' . implode('`, `', array_keys(postRequestArray())) . '`
188 ) VALUES (';
189
190         // Walk through all entries
191         foreach (postRequestArray() as $key => $value) {
192                 // Log debug message
193                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',key=' . $key . ',value=' . $value);
194
195                 // Add all entries
196                 if (is_null($value)) {
197                         // Add NULL
198                         $SQL .= 'NULL,';
199                 } elseif (substr($value, -2, 2) == '()') {
200                         // SQL function needs no ticks (')
201                         $SQL .= SQL_ESCAPE($value) . ',';
202                 } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '') {
203                         // Number detected, no need for ticks (')
204                         $SQL .= bigintval($value) . ',';
205                 } elseif ('' . (float) $value . '' == '' . $value . '') {
206                         // Float number detected
207                         $SQL .= sprintf('%01.5f', $value);
208                 } else {
209                         // Everything else might be a string, so add ticks around it
210                         $SQL .= chr(39) . SQL_ESCAPE($value) . chr(39) . ',';
211                 }
212         } // END - foreach
213
214         // Finish SQL query
215         $SQL = substr($SQL, 0, -1) . ')';
216
217         // Return SQL query
218         return $SQL;
219 }
220
221 // Initializes the SQL link by bringing it up if set
222 function initSqlLink () {
223         // Do this only if link is down
224         assert(!SQL_IS_LINK_UP());
225
226         // Is the configuration data set?
227         if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
228                 // Remove cache
229                 unset($GLOBALS['is_sql_link_up']);
230
231                 // Connect to DB
232                 SQL_CONNECT($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FILE__, __LINE__);
233
234                 // Is the link valid?
235                 if (SQL_IS_LINK_UP()) {
236                         // Enable exit on error
237                         enableExitOnError();
238
239                         // Is it a valid resource?
240                         if (SQL_SELECT_DB($GLOBALS['mysql']['dbase'], __FILE__, __LINE__) === TRUE) {
241                                 // Set database name (required for ext-optimize and ifSqlTableExists())
242                                 setConfigEntry('__DB_NAME', $GLOBALS['mysql']['dbase']);
243
244                                 // Remove MySQL array from namespace
245                                 unset($GLOBALS['mysql']);
246
247                                 // Load cache
248                                 loadIncludeOnce('inc/load_cache.php');
249                         } else {
250                                 // Wrong database?
251                                 reportBug(__FILE__, __LINE__, 'Wrong database selected.');
252                         }
253                 } else {
254                         // No link to database!
255                         reportBug(__FILE__, __LINE__, 'Database link is not yet up.');
256                 }
257         } else {
258                 // Maybe you forgot to enter your database login?
259                 reportBug(__FILE__, __LINE__, 'Database login is missing.');
260         }
261 }
262
263 // [EOF]
264 ?>