Several code-cleanups:
[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 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.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         // Init variables
46         $data['title'] = '';
47         $result = false;
48
49         // Is the script installed?
50         if ((isInstalled()) && ($module != 'error')) {
51                 // Check if cache is valid
52                 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($module, $GLOBALS['cache_array']['modules']['module']))) {
53                         // Load from cache
54                         $data['title'] = $GLOBALS['cache_array']['modules']['title'][$module];
55
56                         // Update cache hits
57                         incrementStatsEntry('cache_hits');
58                 } elseif (!isExtensionActive('cache')) {
59                         // Load from database
60                         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
61                                 array($module), __FUNCTION__, __LINE__);
62
63                         // Is the entry there?
64                         if (SQL_NUMROWS($result) == 1) {
65                                 // Get the title from database
66                                 $data = SQL_FETCHARRAY($result);
67                         } // END - if
68
69                         // Free the result
70                         SQL_FREERESULT($result);
71                 }
72         } // END - if
73
74         // Trim name
75         $data['title'] = trim($data['title']);
76
77         // Still no luck or empty title?
78         if (empty($data['title'])) {
79                 // Is it 'error'?
80                 if ($module == 'error') {
81                         // Error (real module was not found)
82                         $data['title'] = getMessage('MODULE_ERROR_404');
83                 }  else {
84                         // No name found
85                         $data['title'] = getMaskedMessage('UNKNOWN_MODULE_DETECTED', $module);
86                         if ((is_resource($result)) && (SQL_HASZERONUMS($result))) {
87                                 // Add module to database
88                                 $dummy = checkModulePermissions($module);
89                         } // END - if
90                 }
91         } // END - if
92
93         // Return name
94         return $data['title'];
95 }
96
97 // Checks if module_status entry is there
98 function isModuleStatusSet ($module) {
99         // Check it
100         return (isset($GLOBALS['module_status'][$module]));
101 }
102
103 // Setter module status
104 function setModuleStatus ($module, $status) {
105         $GLOBALS['module_status'][$module] = $status;
106 }
107
108 // Getter for module status
109 function getModuleStatus ($module) {
110         // Is the module_status entry there?
111         if (!isModuleStatusSet($module)) {
112                 // Abort
113                 debug_report_bug('Module status not set. module=' . $module);
114         } // END - if
115
116         // Return it
117         return $GLOBALS['module_status'][$module];
118 }
119
120 // Checks wether the given module is registered
121 function isModuleRegistered ($module) {
122         // By default nothing is found
123         $found  = false;
124
125         // Check if cache is latest version
126         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
127                 // Is the cache there?
128                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
129                 if (isset($GLOBALS['cache_array']['modules']['locked'][$module])) {
130                         // Update cache hits
131                         incrementStatsEntry('cache_hits');
132
133                         // Is found
134                         $found = true;
135                 } else {
136                         // No, then we have to update it!
137                         setModuleStatus($module, 'cache_miss');
138                 }
139         } elseif (!isExtensionActive('cache')) {
140                 // Check for module in database
141                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
142                 $result = SQL_QUERY_ESC("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
143                         array($module), __FUNCTION__, __LINE__);
144                 if (SQL_NUMROWS($result) == 1) {
145                         // Read data
146                         $data = SQL_FETCHARRAY($result);
147
148                         // Set all entries
149                         foreach ($data as $key=>$value) {
150                                 $GLOBALS['cache_array']['modules'][$key][$module] = $value;
151                         } // END - foreach
152
153                         // Mark as found
154                         $found = true;
155                 } elseif (isDebugModeEnabled()) {
156                         // Debug message only in debug-mode...
157                         logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $module . ' not found.');
158                 }
159
160                 // Free result
161                 SQL_FREERESULT($result);
162         }
163
164         // Return status
165         return $found;
166 }
167
168 // Checks wether the given module is locked by just checking the cache
169 function isModuleLocked ($module) {
170         // Determine if there a cache entry and is it set
171         $return = ((isset($GLOBALS['cache_array']['modules']['locked'][$module])) && ($GLOBALS['cache_array']['modules']['locked'][$module] == 'Y'));
172
173         // Return determined value
174         return $return;
175 }
176
177 // Checks wether the given module is hidden by just checking the cache
178 function isModuleHidden ($module) {
179         // Determine if there a cache entry and is it set
180         $return = ((isset($GLOBALS['cache_array']['modules']['hidden'][$module])) && ($GLOBALS['cache_array']['modules']['hidden'][$module] == 'Y'));
181
182         // Return determined value
183         return $return;
184 }
185
186 // Checks wether the given module is mem_only by just checking the cache
187 function isModuleMemberOnly ($module) {
188         // Determine if there a cache entry and is it set
189         $return = ((isset($GLOBALS['cache_array']['modules']['mem_only'][$module])) && ($GLOBALS['cache_array']['modules']['mem_only'][$module] == 'Y'));
190
191         // Return determined value
192         return $return;
193 }
194
195 // Checks wether the given module is admin_only by just checking the cache
196 function isModuleAdminOnly ($module) {
197         // Determine if there a cache entry and is it set
198         $return = ((isset($GLOBALS['cache_array']['modules']['admin_only'][$module])) && ($GLOBALS['cache_array']['modules']['admin_only'][$module] == 'Y'));
199
200         // Return determined value
201         return $return;
202 }
203
204 // Check validity of a given module name (no file extension)
205 function checkModulePermissions ($module = '') {
206         // Is it empty (default), then take the current one
207         if (empty($module)) {
208                 // Use current module
209                 $module = getModule();
210         } // END - if
211
212         // Do we have cache?
213         if (isModuleStatusSet($module)) {
214                 // Then use it
215                 return getModuleStatus($module);
216         } // END - if
217
218         // Filter module name (names with low chars and underlines are fine!)
219         $module = preg_replace('/[^a-z_]/', '', $module);
220
221         // Check for prefix is a extension...
222         $modSplit = explode('_', $module);
223         $extension = ''; $module_chk = $module;
224         //* DEBUG: */ debugOutput(__LINE__.'*'.count($modSplit).'/'.$module.'*');
225         if (count($modSplit) == 2) {
226                 // Okay, there is a seperator (_) in the name so is the first part a module?
227                 //* DEBUG: */ debugOutput(__LINE__.'*'.$modSplit[0].'*');
228                 if (isExtensionActive($modSplit[0])) {
229                         // The prefix is an extension's name, so let's set it
230                         $extension = $modSplit[0]; $module = $modSplit[1];
231                 } // END - if
232         } // END - if
233
234         // Major error in module registry is the default
235         setModuleStatus($module_chk, 'major');
236
237         // Check if script is installed if not return a 'done' to prevent some errors
238         if ((isInstallationPhase()) || (!isAdminRegistered())) {
239                 // Not installed or no admin registered or in installation phase
240                 setModuleStatus($module_chk, 'done');
241
242                 // Return status
243                 return 'done';
244         } // END - if
245
246         // Check if the module is registered
247         $found = isModuleRegistered($module_chk);
248
249         // Is the module found?
250         if ($found === true) {
251                 // Check returned values against current access permissions
252                 //
253                 // Admin access                                                              ----- Guest access -----                                                                                                                         --- Guest   or   member? ---
254                 if ((isAdmin()) || ((!isModuleLocked($module_chk)) && (!isModuleAdminOnly($module_chk)) && ((!isModuleMemberOnly($module_chk)) || (isMember())))) {
255                         // If you are admin you are welcome for everything!
256                         setModuleStatus($module_chk, 'done');
257                 } elseif (isModuleLocked($module_chk)) {
258                         // Module is locked
259                         setModuleStatus($module_chk, 'locked');
260                 } elseif ((isModuleMemberOnly($module_chk)) && (!isMember())) {
261                         // You have to login first!
262                         setModuleStatus($module_chk, 'mem_only');
263                 } elseif ((isModuleAdminOnly($module_chk)) && (!isAdmin())) {
264                         // Only the Admin is allowed to enter this module!
265                         setModuleStatus($module_chk, 'admin_only');
266                 } else {
267                         // @TODO Nothing helped???
268                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%d,hidden=%d,mem=%d,admin=%d",
269                                 getModuleStatus($module_chk),
270                                 intval(isModuleLocked($module_chk)),
271                                 intval(isModuleHidden($module_chk)),
272                                 intval(isModuleMemberOnly($module_chk)),
273                                 intval(isModuleAdminOnly($module_chk))
274                         ));
275                 }
276         } // END - if
277
278         // Still no luck or not found?
279         if (($found === false) && (!isExtensionActive('cache')) && (getModuleStatus($module_chk) != 'done'))  {
280                 //              ----- Default module -----                                  ---- Module in base folder  ----                       --- Module with extension's name ---
281                 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $module))) || (isIncludeReadable(sprintf("%s.php", $module))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $module)))) {
282                         // Data is missing so we add it
283                         if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
284                                 /*
285                                  * Since 0.3.6 we have a has_menu column, this took me a half
286                                  * hour to find a loop here... *sigh*
287                                  */
288                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
289 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`)
290 VALUES
291 ('%s','Y','N','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
292                         } else {
293                                 // Wrong/missing sql_patches!
294                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
295 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`)
296 VALUES
297 ('%s','Y','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
298                         }
299
300                         // Everthing is fine?
301                         if (SQL_HASZEROAFFECTED()) {
302                                 // Something bad happend!
303                                 setModuleStatus($module_chk, 'major');
304                                 return 'major';
305                         } // END - if
306
307                         // Destroy cache here
308                         // @TODO Rewrite this to a filter
309                         if ((isHtmlOutputMode()) || (isRawOutputMode())) {
310                                 rebuildCache('modules', 'modules');
311                         } // END - if
312
313                         // And reload data
314                         unset($GLOBALS['module_status'][$module_chk]);
315                         return checkModulePermissions($module_chk);
316                 } else {
317                         // Module not found we don't add it to the database
318                         setModuleStatus($module_chk, '404');
319                 }
320         } elseif ((getModuleStatus($module_chk) == 'cache_miss') && (isHtmlOutputMode())) {
321                 // Rebuild the cache files
322                 rebuildCache('modules', 'modules');
323         } elseif ($found === false) {
324                 // Problem with module detected
325                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. getModuleStatus()=%s,locked=%d,hidden=%d,mem=%d,admin=%d,output_mode=%s",
326                         $module_chk,
327                         getModuleStatus($module_chk),
328                         intval(isModuleLocked($module_chk)),
329                         intval(isModuleHidden($module_chk)),
330                         intval(isModuleMemberOnly($module_chk)),
331                         intval(isModuleAdminOnly($module_chk)),
332                         getScriptOutputMode()
333                 ));
334         }
335
336         // Debug log
337         logDebugMessage(__FUNCTION__, __LINE__, sprintf("module=%s, status=%s", $module_chk, getModuleStatus($module_chk)));
338
339         // Return the value
340         return getModuleStatus($module_chk);
341 }
342
343 // Checks if the module has a menu
344 function ifModuleHasMenu ($module, $forceDb = false) {
345         // All is false by default
346         $ret = false;
347
348         // Extension installed and newer than or has version 0.1.2?
349         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
350                 // Cache version is okay, so let's check the cache!
351                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$module])) {
352                         // Check module cache and count hit
353                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$module] == 'Y');
354                         incrementStatsEntry('cache_hits');
355                 } elseif (isset($GLOBALS['cache_array']['extension']['ext_menu'][$module])) {
356                         // Check cache and count hit
357                         $ret = ($GLOBALS['cache_array']['extension']['ext_menu'][$module] == 'Y');
358                         incrementStatsEntry('cache_hits');
359                 } else {
360                         // Admin/guest/member/sponsor modules have always a menu!
361                         $ret = in_array($module, array('admin', 'index', 'login', 'sponsor'));
362                 }
363         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && ((!isExtensionActive('cache')) || ($forceDb === true))) {
364                 // Check database for entry
365                 $result = SQL_QUERY_ESC("SELECT `has_menu` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
366                         array($module), __FUNCTION__, __LINE__);
367
368                 // Entry found?
369                 if (SQL_NUMROWS($result) == 1) {
370                         // Load "has_menu" column
371                         $data = SQL_FETCHARRAY($result);
372
373                         // Fake cache... ;-)
374                         $GLOBALS['cache_array']['extension']['ext_menu'][$module] = $data['has_menu'];
375
376                         // Does it have a menu?
377                         $ret = ($data['has_menu'] == 'Y');
378                 } // END  - if
379
380                 // Free memory
381                 SQL_FREERESULT($result);
382         } elseif (!isExtensionInstalled('sql_patches')) {
383                 // No sql_patches installed, so maybe in admin/guest/member/sponsor area or no admin registered?
384                 $ret = in_array($module, array('admin', 'index', 'login', 'sponsor')); // Then there is a menu!
385         } else {
386                 // Unsupported state!
387                 logDebugMessage(__FUNCTION__, __LINE__, 'This should never be reached.');
388         }
389
390         // Return status
391         return $ret;
392 }
393
394 // Adds a SQL for given module
395 function addModuleSql ($module, $locked, $hidden, $adminOnly, $memOnly) {
396         // Is the module already registered?
397         if (!isModuleRegistered($module)) {
398                 // Add it
399                 addExtensionSql("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg` (`module`,`locked`,`hidden`,`admin_only`,`mem_only`) VALUES('" . $module . "','" . $locked . "','" . $hidden . "','" . $adminOnly . "','" . $memOnly . "')");
400         } else {
401                 // Already registered
402                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Already registered: module=%s,locked=%s,hidden=%s,admin=%s,mem=%s",
403                         $module,
404                         $locked,
405                         $hidden,
406                         $adminOnly,
407                         $memOnly
408                 ));
409         }
410 }
411
412 // [EOF]
413 ?>