Migration of stelzi's commit 1022 with some changes so we have a nicer code. See...
[mailer.git] / inc / wrapper-functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 04/04/2009 *
4  * ===============                              Last change: 04/04/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : wrapper-functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Wrapper functions                                *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Wrapper-Funktionen                               *
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 - 2008 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         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
42         require($INC);
43 } // END - if
44
45 // Read a given file
46 function readFromFile ($FQFN, $sqlPrepare = false) {
47         // Load the file
48         if (function_exists('file_get_contents')) {
49                 // Use new function
50                 $content = file_get_contents($FQFN);
51         } else {
52                 // Fall-back to implode-file chain
53                 $content = implode('', file($FQFN));
54         }
55
56         // Prepare SQL queries?
57         if ($sqlPrepare === true) {
58                 // Remove some unwanted chars
59                 $content = str_replace("\r", '', $content);
60                 $content = str_replace("\n\n", "\n", $content);
61         } // END - if
62
63         // Return the content
64         return $content;
65 }
66
67 // Writes content to a file
68 function writeToFile ($FQFN, $content) {
69         // Is the file writeable?
70         if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!changeMode($FQFN, 0644))) {
71                 // Not writeable!
72                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
73
74                 // Failed! :(
75                 return false;
76         } // END - if
77
78         // By default all is failed...
79         $return = false;
80
81         // Is the function there?
82         if (function_exists('file_put_contents')) {
83                 // Write it directly
84                 $return = file_put_contents($FQFN, $content);
85         } else {
86                 // Write it with fopen
87                 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
88                 fwrite($fp, $content);
89                 fclose($fp);
90
91                 // Set CHMOD rights
92                 $return = changeMode($FQFN, 0644);
93         }
94
95         // Return status
96         return $return;
97 }
98
99 // Clears the output buffer. This function does *NOT* backup sent content.
100 function clearOutputBuffer () {
101         // Trigger an error on failure
102         if (!ob_end_clean()) {
103                 // Failed!
104                 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
105         } // END - if
106 }
107
108 // Loads an include file and logs any missing files for debug purposes
109 function loadInclude ($INC) {
110         // Add the path. This is why we need a trailing slash in config.php
111         $FQFN = constant('PATH') . $INC;
112
113         // Is the include file there?
114         if (!isIncludeReadable($INC)) {
115                 // Not there so log it
116                 debug_report_bug(sprintf("Include file %s not found.", $INC));
117                 return false;
118         } // END - if
119
120         // Try to load it
121         require($FQFN);
122 }
123
124 // Loads an include file once
125 function loadIncludeOnce ($INC) {
126         // Is it not loaded?
127         if (!isset($GLOBALS['load_once'][$INC])) {
128                 // Mark it as loaded
129                 $GLOBALS['load_once'][$INC] = "loaded";
130
131                 // Then try to load it
132                 loadInclude($INC);
133         } // END - if
134 }
135
136 // Checks wether an include file (non-FQFN better) is readable
137 function isIncludeReadable ($INC) {
138         // Construct FQFN
139         $FQFN = constant('PATH') . $INC;
140
141         // Is it readable?
142         return isFileReadable($FQFN);
143 }
144
145 // Encode strings
146 // @TODO Implement $compress
147 function encodeString ($str, $compress = true) {
148         $str = urlencode(base64_encode(compileUriCode($str)));
149         return $str;
150 }
151
152 // Decode strings encoded with encodeString()
153 // @TODO Implement $decompress
154 function decodeString ($str, $decompress = true) {
155         $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
156         return $str;
157 }
158
159 // Smartly adds slashes
160 function smartAddSlashes ($unquoted) {
161         $unquoted = str_replace("\\", '', $unquoted);
162         return addslashes($unquoted);
163 }
164
165 // Decode entities in a nicer way
166 function decodeEntities ($str) {
167         // Decode the entities to UTF-8 now
168         $decodedString = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
169
170         // Return decoded string
171         return $decodedString;
172 }
173
174 // Merges an array together but only if both are arrays
175 function merge_array ($array1, $array2) {
176         // Are both an array?
177         if ((is_array($array1)) && (is_array($array2))) {
178                 // Merge all together
179                 return array_merge($array1, $array2);
180         } elseif (is_array($array1)) {
181                 // Return left array
182                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
183                 return $array1;
184         } elseif (is_array($array2)) {
185                 // Return right array
186                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
187                 return $array2;
188         }
189
190         // Both are not arrays
191         debug_report_bug(__FUNCTION__.": No arrays provided!");
192 }
193
194 // Check if given FQFN is a readable file
195 function isFileReadable ($FQFN) {
196         // Check all...
197         return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
198 }
199
200 // Checks wether the given FQFN is a directory and not .,.. or .svn
201 function isDirectory ($FQFN) {
202         // Generate baseName
203         $baseName = basename($FQFN);
204
205         // Check it
206         $isDirectory = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
207
208         // Return the result
209         return $isDirectory;
210 }
211
212 // "Getter" for remote IP number
213 function detectRemoteAddr () {
214         // Get remote ip from environment
215         $remoteAddr = determineRealRemoteAddress();
216
217         // Is removeip installed?
218         if (EXT_IS_ACTIVE('removeip')) {
219                 // Then anonymize it
220                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
221         } // END - if
222
223         // Return it
224         return $remoteAddr;
225 }
226
227 // "Getter" for remote hostname
228 function detectRemoteHostname () {
229         // Get remote ip from environment
230         $remoteHost = getenv('REMOTE_HOST');
231
232         // Is removeip installed?
233         if (EXT_IS_ACTIVE('removeip')) {
234                 // Then anonymize it
235                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
236         } // END - if
237
238         // Return it
239         return $remoteHost;
240 }
241
242 // "Getter" for user agent
243 function detectUserAgent () {
244         // Get remote ip from environment
245         $userAgent = getenv('HTTP_USER_AGENT');
246
247         // Is removeip installed?
248         if (EXT_IS_ACTIVE('removeip')) {
249                 // Then anonymize it
250                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
251         } // END - if
252
253         // Return it
254         return $userAgent;
255 }
256
257 // "Getter" for referer
258 function detectReferer () {
259         // Get remote ip from environment
260         $referer = getenv('HTTP_REFERER');
261
262         // Is removeip installed?
263         if (EXT_IS_ACTIVE('removeip')) {
264                 // Then anonymize it
265                 $referer = GET_ANONYMOUS_REFERER($referer);
266         } // END - if
267
268         // Return it
269         return $referer;
270 }
271
272 // Check wether we are installing
273 function isInstalling () {
274         $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
275         //* DEBUG: */ var_dump($installing);
276         return $installing;
277 }
278
279 // Check wether this script is installed
280 function isInstalled () {
281         return ((getConfig('MXCHANGE_INSTALLED') == 'Y') || (isIncludeReadable('inc/cache/config-local.php')));
282 }
283
284 // Check wether an admin is registered
285 function isAdminRegistered () {
286         return (getConfig('ADMIN_REGISTERED') == 'Y');
287 }
288
289 // Checks wether the reset mode is active
290 function isResetModeEnabled () {
291         // Now simply check it
292         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
293 }
294
295 // Checks wether the debug mode is enabled
296 function isDebugModeEnabled () {
297         // Simply check it
298         return (getConfig('DEBUG_MODE') == 'Y');
299 }
300
301 // Checks wether the cache instance is valid
302 function isCacheInstanceValid () {
303         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
304 }
305
306 // Copies a file from source to destination and verifies if that goes fine.
307 // This function should wrap the copy() command and make a nicer debug backtrace
308 // even if there is no xdebug extension installed.
309 function copyFileVerified ($source, $dest, $chmod = '') {
310         // Failed is the default
311         $status = false;
312
313         // Is the source file there?
314         if (!isFileReadable($source)) {
315                 // Then abort here
316                 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
317         } // END - if
318
319         // Is the target directory there?
320         if (!isDirectory(dirname($dest))) {
321                 // Then abort here
322                 debug_report_bug('Cannot find directory ' . str_replace(constant('PATH'), '', dirname($dest)) . '.');
323         } // END - if
324
325         // Now try to copy it
326         if (!copy($source, $dest)) {
327                 // Something went wrong
328                 debug_report_bug('copy() has failed to copy the file.');
329         } // END - if
330
331         // If there are chmod rights set, apply them
332         if (!empty($chmod)) {
333                 // Try to apply them
334                 $status = changeMode($dest, $chmod);
335         } else {
336                 // All fine
337                 $status = true;
338         }
339
340         // All fine
341         return $status;
342 }
343
344 // Wrapper function for header()
345 // Send a header but checks before if we can do so
346 function sendHeader ($header) {
347         // Is the header already sent?
348         if (headers_sent()) {
349                 // Then abort here
350                 debug_report_bug('Headers already sent!');
351         } // END - if
352
353         // Send the header
354         header($header);
355 }
356
357 // Wrapper function for chmod()
358 // @TODO Do some more sanity check here
359 function changeMode ($FQFN, $mode) {
360         // Is the file/directory there?
361         if ((!isFile($FQFN)) && (!isDirectory($FQFN))) {
362                 // Neither, so abort here
363                 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
364         } // END - if
365
366         // Try to set them
367         chmod($FQFN, $mode);
368 }
369
370 // Wrapper for $_POST['sel']
371 function countPostSelection () {
372         return countSelection(REQUEST_POST('sel'));
373 }
374
375 // Checks wether the config-local.php is loaded
376 function isConfigLocalLoaded () {
377         return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
378 }
379
380 // [EOF]
381 ?>