15d2f304656b7d1e51e3de190c211e8f2cdb53ce
[mailer.git] / inc / module-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/01/2010 *
4  * ===================                          Last change: 07/01/2010 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : module-functions.php                             *
8  * -------------------------------------------------------------------- *
9  * Short description : Module functions                                 *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Modulfunktionen                                  *
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 // "Getter" for module title
44 function getModuleTitle ($module) {
45         // Do we have cache?
46         if (!isset($GLOBALS[__FUNCTION__][$module])) {
47                 // Init variables
48                 $data['title'] = '';
49                 $result = false;
50
51                 // Is the script installed?
52                 if ((isInstalled()) && ($module != 'error')) {
53                         // Check if cache is valid
54                         if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($module, $GLOBALS['cache_array']['modules']['module']))) {
55                                 // Load from cache
56                                 $data['title'] = $GLOBALS['cache_array']['modules']['title'][$module];
57
58                                 // Update cache hits
59                                 incrementStatsEntry('cache_hits');
60                         } elseif (!isExtensionActive('cache')) {
61                                 // Load from database
62                                 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
63                                         array($module), __FUNCTION__, __LINE__);
64
65                                 // Is the entry there?
66                                 if (SQL_NUMROWS($result) == 1) {
67                                         // Get the title from database
68                                         $data = SQL_FETCHARRAY($result);
69                                 } // END - if
70
71                                 // Free the result
72                                 SQL_FREERESULT($result);
73                         }
74                 } // END - if
75
76                 // Trim name
77                 $data['title'] = trim($data['title']);
78
79                 // Still no luck or empty title?
80                 if (empty($data['title'])) {
81                         // Is it 'error'?
82                         if ($module == 'error') {
83                                 // Error (real module was not found)
84                                 $data['title'] = '{--MODULE_ERROR_404--}';
85                         }  else {
86                                 // No name found
87                                 $data['title'] = '{%message,UNKNOWN_MODULE_DETECTED_TITLE=' . $module . '%}';
88                                 if ((is_resource($result)) && (SQL_HASZERONUMS($result))) {
89                                         // Add module to database and ignore return value
90                                         checkModulePermissions($module);
91                                 } // END - if
92                         }
93                 } // END - if
94
95                 // Store in cache
96                 $GLOBALS[__FUNCTION__][$module] = $data['title'];
97         } // END - if
98
99         // Return it
100         return $GLOBALS[__FUNCTION__][$module];
101 }
102
103 // Checks if module_status entry is there
104 function isModuleStatusSet ($module) {
105         // Check it
106         return (isset($GLOBALS['module_status'][$module]));
107 }
108
109 // Setter module status
110 function setModuleStatus ($module, $status) {
111         $GLOBALS['module_status'][$module] = $status;
112 }
113
114 // Getter for module status
115 function getModuleStatus ($module) {
116         // Is the module_status entry there?
117         if (!isModuleStatusSet($module)) {
118                 // Abort
119                 reportBug('Module status not set. module=' . $module);
120         } // END - if
121
122         // Return it
123         return $GLOBALS['module_status'][$module];
124 }
125
126 // Checks whether the given module is registered
127 function isModuleRegistered ($module) {
128         // By default nothing is found
129         $found  = false;
130
131         // Check if cache is latest version
132         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
133                 // Is the cache there?
134                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
135                 if (isset($GLOBALS['cache_array']['modules']['locked'][$module])) {
136                         // Update cache hits
137                         incrementStatsEntry('cache_hits');
138
139                         // Is found
140                         $found = true;
141                 } else {
142                         // No, then we have to update it!
143                         setModuleStatus($module, 'cache_miss');
144                 }
145         } elseif (!isExtensionActive('cache')) {
146                 // Check for module in database
147                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
148                 $result = SQL_QUERY_ESC("SELECT `locked`,`hidden`,`admin_only`,`mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
149                         array($module), __FUNCTION__, __LINE__);
150                 if (SQL_NUMROWS($result) == 1) {
151                         // Read data
152                         $data = SQL_FETCHARRAY($result);
153
154                         // Set all entries
155                         foreach ($data as $key => $value) {
156                                 $GLOBALS['cache_array']['modules'][$key][$module] = $value;
157                         } // END - foreach
158
159                         // Mark as found
160                         $found = true;
161                 } elseif (isDebugModeEnabled()) {
162                         // Debug message only in debug-mode...
163                         logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $module . ' not found.');
164                 }
165
166                 // Free result
167                 SQL_FREERESULT($result);
168         }
169
170         // Return status
171         return $found;
172 }
173
174 // Checks whether the given module is locked by just checking the cache
175 function isModuleLocked ($module) {
176         // Determine if there a cache entry and is it set
177         $return = ((isset($GLOBALS['cache_array']['modules']['locked'][$module])) && ($GLOBALS['cache_array']['modules']['locked'][$module] == 'Y'));
178
179         // Return determined value
180         return $return;
181 }
182
183 // Checks whether the given module is hidden by just checking the cache
184 function isModuleHidden ($module) {
185         // Determine if there a cache entry and is it set
186         $return = ((isset($GLOBALS['cache_array']['modules']['hidden'][$module])) && ($GLOBALS['cache_array']['modules']['hidden'][$module] == 'Y'));
187
188         // Return determined value
189         return $return;
190 }
191
192 // Checks whether the given module is mem_only by just checking the cache
193 function isModuleMemberOnly ($module) {
194         // Determine if there a cache entry and is it set
195         $return = ((isset($GLOBALS['cache_array']['modules']['mem_only'][$module])) && ($GLOBALS['cache_array']['modules']['mem_only'][$module] == 'Y'));
196
197         // Return determined value
198         return $return;
199 }
200
201 // Checks whether the given module is admin_only by just checking the cache
202 function isModuleAdminOnly ($module) {
203         // Determine if there a cache entry and is it set
204         $return = ((isset($GLOBALS['cache_array']['modules']['admin_only'][$module])) && ($GLOBALS['cache_array']['modules']['admin_only'][$module] == 'Y'));
205
206         // Return determined value
207         return $return;
208 }
209
210 // Check validity of a given module name (no file extension)
211 function checkModulePermissions ($module = '') {
212         // Is it empty (default), then take the current one
213         if (empty($module)) {
214                 // Use current module
215                 $module = getModule();
216         } // END - if
217
218         // Do we have cache?
219         if (isModuleStatusSet($module)) {
220                 // Then use it
221                 return getModuleStatus($module);
222         } // END - if
223
224         // Filter module name (names with low chars and underlines are fine!)
225         $module = preg_replace('/[^a-z_]/', '', $module);
226
227         // Check for prefix is a extension...
228         $modSplit = explode('_', $module);
229         $extension = ''; $module_chk = $module;
230         //* DEBUG: */ debugOutput(__LINE__.'*'.count($modSplit).'/'.$module.'*');
231         if (count($modSplit) == 2) {
232                 // Okay, there is a separator (_) in the name so is the first part a module?
233                 //* DEBUG: */ debugOutput(__LINE__.'*'.$modSplit[0].'*');
234                 if (isExtensionActive($modSplit[0])) {
235                         // The prefix is an extension's name, so let's set it
236                         $extension = $modSplit[0]; $module = $modSplit[1];
237                 } // END - if
238         } // END - if
239
240         // Major error in module registry is the default
241         setModuleStatus($module_chk, 'major');
242
243         // Check if script is installed if not return a 'done' to prevent some errors
244         if ((isInstallationPhase()) || (!isAdminRegistered())) {
245                 // Not installed or no admin registered or in installation phase
246                 setModuleStatus($module_chk, 'done');
247
248                 // Return status
249                 return 'done';
250         } // END - if
251
252         // Check if the module is registered
253         $found = isModuleRegistered($module_chk);
254
255         // Is the module found?
256         if ($found === true) {
257                 // Check returned values against current access permissions
258                 //
259                 // Admin access                                                              ----- Guest access -----                                                                                                                         --- Guest   or   member? ---
260                 if ((isAdmin()) || ((!isModuleLocked($module_chk)) && (!isModuleAdminOnly($module_chk)) && ((!isModuleMemberOnly($module_chk)) || (isMember())))) {
261                         // If you are admin you are welcome for everything!
262                         setModuleStatus($module_chk, 'done');
263                 } elseif (isModuleLocked($module_chk)) {
264                         // Module is locked
265                         setModuleStatus($module_chk, 'locked');
266                 } elseif ((isModuleMemberOnly($module_chk)) && (!isMember())) {
267                         // You have to login first!
268                         setModuleStatus($module_chk, 'mem_only');
269                 } elseif ((isModuleAdminOnly($module_chk)) && (!isAdmin())) {
270                         // Only the Admin is allowed to enter this module!
271                         setModuleStatus($module_chk, 'admin_only');
272                 } else {
273                         // @TODO Nothing helped???
274                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%d,hidden=%d,mem=%d,admin=%d",
275                                 getModuleStatus($module_chk),
276                                 intval(isModuleLocked($module_chk)),
277                                 intval(isModuleHidden($module_chk)),
278                                 intval(isModuleMemberOnly($module_chk)),
279                                 intval(isModuleAdminOnly($module_chk))
280                         ));
281                 }
282         } // END - if
283
284         // Still no luck or not found?
285         if (($found === false) && (!isExtensionActive('cache')) && (getModuleStatus($module_chk) != 'done'))  {
286                 //              ----- Default module -----                                  ---- Module in base folder  ----                       --- Module with extension's name ---
287                 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $module))) || (isIncludeReadable(sprintf("%s.php", $module))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $module)))) {
288                         // Data is missing so we add it
289                         if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
290                                 /*
291                                  * Since 0.3.6 we have a has_menu column, this took me a half
292                                  * hour to find a loop here... *sigh*
293                                  */
294                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
295 (`module`,`locked`,`hidden`,`mem_only`,`admin_only`,`has_menu`)
296 VALUES
297 ('%s','Y','N','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
298                         } else {
299                                 // Wrong/missing sql_patches!
300                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
301 (`module`,`locked`,`hidden`,`mem_only`,`admin_only`)
302 VALUES
303 ('%s','Y','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
304                         }
305
306                         // Everthing is fine?
307                         if (SQL_HASZEROAFFECTED()) {
308                                 // Something bad happend!
309                                 setModuleStatus($module_chk, 'major');
310                                 return 'major';
311                         } // END - if
312
313                         // Destroy cache here
314                         // @TODO Rewrite this to a filter
315                         if ((isHtmlOutputMode()) || (isRawOutputMode())) {
316                                 rebuildCache('modules', 'modules');
317                         } // END - if
318
319                         // And reload data
320                         unset($GLOBALS['module_status'][$module_chk]);
321                         return checkModulePermissions($module_chk);
322                 } else {
323                         // Module not found we don't add it to the database
324                         setModuleStatus($module_chk, '404');
325                 }
326         } elseif ((getModuleStatus($module_chk) == 'cache_miss') && (isHtmlOutputMode())) {
327                 // Rebuild the cache files
328                 rebuildCache('modules', 'modules');
329         } elseif ($found === false) {
330                 // Problem with module detected
331                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. getModuleStatus()=%s,locked=%d,hidden=%d,mem=%d,admin=%d,output_mode=%s",
332                         $module_chk,
333                         getModuleStatus($module_chk),
334                         intval(isModuleLocked($module_chk)),
335                         intval(isModuleHidden($module_chk)),
336                         intval(isModuleMemberOnly($module_chk)),
337                         intval(isModuleAdminOnly($module_chk)),
338                         getScriptOutputMode()
339                 ));
340         }
341
342         // Debug log
343         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("module=%s, status=%s", $module_chk, getModuleStatus($module_chk)));
344
345         // Return the value
346         return getModuleStatus($module_chk);
347 }
348
349 // Checks if the module has a menu
350 function ifModuleHasMenu ($module, $forceDb = false) {
351         // All is false by default
352         $ret = false;
353
354         // Extension installed and newer than or has version 0.1.2?
355         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
356                 // Cache version is okay, so let's check the cache!
357                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$module])) {
358                         // Check module cache and count hit
359                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$module] == 'Y');
360                         incrementStatsEntry('cache_hits');
361                 } elseif (isset($GLOBALS['cache_array']['extension']['ext_menu'][$module])) {
362                         // Check cache and count hit
363                         $ret = ($GLOBALS['cache_array']['extension']['ext_menu'][$module] == 'Y');
364                         incrementStatsEntry('cache_hits');
365                 } else {
366                         // Admin/guest/member/sponsor modules have always a menu!
367                         $ret = in_array($module, array('admin', 'index', 'login', 'sponsor'));
368                 }
369         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && ((!isExtensionActive('cache')) || ($forceDb === true))) {
370                 // Check database for entry
371                 $result = SQL_QUERY_ESC("SELECT `has_menu` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
372                         array($module), __FUNCTION__, __LINE__);
373
374                 // Entry found?
375                 if (SQL_NUMROWS($result) == 1) {
376                         // Load "has_menu" column
377                         $data = SQL_FETCHARRAY($result);
378
379                         // Fake cache... ;-)
380                         $GLOBALS['cache_array']['extension']['ext_menu'][$module] = $data['has_menu'];
381
382                         // Does it have a menu?
383                         $ret = ($data['has_menu'] == 'Y');
384                 } // END  - if
385
386                 // Free memory
387                 SQL_FREERESULT($result);
388         } elseif (!isExtensionInstalled('sql_patches')) {
389                 // No sql_patches installed, so maybe in admin/guest/member/sponsor area or no admin registered?
390                 $ret = in_array($module, array('admin', 'index', 'login', 'sponsor')); // Then there is a menu!
391         } else {
392                 // Unsupported state!
393                 logDebugMessage(__FUNCTION__, __LINE__, 'This should never be reached.');
394         }
395
396         // Return status
397         return $ret;
398 }
399
400 // Adds a SQL for given module
401 function addModuleSql ($module, $title, $locked, $hidden, $adminOnly, $memOnly) {
402         // Is the module already registered?
403         if (!isModuleRegistered($module)) {
404                 // Add it
405                 addExtensionSql("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg` (`module`,`title`,`locked`,`hidden`,`admin_only`,`mem_only`) VALUES ('" . $module . "','" . $title . "','" . $locked . "','" . $hidden . "','" . $adminOnly . "','" . $memOnly . "')");
406         } else {
407                 // Already registered
408                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Already registered: module=%s,locked=%s,hidden=%s,admin=%s,mem=%s",
409                         $module,
410                         $locked,
411                         $hidden,
412                         $adminOnly,
413                         $memOnly
414                 ));
415         }
416 }
417
418 // Load the currently set module
419 function loadModule () {
420         // By default all modules are invalid
421         $isModuleValid = false;
422
423         // Init module state as 'failed' (always failed first)
424         $moduleState = 'failed';
425
426         // Construct module name
427         $GLOBALS['module_inc'] =  sprintf("inc/modules/%s.php", getModule());
428
429         // Check module permission (again)
430         $moduleState = checkModulePermissions();
431
432         // Which permission/error state do we have?
433         switch ($moduleState) {
434                 case 'cache_miss': // The cache is gone
435                 case 'admin_only': // Admin-only access
436                 case 'mem_only': // Member-only access
437                 case 'done': // All fine!
438                         // Does the module exists on local file system?
439                         if ((isIncludeReadable($GLOBALS['module_inc'])) && (!ifFatalErrorsDetected())) {
440                                 // Module is valid, active and located on the local disk...
441                                 $isModuleValid = true;
442                         } elseif (!ifFatalErrorsDetected()) {
443                                 // Set HTTP status
444                                 setHttpStatus('404');
445
446                                 // Module not found
447                                 addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_404--}');
448
449                                 // Set module to error module (non-existent!)
450                                 setModule('error');
451                         }
452                         break;
453
454                 case '404':
455                         // Set HTTP status
456                         setHttpStatus('404');
457
458                         // Add fatal message
459                         addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_404--}');
460                         break;
461
462                 case 'locked':
463                         // Set HTTP status
464                         setHttpStatus('403 Forbidden');
465
466                         if (!isIncludeReadable($GLOBALS['module_inc'])) {
467                                 // Set HTTP status again
468                                 setHttpStatus('404 Not Found');
469
470                                 // Module does addionally not exists
471                                 addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_LOCKED_404--}');
472                         } // END - if
473
474                         // Add fatal message
475                         addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_IS_LOCKED--}');
476                         break;
477
478                 default:
479                         // Unknown module status
480                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s return from module check. Module=%s", $moduleState, getModule()));
481                         addFatalMessage(__FUNCTION__, __LINE__, '{%message,UNKNOWN_MODULE_STATUS=' . $moduleState . '%}');
482                         break;
483         } // END - switch
484
485         // Return status
486         return $isModuleValid;
487 }
488
489 // Include module
490 function doIncludeModule () {
491         // Set content type
492         setContentType('text/html');
493
494         // The header file
495         loadIncludeOnce('inc/header.php');
496
497         // Modules are by default not valid!
498         $isModuleValid = false;
499
500         // By default NULL is used
501         $GLOBALS['module_inc'] = NULL;
502
503         // Is the maintenance mode active or goes all well?
504         if ((isExtensionActive('maintenance')) && (isMaintenanceEnabled()) && (!isAdmin()) && (getModule() != 'admin')) {
505                 // Maintain mode is active and you are no admin
506                 addFatalMessage(__FUNCTION__, __LINE__, '{--MAILER_DOWN_FOR_MAINTENANCE--}');
507         } elseif ((SQL_IS_LINK_UP()) && (!ifFatalErrorsDetected())) {
508                 // Do the small "load module" call
509                 $isModuleValid = loadModule();
510         } elseif (!ifFatalErrorsDetected()) {
511                 // SQL problems detected
512                 addFatalMessage(__FUNCTION__, __LINE__, '{--MYSQL_ERRORS--}');
513         }
514
515         // Is the module valid?
516         if (($isModuleValid === true) && (!is_null($GLOBALS['module_inc']))) {
517                 // Run pre-filter
518                 runFilterChain('pre_module_load');
519
520                 // Everything is okay so we can load the module
521                 loadIncludeOnce($GLOBALS['module_inc']);
522
523                 // Run post-filter
524                 runFilterChain('post_module_load');
525         } // END - if
526
527         // Add the footer (this will call doShutdown())
528         loadIncludeOnce('inc/footer.php');
529 }
530
531 // [EOF]
532 ?>