6ccafda6272d4affcb881b1f4ba9a7a9bc94ce23
[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         // Sanity-check if file is there (should be there, but just to make it sure)
48         if (!isFileReadable($FQFN)) {
49                 // This should not happen
50                 debug_report_bug(__FUNCTION__.': File ' . basename($FQFN) . ' is not readable!');
51         } // END - if
52
53         // Load the file
54         if (function_exists('file_get_contents')) {
55                 // Use new function
56                 $content = file_get_contents($FQFN);
57         } else {
58                 // Fall-back to implode-file chain
59                 $content = implode('', file($FQFN));
60         }
61
62         // Prepare SQL queries?
63         if ($sqlPrepare === true) {
64                 // Remove some unwanted chars
65                 $content = str_replace("\r", '', $content);
66                 $content = str_replace("\n\n", "\n", $content);
67         } // END - if
68
69         // Return the content
70         return $content;
71 }
72
73 // Writes content to a file
74 function writeToFile ($FQFN, $content) {
75         // Is the file writeable?
76         if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!changeMode($FQFN, 0644))) {
77                 // Not writeable!
78                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
79
80                 // Failed! :(
81                 return false;
82         } // END - if
83
84         // By default all is failed...
85         $return = false;
86
87         // Is the function there?
88         if (function_exists('file_put_contents')) {
89                 // Write it directly
90                 $return = file_put_contents($FQFN, $content);
91         } else {
92                 // Write it with fopen
93                 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
94                 fwrite($fp, $content);
95                 fclose($fp);
96
97                 // Set CHMOD rights
98                 $return = changeMode($FQFN, 0644);
99         }
100
101         // Return status
102         return $return;
103 }
104
105 // Clears the output buffer. This function does *NOT* backup sent content.
106 function clearOutputBuffer () {
107         // Trigger an error on failure
108         if (!ob_end_clean()) {
109                 // Failed!
110                 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
111         } // END - if
112 }
113
114 // Loads an include file and logs any missing files for debug purposes
115 function loadInclude ($INC) {
116         // Add the path. This is why we need a trailing slash in config.php
117         $FQFN = constant('PATH') . $INC;
118
119         // Is the include file there?
120         if (!isIncludeReadable($INC)) {
121                 // Not there so log it
122                 debug_report_bug(sprintf("Include file %s not found.", $INC));
123                 return false;
124         } // END - if
125
126         // Try to load it
127         require($FQFN);
128 }
129
130 // Loads an include file once
131 function loadIncludeOnce ($INC) {
132         // Is it not loaded?
133         if (!isset($GLOBALS['load_once'][$INC])) {
134                 // Mark it as loaded
135                 $GLOBALS['load_once'][$INC] = "loaded";
136
137                 // Then try to load it
138                 loadInclude($INC);
139         } // END - if
140 }
141
142 // Checks wether an include file (non-FQFN better) is readable
143 function isIncludeReadable ($INC) {
144         // Construct FQFN
145         $FQFN = constant('PATH') . $INC;
146
147         // Is it readable?
148         return isFileReadable($FQFN);
149 }
150
151 // Encode strings
152 // @TODO Implement $compress
153 function encodeString ($str, $compress = true) {
154         $str = urlencode(base64_encode(compileUriCode($str)));
155         return $str;
156 }
157
158 // Decode strings encoded with encodeString()
159 // @TODO Implement $decompress
160 function decodeString ($str, $decompress = true) {
161         $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
162         return $str;
163 }
164
165 // Smartly adds slashes
166 function smartAddSlashes ($unquoted) {
167         $unquoted = str_replace("\\", '', $unquoted);
168         return addslashes($unquoted);
169 }
170
171 // Decode entities in a nicer way
172 function decodeEntities ($str) {
173         // Decode the entities to UTF-8 now
174         $decodedString = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
175
176         // Return decoded string
177         return $decodedString;
178 }
179
180 // Merges an array together but only if both are arrays
181 function merge_array ($array1, $array2) {
182         // Are both an array?
183         if ((is_array($array1)) && (is_array($array2))) {
184                 // Merge all together
185                 return array_merge($array1, $array2);
186         } elseif (is_array($array1)) {
187                 // Return left array
188                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
189                 return $array1;
190         } elseif (is_array($array2)) {
191                 // Return right array
192                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
193                 return $array2;
194         }
195
196         // Both are not arrays
197         debug_report_bug(__FUNCTION__.": No arrays provided!");
198 }
199
200 // Check if given FQFN is a readable file
201 function isFileReadable ($FQFN) {
202         // Check all...
203         return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
204 }
205
206 // Checks wether the given FQFN is a directory and not .,.. or .svn
207 function isDirectory ($FQFN) {
208         // Generate baseName
209         $baseName = basename($FQFN);
210
211         // Check it
212         $isDirectory = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
213
214         // Return the result
215         return $isDirectory;
216 }
217
218 // "Getter" for remote IP number
219 function detectRemoteAddr () {
220         // Get remote ip from environment
221         $remoteAddr = determineRealRemoteAddress();
222
223         // Is removeip installed?
224         if (EXT_IS_ACTIVE('removeip')) {
225                 // Then anonymize it
226                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
227         } // END - if
228
229         // Return it
230         return $remoteAddr;
231 }
232
233 // "Getter" for remote hostname
234 function detectRemoteHostname () {
235         // Get remote ip from environment
236         $remoteHost = getenv('REMOTE_HOST');
237
238         // Is removeip installed?
239         if (EXT_IS_ACTIVE('removeip')) {
240                 // Then anonymize it
241                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
242         } // END - if
243
244         // Return it
245         return $remoteHost;
246 }
247
248 // "Getter" for user agent
249 function detectUserAgent () {
250         // Get remote ip from environment
251         $userAgent = getenv('HTTP_USER_AGENT');
252
253         // Is removeip installed?
254         if (EXT_IS_ACTIVE('removeip')) {
255                 // Then anonymize it
256                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
257         } // END - if
258
259         // Return it
260         return $userAgent;
261 }
262
263 // "Getter" for referer
264 function detectReferer () {
265         // Get remote ip from environment
266         $referer = getenv('HTTP_REFERER');
267
268         // Is removeip installed?
269         if (EXT_IS_ACTIVE('removeip')) {
270                 // Then anonymize it
271                 $referer = GET_ANONYMOUS_REFERER($referer);
272         } // END - if
273
274         // Return it
275         return $referer;
276 }
277
278 // Check wether we are installing
279 function isInstalling () {
280         $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
281         //* DEBUG: */ var_dump($installing);
282         return $installing;
283 }
284
285 // Check wether this script is installed
286 function isInstalled () {
287         return (
288         (
289                 // New config file found and loaded
290                 getConfig('MXCHANGE_INSTALLED') == 'Y'
291         ) || (
292                 // Fall-back!
293                 isIncludeReadable('inc/config.php')
294         ) || (
295                 (
296                         // New config file found, but not yet read
297                         isIncludeReadable('inc/cache/config-local.php')
298                 ) && (
299                         (
300                                 // Only new config file is found
301                                 !isIncludeReadable('inc/config.php')
302                         ) || (
303                                 // Is installation mode
304                                 isInstalling()
305                         )
306                 )
307         )
308         );
309 }
310
311 // Check wether an admin is registered
312 function isAdminRegistered () {
313         return (getConfig('ADMIN_REGISTERED') == 'Y');
314 }
315
316 // Checks wether the reset mode is active
317 function isResetModeEnabled () {
318         // Now simply check it
319         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
320 }
321
322 // Checks wether the debug mode is enabled
323 function isDebugModeEnabled () {
324         // Simply check it
325         return (getConfig('DEBUG_MODE') == 'Y');
326 }
327
328 // Checks wether we shall debug regular expressions
329 function isDebugRegExpressionEnabled () {
330         // Simply check it
331         return (getConfig('DEBUG_REGEX') == 'Y');
332 }
333
334 // Checks wether the cache instance is valid
335 function isCacheInstanceValid () {
336         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
337 }
338
339 // Copies a file from source to destination and verifies if that goes fine.
340 // This function should wrap the copy() command and make a nicer debug backtrace
341 // even if there is no xdebug extension installed.
342 function copyFileVerified ($source, $dest, $chmod = '') {
343         // Failed is the default
344         $status = false;
345
346         // Is the source file there?
347         if (!isFileReadable($source)) {
348                 // Then abort here
349                 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
350         } // END - if
351
352         // Is the target directory there?
353         if (!isDirectory(dirname($dest))) {
354                 // Then abort here
355                 debug_report_bug('Cannot find directory ' . str_replace(constant('PATH'), '', dirname($dest)) . '.');
356         } // END - if
357
358         // Now try to copy it
359         if (!copy($source, $dest)) {
360                 // Something went wrong
361                 debug_report_bug('copy() has failed to copy the file.');
362         } // END - if
363
364         // If there are chmod rights set, apply them
365         if (!empty($chmod)) {
366                 // Try to apply them
367                 $status = changeMode($dest, $chmod);
368         } else {
369                 // All fine
370                 $status = true;
371         }
372
373         // All fine
374         return $status;
375 }
376
377 // Wrapper function for header()
378 // Send a header but checks before if we can do so
379 function sendHeader ($header) {
380         // Is the header already sent?
381         if (headers_sent()) {
382                 // Then abort here
383                 debug_report_bug('Headers already sent!');
384         } // END - if
385
386         // Send the header
387         header(trim($header));
388 }
389
390 // Wrapper function for chmod()
391 // @TODO Do some more sanity check here
392 function changeMode ($FQFN, $mode) {
393         // Is the file/directory there?
394         if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
395                 // Neither, so abort here
396                 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
397         } // END - if
398
399         // Try to set them
400         chmod($FQFN, $mode);
401 }
402
403 // Wrapper for unlink()
404 function removeFile ($FQFN) {
405         // Is the file there?
406         if (isFileReadable($FQFN)) {
407                 // Yes, so remove it
408                 return unlink($FQFN);
409         } // END - if
410
411         // All fine if no file was removed. If we change this to 'false' or rewrite
412         // above if() block it would be to restrictive.
413         return true;
414 }
415
416 // Wrapper for $_POST['sel']
417 function countPostSelection () {
418         return countSelection(REQUEST_POST('sel'));
419 }
420
421 // Checks wether the config-local.php is loaded
422 function isConfigLocalLoaded () {
423         return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
424 }
425
426 // Checks wether a nickname or userid was entered and caches the result
427 function isNicknameUsed ($userid) {
428         // Default is false
429         $isUsed = false;
430
431         // Is the cache there
432         if (isset($GLOBALS['cache_probe_nicknames'][$userid])) {
433                 // Then use it
434                 $isUsed = $GLOBALS['cache_probe_nicknames'][$userid];
435         } else {
436                 // Determine it
437                 $isUsed = ((EXT_IS_ACTIVE('nickname')) && (('' . round($userid) . '') != $userid));
438
439                 // And write it to the cache
440                 $GLOBALS['cache_probe_nicknames'][$userid] = $isUsed;
441         }
442
443         // Return the result
444         return $isUsed;
445 }
446
447 // Getter for 'what' value
448 function getWhat () {
449         // Default is null
450         $what = null;
451
452         // Is the value set?
453         if (isWhatSet(true)) {
454                 // Then use it
455                 $what = $GLOBALS['what'];
456         } // END - if
457
458         // Return it
459         return $what;
460 }
461
462 // Setter for 'what' value
463 function setWhat ($newWhat) {
464         $GLOBALS['what'] = SQL_ESCAPE($newWhat);
465 }
466
467 // Setter for 'what' from configuration
468 function setWhatFromConfig ($configEntry) {
469         // Get 'what' from config
470         $what = getConfig($configEntry);
471
472         // Set it
473         setWhat($what);
474 }
475
476 // Checks wether what is set and optionally aborts on miss
477 function isWhatSet ($abortOnMiss =  false) {
478         // Check for it
479         $isset = (isset($GLOBALS['what']));
480
481         // Should we abort here?
482         if (($abortOnMiss === true) && ($isset === false)) {
483                 // Output backtrace
484                 debug_report_bug('what is empty.');
485         } // END - if
486
487         // Return it
488         return $isset;
489 }
490
491 // Getter for 'action' value
492 function getAction () {
493         // Default is null
494         $action = null;
495
496         // Is the value set?
497         if (isActionSet(true)) {
498                 // Then use it
499                 $action = $GLOBALS['action'];
500         } // END - if
501
502         // Return it
503         return $action;
504 }
505
506 // Setter for 'action' value
507 function setAction ($newAction) {
508         $GLOBALS['action'] = SQL_ESCAPE($newAction);
509 }
510
511 // Checks wether action is set and optionally aborts on miss
512 function isActionSet ($abortOnMiss =  false) {
513         // Check for it
514         $isset = (isset($GLOBALS['action']));
515
516         // Should we abort here?
517         if (($abortOnMiss === true) && ($isset === false)) {
518                 // Output backtrace
519                 debug_report_bug('action is empty.');
520         } // END - if
521
522         // Return it
523         return $isset;
524 }
525
526 // Getter for 'module' value
527 function getModule () {
528         // Default is null
529         $module = null;
530
531         // Is the value set?
532         if (isModuleSet(true)) {
533                 // Then use it
534                 $module = $GLOBALS['module'];
535         } // END - if
536
537         // Return it
538         return $module;
539 }
540
541 // Setter for 'module' value
542 function setModule ($newModule) {
543         $GLOBALS['module'] = SQL_ESCAPE($newModule);
544 }
545
546 // Checks wether module is set and optionally aborts on miss
547 function isModuleSet ($abortOnMiss =  false) {
548         // Check for it
549         $isset = (!empty($GLOBALS['module']));
550
551         // Should we abort here?
552         if (($abortOnMiss === true) && ($isset === false)) {
553                 // Output backtrace
554                 debug_report_bug('module is empty.');
555         } // END - if
556
557         // Return it
558         return $isset;
559 }
560
561 // Getter for 'output_mode' value
562 function getOutputMode () {
563         // Default is null
564         $output_mode = null;
565
566         // Is the value set?
567         if (isOutputModeSet(true)) {
568                 // Then use it
569                 $output_mode = $GLOBALS['output_mode'];
570         } // END - if
571
572         // Return it
573         return $output_mode;
574 }
575
576 // Setter for 'output_mode' value
577 function setOutputMode ($newOutputMode) {
578         $GLOBALS['output_mode'] = SQL_ESCAPE($newOutputMode);
579 }
580
581 // Checks wether output_mode is set and optionally aborts on miss
582 function isOutputModeSet ($abortOnMiss =  false) {
583         // Check for it
584         $isset = (isset($GLOBALS['output_mode']));
585
586         // Should we abort here?
587         if (($abortOnMiss === true) && ($isset === false)) {
588                 // Output backtrace
589                 debug_report_bug('output_mode is empty.');
590         } // END - if
591
592         // Return it
593         return $isset;
594 }
595
596 // Enables block-mode
597 function enableBlockMode ($enabled = true) {
598         $GLOBALS['block_mode'] = $enabled;
599 }
600
601 // Checks wether block-mode is enabled
602 function isBlockModeEnabled () {
603         // Abort if not set
604         if (!isset($GLOBALS['block_mode'])) {
605                 // Needs to be fixed
606                 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
607         } // END - if
608
609         // Return it
610         return $GLOBALS['block_mode'];
611 }
612
613 // [EOF]
614 ?>