Ref link fixed, nickname fixed, several rewrites, TODOs.txt updated:
[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                 // Both are not arrays
185                 debug_report_bug(__FUNCTION__ . ': No arrays provided!');
186         } elseif (!is_array($array1)) {
187                 // Left one is not an array
188                 debug_report_bug(__FUNCTION__, sprintf("array1 is not an array. array != %s", gettype($array1)));
189         } elseif (!is_array($array2)) {
190                 // Right one is not an array
191                 debug_report_bug(__FUNCTION__, sprintf("array2 is not an array. array != %s", gettype($array2)));
192         }
193
194         // Merge all together
195         return array_merge($array1, $array2);
196 }
197
198 // Check if given FQFN is a readable file
199 function isFileReadable ($FQFN) {
200         // Check all...
201         return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
202 }
203
204 // Checks wether the given FQFN is a directory and not .,.. or .svn
205 function isDirectory ($FQFN) {
206         // Generate baseName
207         $baseName = basename($FQFN);
208
209         // Check it
210         $isDirectory = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
211
212         // Return the result
213         return $isDirectory;
214 }
215
216 // "Getter" for remote IP number
217 function detectRemoteAddr () {
218         // Get remote ip from environment
219         $remoteAddr = determineRealRemoteAddress();
220
221         // Is removeip installed?
222         if (EXT_IS_ACTIVE('removeip')) {
223                 // Then anonymize it
224                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
225         } // END - if
226
227         // Return it
228         return $remoteAddr;
229 }
230
231 // "Getter" for remote hostname
232 function detectRemoteHostname () {
233         // Get remote ip from environment
234         $remoteHost = getenv('REMOTE_HOST');
235
236         // Is removeip installed?
237         if (EXT_IS_ACTIVE('removeip')) {
238                 // Then anonymize it
239                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
240         } // END - if
241
242         // Return it
243         return $remoteHost;
244 }
245
246 // "Getter" for user agent
247 function detectUserAgent () {
248         // Get remote ip from environment
249         $userAgent = getenv('HTTP_USER_AGENT');
250
251         // Is removeip installed?
252         if (EXT_IS_ACTIVE('removeip')) {
253                 // Then anonymize it
254                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
255         } // END - if
256
257         // Return it
258         return $userAgent;
259 }
260
261 // "Getter" for referer
262 function detectReferer () {
263         // Get remote ip from environment
264         $referer = getenv('HTTP_REFERER');
265
266         // Is removeip installed?
267         if (EXT_IS_ACTIVE('removeip')) {
268                 // Then anonymize it
269                 $referer = GET_ANONYMOUS_REFERER($referer);
270         } // END - if
271
272         // Return it
273         return $referer;
274 }
275
276 // Check wether we are installing
277 function isInstalling () {
278         $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
279         //* DEBUG: */ var_dump($installing);
280         return $installing;
281 }
282
283 // Check wether this script is installed
284 function isInstalled () {
285         return (
286         (
287                 // New config file found and loaded
288                 isIncludeReadable('inc/cache/config-local.php')
289         ) || (
290                 // Fall-back to config
291                 getConfig('MXCHANGE_INSTALLED') == 'Y'
292         ) || (
293                 (
294                         // New config file found, but not yet read
295                         isIncludeReadable('inc/cache/config-local.php')
296                 ) && (
297                         (
298                                 // Only new config file is found
299                                 !isIncludeReadable('inc/config.php')
300                         ) || (
301                                 // Is installation mode
302                                 isInstalling()
303                         )
304                 )
305         )
306         );
307 }
308
309 // Check wether an admin is registered
310 function isAdminRegistered () {
311         return (getConfig('ADMIN_REGISTERED') == 'Y');
312 }
313
314 // Checks wether the reset mode is active
315 function isResetModeEnabled () {
316         // Now simply check it
317         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
318 }
319
320 // Checks wether the debug mode is enabled
321 function isDebugModeEnabled () {
322         // Simply check it
323         return (getConfig('DEBUG_MODE') == 'Y');
324 }
325
326 // Checks wether we shall debug regular expressions
327 function isDebugRegExpressionEnabled () {
328         // Simply check it
329         return (getConfig('DEBUG_REGEX') == 'Y');
330 }
331
332 // Checks wether the cache instance is valid
333 function isCacheInstanceValid () {
334         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
335 }
336
337 // Copies a file from source to destination and verifies if that goes fine.
338 // This function should wrap the copy() command and make a nicer debug backtrace
339 // even if there is no xdebug extension installed.
340 function copyFileVerified ($source, $dest, $chmod = '') {
341         // Failed is the default
342         $status = false;
343
344         // Is the source file there?
345         if (!isFileReadable($source)) {
346                 // Then abort here
347                 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
348         } // END - if
349
350         // Is the target directory there?
351         if (!isDirectory(dirname($dest))) {
352                 // Then abort here
353                 debug_report_bug('Cannot find directory ' . str_replace(constant('PATH'), '', dirname($dest)) . '.');
354         } // END - if
355
356         // Now try to copy it
357         if (!copy($source, $dest)) {
358                 // Something went wrong
359                 debug_report_bug('copy() has failed to copy the file.');
360         } // END - if
361
362         // If there are chmod rights set, apply them
363         if (!empty($chmod)) {
364                 // Try to apply them
365                 $status = changeMode($dest, $chmod);
366         } else {
367                 // All fine
368                 $status = true;
369         }
370
371         // All fine
372         return $status;
373 }
374
375 // Wrapper function for header()
376 // Send a header but checks before if we can do so
377 function sendHeader ($header) {
378         // Is the header already sent?
379         if (headers_sent()) {
380                 // Then abort here
381                 debug_report_bug('Headers already sent!');
382         } // END - if
383
384         // Send the header
385         header(trim($header));
386 }
387
388 // Wrapper function for chmod()
389 // @TODO Do some more sanity check here
390 function changeMode ($FQFN, $mode) {
391         // Is the file/directory there?
392         if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
393                 // Neither, so abort here
394                 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
395         } // END - if
396
397         // Try to set them
398         chmod($FQFN, $mode);
399 }
400
401 // Wrapper for unlink()
402 function removeFile ($FQFN) {
403         // Is the file there?
404         if (isFileReadable($FQFN)) {
405                 // Yes, so remove it
406                 return unlink($FQFN);
407         } // END - if
408
409         // All fine if no file was removed. If we change this to 'false' or rewrite
410         // above if() block it would be to restrictive.
411         return true;
412 }
413
414 // Wrapper for $_POST['sel']
415 function countPostSelection () {
416         return countSelection(REQUEST_POST('sel'));
417 }
418
419 // Checks wether the config-local.php is loaded
420 function isConfigLocalLoaded () {
421         return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
422 }
423
424 // Checks wether a nickname or userid was entered and caches the result
425 function isNicknameUsed ($userid) {
426         // Default is false
427         $isUsed = false;
428
429         // Is the cache there
430         if (isset($GLOBALS['cache_probe_nicknames'][$userid])) {
431                 // Then use it
432                 $isUsed = $GLOBALS['cache_probe_nicknames'][$userid];
433         } else {
434                 // Determine it
435                 $isUsed = ((EXT_IS_ACTIVE('nickname')) && (('' . round($userid) . '') != $userid));
436
437                 // And write it to the cache
438                 $GLOBALS['cache_probe_nicknames'][$userid] = $isUsed;
439         }
440
441         // Return the result
442         return $isUsed;
443 }
444
445 // Getter for 'what' value
446 function getWhat () {
447         // Default is null
448         $what = null;
449
450         // Is the value set?
451         if (isWhatSet(true)) {
452                 // Then use it
453                 $what = $GLOBALS['what'];
454         } // END - if
455
456         // Return it
457         return $what;
458 }
459
460 // Setter for 'what' value
461 function setWhat ($newWhat) {
462         $GLOBALS['what'] = SQL_ESCAPE($newWhat);
463 }
464
465 // Setter for 'what' from configuration
466 function setWhatFromConfig ($configEntry) {
467         // Get 'what' from config
468         $what = getConfig($configEntry);
469
470         // Set it
471         setWhat($what);
472 }
473
474 // Checks wether what is set and optionally aborts on miss
475 function isWhatSet ($abortOnMiss =  false) {
476         // Check for it
477         $isset = (isset($GLOBALS['what']));
478
479         // Should we abort here?
480         if (($abortOnMiss === true) && ($isset === false)) {
481                 // Output backtrace
482                 debug_report_bug('what is empty.');
483         } // END - if
484
485         // Return it
486         return $isset;
487 }
488
489 // Getter for 'action' value
490 function getAction () {
491         // Default is null
492         $action = null;
493
494         // Is the value set?
495         if (isActionSet(true)) {
496                 // Then use it
497                 $action = $GLOBALS['action'];
498         } // END - if
499
500         // Return it
501         return $action;
502 }
503
504 // Setter for 'action' value
505 function setAction ($newAction) {
506         $GLOBALS['action'] = SQL_ESCAPE($newAction);
507 }
508
509 // Checks wether action is set and optionally aborts on miss
510 function isActionSet ($abortOnMiss =  false) {
511         // Check for it
512         $isset = (isset($GLOBALS['action']));
513
514         // Should we abort here?
515         if (($abortOnMiss === true) && ($isset === false)) {
516                 // Output backtrace
517                 debug_report_bug('action is empty.');
518         } // END - if
519
520         // Return it
521         return $isset;
522 }
523
524 // Getter for 'module' value
525 function getModule () {
526         // Default is null
527         $module = null;
528
529         // Is the value set?
530         if (isModuleSet(true)) {
531                 // Then use it
532                 $module = $GLOBALS['module'];
533         } // END - if
534
535         // Return it
536         return $module;
537 }
538
539 // Setter for 'module' value
540 function setModule ($newModule) {
541         $GLOBALS['module'] = SQL_ESCAPE($newModule);
542 }
543
544 // Checks wether module is set and optionally aborts on miss
545 function isModuleSet ($abortOnMiss =  false) {
546         // Check for it
547         $isset = (!empty($GLOBALS['module']));
548
549         // Should we abort here?
550         if (($abortOnMiss === true) && ($isset === false)) {
551                 // Output backtrace
552                 debug_report_bug('module is empty.');
553         } // END - if
554
555         // Return it
556         return $isset;
557 }
558
559 // Getter for 'output_mode' value
560 function getOutputMode () {
561         // Default is null
562         $output_mode = null;
563
564         // Is the value set?
565         if (isOutputModeSet(true)) {
566                 // Then use it
567                 $output_mode = $GLOBALS['output_mode'];
568         } // END - if
569
570         // Return it
571         return $output_mode;
572 }
573
574 // Setter for 'output_mode' value
575 function setOutputMode ($newOutputMode) {
576         $GLOBALS['output_mode'] = SQL_ESCAPE($newOutputMode);
577 }
578
579 // Checks wether output_mode is set and optionally aborts on miss
580 function isOutputModeSet ($abortOnMiss =  false) {
581         // Check for it
582         $isset = (isset($GLOBALS['output_mode']));
583
584         // Should we abort here?
585         if (($abortOnMiss === true) && ($isset === false)) {
586                 // Output backtrace
587                 debug_report_bug('output_mode is empty.');
588         } // END - if
589
590         // Return it
591         return $isset;
592 }
593
594 // Enables block-mode
595 function enableBlockMode ($enabled = true) {
596         $GLOBALS['block_mode'] = $enabled;
597 }
598
599 // Checks wether block-mode is enabled
600 function isBlockModeEnabled () {
601         // Abort if not set
602         if (!isset($GLOBALS['block_mode'])) {
603                 // Needs to be fixed
604                 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
605         } // END - if
606
607         // Return it
608         return $GLOBALS['block_mode'];
609 }
610
611 // [EOF]
612 ?>