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