Renamed more:
[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 - 2013 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         // Is there 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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
67                                         // Get the title from database
68                                         $data = sqlFetchArray($result);
69                                 } // END - if
70
71                                 // Free the result
72                                 sqlFreeResult($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_TITLE--}';
85                         }  else {
86                                 // No name found
87                                 $data['title'] = '{%message,UNKNOWN_MODULE_DETECTED_TITLE=' . $module . '%}';
88                                 if ((is_resource($result)) && (ifSqlHasZeroNums($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(__FUNCTION__, __LINE__, '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 = sqlQueryEscaped("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
149                         array($module), __FUNCTION__, __LINE__);
150                 if (sqlNumRows($result) == 1) {
151                         // Read data
152                         $data = sqlFetchArray($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                 sqlFreeResult($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         // Is there 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 there is a has_menu column, this took me a half
292                                  * hour to find a loop here... *sigh*
293                                  */
294                                 sqlQueryEscaped("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                                 sqlQueryEscaped("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 (ifSqlHasZeroAffectedRows()) {
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 = sqlQueryEscaped("SELECT `has_menu` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
372                         array($module), __FUNCTION__, __LINE__);
373
374                 // Entry found?
375                 if (sqlNumRows($result) == 1) {
376                         // Load "has_menu" column
377                         $data = sqlFetchArray($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                 sqlFreeResult($result);
388         } elseif (!isExtensionInstalled('sql_patches')) {
389                 // No ext-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         } elseif (!isInstallationPhase()) {
392                 // Unsupported state, but ignored in installation phase
393                 logDebugMessage(__FUNCTION__, __LINE__, 'This should never be reached, module[' . gettype($module) . ']=' . $module . ',forceDb=' . intval($forceDb));
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         // Construct module name
424         $GLOBALS['module_inc'] = sprintf("inc/modules/%s.php", getModule());
425
426         // Check module permission (again)
427         $moduleState = checkModulePermissions();
428
429         // Which permission/error state do we have?
430         switch ($moduleState) {
431                 case 'cache_miss': // The cache is gone
432                 case 'admin_only': // Admin-only access
433                 case 'mem_only': // Member-only access
434                 case 'done': // All fine!
435                         // Does the module exists on local file system?
436                         if ((isIncludeReadable($GLOBALS['module_inc'])) && (!ifFatalErrorsDetected())) {
437                                 // Module is valid, active and located on the local disk...
438                                 $isModuleValid = TRUE;
439                         } elseif (!ifFatalErrorsDetected()) {
440                                 // Set HTTP status
441                                 setHttpStatus('404');
442
443                                 // Module not found
444                                 addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_404--}');
445
446                                 // Set module to error module (non-existent!)
447                                 setModule('error');
448                         }
449                         break;
450
451                 case '404':
452                         // Set HTTP status
453                         setHttpStatus('404');
454
455                         // Add fatal message
456                         addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_404--}');
457                         break;
458
459                 case 'locked':
460                         // Set HTTP status
461                         setHttpStatus('403 Forbidden');
462
463                         if (!isIncludeReadable($GLOBALS['module_inc'])) {
464                                 // Set HTTP status again
465                                 setHttpStatus('404 Not Found');
466
467                                 // Module does addionally not exists
468                                 addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_LOCKED_404--}');
469                         } // END - if
470
471                         // Add fatal message
472                         addFatalMessage(__FUNCTION__, __LINE__, '{--MODULE_REGISTRY_IS_LOCKED--}');
473                         break;
474
475                 default:
476                         // Unknown module status
477                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s return from module check. Module=%s", $moduleState, getModule()));
478                         addFatalMessage(__FUNCTION__, __LINE__, '{%message,UNKNOWN_MODULE_STATUS=' . $moduleState . '%}');
479                         break;
480         } // END - switch
481
482         // Return status
483         return $isModuleValid;
484 }
485
486 // Include module
487 function doIncludeModule () {
488         // Set content type
489         setContentType('text/html');
490
491         // The header file
492         loadIncludeOnce('inc/header.php');
493
494         // Modules are by default not valid!
495         $isModuleValid = FALSE;
496
497         // By default NULL is used
498         $GLOBALS['module_inc'] = NULL;
499
500         // Is the maintenance mode active or goes all well?
501         if ((isExtensionActive('maintenance')) && (isMaintenanceEnabled()) && (!isAdmin()) && (getModule() != 'admin')) {
502                 // Maintain mode is active and you are no admin
503                 addFatalMessage(__FUNCTION__, __LINE__, '{--MAILER_DOWN_FOR_MAINTENANCE--}');
504         } elseif ((isSqlLinkUp()) && (!ifFatalErrorsDetected())) {
505                 // Do the small "load module" call
506                 $isModuleValid = loadModule();
507         } elseif (!ifFatalErrorsDetected()) {
508                 // SQL problems detected
509                 addFatalMessage(__FUNCTION__, __LINE__, '{--MYSQL_ERRORS--}');
510         }
511
512         // Is the module valid?
513         if (($isModuleValid === TRUE) && (!is_null($GLOBALS['module_inc']))) {
514                 // Run pre-filter
515                 runFilterChain('pre_module_load');
516
517                 // Everything is okay so we can load the module
518                 loadIncludeOnce($GLOBALS['module_inc']);
519
520                 // Run post-filter
521                 runFilterChain('post_module_load');
522         } // END - if
523
524         // Add the footer (this will call doShutdown())
525         loadIncludeOnce('inc/footer.php');
526 }
527
528 // "Getter" for menu mode from given module
529 function getMenuModeFromModule () {
530         // Is cache set?
531         if (!isset($GLOBALS[__FUNCTION__])) {
532                 // Default is 'noindex' which is invalid for SQL tables but okay for meta data template
533                 $GLOBALS[__FUNCTION__] = 'noindex';
534
535                 // Determine it hard-coded
536                 if (getModule() == 'login') {
537                         // Is member area
538                         $GLOBALS[__FUNCTION__] = 'member';
539                 } elseif (getModule() == 'index') {
540                         // Is guest area
541                         $GLOBALS[__FUNCTION__] = 'guest';
542                 } elseif (getModule() == 'admin') {
543                         // Is admin area
544                         $GLOBALS[__FUNCTION__] = 'admin';
545                 } elseif (isInstallationPhase()) {
546                         // Is installation phase
547                         $GLOBALS[__FUNCTION__] = 'install';
548                 } else {
549                         // Get it from filter
550                         $GLOBALS[__FUNCTION__] = runFilterChain('determine_menu_mode');
551                 }
552         } // END - if
553
554         // Return it
555         return $GLOBALS[__FUNCTION__];
556 }
557
558 // [EOF]
559 ?>