Comments added (were absend)
[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 (
282         (
283         // New config file found and loaded
284         getConfig('MXCHANGE_INSTALLED') == 'Y'
285         ) || (
286         // Fall-back!
287         isIncludeReadable('inc/config.php')
288         ) || (
289         (
290         // New config file found, but not yet read
291         isIncludeReadable('inc/cache/config-local.php')
292         ) && (
293         (
294         // Only new config file is found
295         !isIncludeReadable('inc/config.php')
296         ) || (
297         // Is installation mode
298         isInstalling()
299         )
300         )
301         )
302         );
303 }
304
305 // Check wether an admin is registered
306 function isAdminRegistered () {
307         return (getConfig('ADMIN_REGISTERED') == 'Y');
308 }
309
310 // Checks wether the reset mode is active
311 function isResetModeEnabled () {
312         // Now simply check it
313         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
314 }
315
316 // Checks wether the debug mode is enabled
317 function isDebugModeEnabled () {
318         // Simply check it
319         return (getConfig('DEBUG_MODE') == 'Y');
320 }
321
322 // Checks wether the cache instance is valid
323 function isCacheInstanceValid () {
324         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
325 }
326
327 // Copies a file from source to destination and verifies if that goes fine.
328 // This function should wrap the copy() command and make a nicer debug backtrace
329 // even if there is no xdebug extension installed.
330 function copyFileVerified ($source, $dest, $chmod = '') {
331         // Failed is the default
332         $status = false;
333
334         // Is the source file there?
335         if (!isFileReadable($source)) {
336                 // Then abort here
337                 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
338         } // END - if
339
340         // Is the target directory there?
341         if (!isDirectory(dirname($dest))) {
342                 // Then abort here
343                 debug_report_bug('Cannot find directory ' . str_replace(constant('PATH'), '', dirname($dest)) . '.');
344         } // END - if
345
346         // Now try to copy it
347         if (!copy($source, $dest)) {
348                 // Something went wrong
349                 debug_report_bug('copy() has failed to copy the file.');
350         } // END - if
351
352         // If there are chmod rights set, apply them
353         if (!empty($chmod)) {
354                 // Try to apply them
355                 $status = changeMode($dest, $chmod);
356         } else {
357                 // All fine
358                 $status = true;
359         }
360
361         // All fine
362         return $status;
363 }
364
365 // Wrapper function for header()
366 // Send a header but checks before if we can do so
367 function sendHeader ($header) {
368         // Is the header already sent?
369         if (headers_sent()) {
370                 // Then abort here
371                 debug_report_bug('Headers already sent!');
372         } // END - if
373
374         // Send the header
375         header($header);
376 }
377
378 // Wrapper function for chmod()
379 // @TODO Do some more sanity check here
380 function changeMode ($FQFN, $mode) {
381         // Is the file/directory there?
382         if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
383                 // Neither, so abort here
384                 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
385         } // END - if
386
387         // Try to set them
388         chmod($FQFN, $mode);
389 }
390
391 // Wrapper for unlink()
392 function removeFile ($FQFN) {
393         // Is the file there?
394         if (isFileReadable($FQFN)) {
395                 // Yes, so remove it
396                 return unlink($FQFN);
397         } // END - if
398
399         // All fine if no file was removed. If we change this to 'false' or rewrite
400         // above if() block it would be to restrictive.
401         return true;
402 }
403
404 // Wrapper for $_POST['sel']
405 function countPostSelection () {
406         return countSelection(REQUEST_POST('sel'));
407 }
408
409 // Checks wether the config-local.php is loaded
410 function isConfigLocalLoaded () {
411         return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
412 }
413
414 // [EOF]
415 ?>