62a8fbc8987d353d60b72456f90b002a9cb22c4a
[mailer.git] / inc / mysql-manager.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 08/26/2003 *
4  * ===============                              Last change: 11/29/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : mysql-manager.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : All MySQL-related functions                      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle MySQL-Relevanten Funktionen                 *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // "Getter" for module title
45 function getModuleTitle ($mod) {
46         // Init variables
47         $title = '';
48         $result = false;
49
50         // Is the script installed?
51         if (isInstalled()) {
52                 // Check if cache is valid
53                 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($mod, $GLOBALS['cache_array']['modules']['module']))) {
54                         // Load from cache
55                         $title = $GLOBALS['cache_array']['modules']['title'][$mod];
56
57                         // Update cache hits
58                         incrementStatsEntry('cache_hits');
59                 } elseif (!isExtensionActive('cache')) {
60                         // Load from database
61                         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
62                                 array($mod), __FUNCTION__, __LINE__);
63
64                         // Is the entry there?
65                         if (SQL_NUMROWS($result)) {
66                                 // Get the title from database
67                                 list($title) = SQL_FETCHROW($result);
68                         } // END - if
69
70                         // Free the result
71                         SQL_FREERESULT($result);
72                 }
73         } // END - if
74
75         // Trim name
76         $title = trim($title);
77
78         // Still no luck or empty title?
79         if (empty($title)) {
80                 // No name found
81                 $title = sprintf("%s (%s)", getMessage('LANG_UNKNOWN_MODULE'), $mod);
82                 if (SQL_NUMROWS($result) == 0) {
83                         // Add module to database
84                         $dummy = checkModulePermissions($mod);
85                 } // END - if
86         } // END - if
87
88         // Return name
89         return $title;
90 }
91
92 // "Getter" for module description
93 // @TODO Can we cache this?
94 function getModuleDescription ($mode, $what, $column = 'what') {
95         // Fix empty 'what'
96         if (empty($what)) {
97                 $what = getConfig('index_home');
98         } // END - if
99
100         // Default is not found
101         $ret = '??? (' . $what . ')';
102
103         // Look for title
104         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE %s='%s' LIMIT 1",
105                 array($mode, $column, $what), __FUNCTION__, __LINE__);
106
107         // Is there an entry?
108         if (SQL_NUMROWS($result) == 1) {
109                 // Fetch the title
110                 list($ret) = SQL_FETCHROW($result);
111         } // END - if
112
113         // Free result
114         SQL_FREERESULT($result);
115
116         // Return it
117         return $ret;
118 }
119
120 // Check validity of a given module name (no file extension)
121 function checkModulePermissions ($mod = '') {
122         // Is it empty (default), then take the current one
123         if (empty($mod)) $mod = getModule();
124
125         // Do we have cache?
126         if (isset($GLOBALS['module_status'][$mod])) {
127                 // Then use it
128                 return $GLOBALS['module_status'][$mod];
129         } // END - if
130
131         // Filter module name (names with low chars and underlines are fine!)
132         $mod = preg_replace('/[^a-z_]/', '', $mod);
133
134         // Check for prefix is a extension...
135         $modSplit = explode('_', $mod);
136         $extension = ''; $mod_chk = $mod;
137         //* DEBUG: */ print(__LINE__."*".count($modSplit)."*/".$mod."*<br />");
138         if (count($modSplit) == 2) {
139                 // Okay, there is a seperator (_) in the name so is the first part a module?
140                 //* DEBUG: */ print(__LINE__."*".$modSplit[0]."*<br />");
141                 if (isExtensionActive($modSplit[0])) {
142                         // The prefix is an extension's name, so let's set it
143                         $extension = $modSplit[0]; $mod = $modSplit[1];
144                 } // END - if
145         } // END - if
146
147         // Major error in module registry is the default
148         $ret = 'major';
149
150         // Check if script is installed if not return a 'done' to prevent some errors
151         if ((isInstallationPhase()) || (!isAdminRegistered())) {
152                 // Not installed or no admin registered or in installation phase
153                 return 'done';
154         } // END - if
155
156         // Init variables
157         $locked = 'Y';
158         $hidden = 'N';
159         $admin  = 'N';
160         $mem    = 'N';
161         $found  = false;
162
163         // Check if cache is latest version
164         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
165                 // Is the cache there?
166                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
167                 if (isset($GLOBALS['cache_array']['modules']['locked'][$mod_chk])) {
168                         // Check cache
169                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache found.');
170                         $locked = $GLOBALS['cache_array']['modules']['locked'][$mod_chk];
171                         $hidden = $GLOBALS['cache_array']['modules']['hidden'][$mod_chk];
172                         $admin  = $GLOBALS['cache_array']['modules']['admin_only'][$mod_chk];
173                         $mem    = $GLOBALS['cache_array']['modules']['mem_only'][$mod_chk];
174
175                         // Update cache hits
176                         incrementStatsEntry('cache_hits');
177                         $found = true;
178                 } else {
179                         // No, then we have to update it!
180                         $ret = 'cache_miss';
181                 }
182         } elseif (!isExtensionActive('cache')) {
183                 // Check for module in database
184                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
185                 $result = SQL_QUERY_ESC("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
186                         array($mod_chk), __FUNCTION__, __LINE__);
187                 if (SQL_NUMROWS($result) == 1) {
188                         // Read data
189                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Entry found.');
190                         list($locked, $hidden, $admin, $mem) = SQL_FETCHROW($result);
191                         $found = true;
192                 } elseif (isDebugModeEnabled()) {
193                         // Debug message only in debug-mode...
194                         logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $mod_chk . ' not found!');
195                 }
196
197                 // Free result
198                 SQL_FREERESULT($result);
199         }
200         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
201
202         // Is the module found?
203         if ($found === true) {
204                 // Check returned values against current access permissions
205                 //
206                 //  Admin access            ----- Guest access -----           --- Guest   or   member? ---
207                 if ((isAdmin()) || (($locked != 'Y') && ($admin != 'Y') && (($mem != 'Y') || (isMember())))) {
208                         // If you are admin you are welcome for everything!
209                         $ret = 'done';
210                 } elseif ($locked == 'Y') {
211                         // Module is locked
212                         $ret = 'locked';
213                 } elseif (($mem == 'Y') && (!isMember())) {
214                         // You have to login first!
215                         $ret = 'mem_only';
216                 } elseif (($admin == 'Y') && (!isAdmin())) {
217                         // Only the Admin is allowed to enter this module!
218                         $ret = 'admin_only';
219                 } else {
220                         // @TODO Nothing helped???
221                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
222                                 $ret,
223                                 $locked,
224                                 $admin,
225                                 $mem
226                         ));
227                 }
228         } // END - if
229
230         // Still no luck or not found?
231         if (($found === false) && (!isExtensionActive('cache')) && ($ret != 'done'))  {
232                 //              ----- Legacy module -----                                               ---- Module in base folder  ----                       --- Module with extension's name ---
233                 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $mod))) || (isIncludeReadable(sprintf("%s.php", $mod))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $mod)))) {
234                         // Data is missing so we add it
235                         if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
236                                 // Since 0.3.6 we have a has_menu column, this took me a half hour
237                                 // to find a loop here... *sigh*
238                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
239 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`) VALUES
240 ('%s','Y','N','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
241                         } else {
242                                 // Wrong/missing sql_patches!
243                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
244 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`) VALUES
245 ('%s','Y','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
246                         }
247
248                         // Everthing is fine?
249                         if (SQL_AFFECTEDROWS() < 1) {
250                                 // Something bad happend!
251                                 return 'major';
252                         } // END - if
253
254                         // Destroy cache here
255                         // @TODO Rewrite this to a filter
256                         if (getOutputMode() == 0) rebuildCacheFile('modules', 'modules');
257
258                         // And reload data
259                         unset($GLOBALS['module_status'][$mod]);
260                         $ret = checkModulePermissions($mod_chk);
261                 } else {
262                         // Module not found we don't add it to the database
263                         $ret = '404';
264                 }
265         } elseif (($ret == 'cache_miss') && (getOutputMode() == 0)) {
266                 // Rebuild the cache files
267                 rebuildCacheFile('modules', 'modules');
268         } elseif ($found === false) {
269                 // Problem with module detected
270                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s, output_mode=%s",
271                         $mod,
272                         $ret,
273                         $locked,
274                         $hidden,
275                         $mem,
276                         $admin,
277                         getOutputMode()
278                 ));
279         }
280
281         // Return the value
282         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
283         $GLOBALS['module_status'][$mod] = $ret;
284         return $ret;
285 }
286
287 // Add menu description pending on given file name (without path!)
288 function addMenuDescription ($accessLevel, $FQFN, $return = false, $output = true) {
289         // Use only filename of the FQFN...
290         $file = basename($FQFN);
291
292         // Init variables
293         $LINK_ADD = '';
294         $OUT = '';
295         $AND = '';
296
297         // First we have to do some analysis...
298         if (substr($file, 0, 7) == 'action-') {
299                 // This is an action file!
300                 $type = 'action';
301                 $search = substr($file, 7);
302                 switch ($accessLevel) {
303                         case 'admin':
304                                 $modCheck = 'admin';
305                                 break;
306
307                         case 'sponsor':
308                         case 'guest':
309                         case 'member':
310                                 $modCheck = getModule();
311                                 break;
312                 }
313                 $AND = " AND (`what`='' OR `what` IS NULL)";
314         } elseif (substr($file, 0, 5) == 'what-') {
315                 // This is an admin what file!
316                 $type = 'what';
317                 $search = substr($file, 5);
318                 $AND = '';
319                 switch ($accessLevel) {
320                         case 'admin':
321                                 $modCheck = 'admin';
322                                 break;
323
324                         case 'guest':
325                         case 'member':
326                                 $modCheck = getModule();
327                                 if (!isAdmin()) {
328                                         $AND = " AND `visible`='Y' AND `locked`='N'";
329                                 }
330                                 break;
331                 }
332
333                 $dummy = substr($search, 0, -4);
334                 $AND .= " AND `action`='".getModeAction($accessLevel, $dummy)."'";
335         } elseif (($accessLevel == 'sponsor') || ($accessLevel == "engine")) {
336                 // Sponsor / engine menu
337                 $type     = 'what';
338                 $search   = $file;
339                 $modCheck = getModule();
340                 $AND      = '';
341         } else {
342                 // Other
343                 $type     = 'menu';
344                 $search   = $file;
345                 $modCheck = getModule();
346                 $AND      = '';
347         }
348
349         // Begin the navigation line
350         if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) {
351                 $GLOBALS['nav_depth'] = 0;
352                 $prefix = "<div class=\"you_are_here\">{--YOU_ARE_HERE--}&nbsp;<strong><a class=\"you_are_here\" href=\"{?URL?}/modules.php?module=".getModule().$LINK_ADD."\">Home</a></strong>";
353         } else {
354                 if ($return === false) $GLOBALS['nav_depth']++;
355                 $prefix = '';
356         }
357
358         $prefix .= '&nbsp;-&gt;&nbsp;';
359
360         // We need to remove .php and the end
361         if (substr($search, -4, 4) == '.php') {
362                 // Remove the .php
363                 $search = substr($search, 0, -4);
364         } // END - i
365
366         // Get the title from menu
367         $result = SQL_QUERY_ESC("SELECT title FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE %s='%s' ".$AND." LIMIT 1",
368         array($accessLevel, $type, $search), __FUNCTION__, __LINE__);
369
370         // Menu found?
371         if (SQL_NUMROWS($result) == 1) {
372                 // Load title
373                 list($ret) = SQL_FETCHROW($result);
374
375                 // Shall we return it?
376                 if ($return === true) {
377                         // Return title
378                         return $ret;
379                 } elseif (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
380                         // Output HTML code
381                         $OUT = $prefix . "<strong><a class=\"you_are_here\" href=\"{?URL?}/modules.php?module=" . $modCheck . '&amp;' . $type . '=' . $search.$LINK_ADD . "\">" . $ret . "</a></strong>\n";
382
383                         // Can we close the you-are-here navigation?
384                         //* DEBUG: */ print(__LINE__."*".$type.'/'.getWhat()."*<br />");
385                         if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
386                                 //* DEBUG: */ print(__LINE__.'+'.$type."+<br />");
387                                 // Add closing div and br-tag
388                                 $OUT .= "</div><br />\n";
389                                 $GLOBALS['nav_depth'] = 0;
390
391                                 // Run the filter chain
392                                 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ""));
393                                 $OUT .= $ret['content'];
394                         } // END - if
395                 }
396         } // END - if
397
398         // Free result
399         SQL_FREERESULT($result);
400
401         // Return or output HTML code?
402         if ($output) {
403                 // Output HTML code here
404                 outputHtml($OUT);
405         } else {
406                 // Return HTML code
407                 return $OUT;
408         }
409 }
410
411 // Adds a menu (mode = guest/member/admin/sponsor) to output
412 function addMenu ($mode, $action, $what) {
413         // Init some variables
414         $main_cnt = 0;
415         $AND = '';
416
417         // is the menu action valid?
418         if (!isMenuActionValid($mode, $action, $what, true)) {
419                 return getCode('MENU_NOT_VALID');
420         } // END - if
421
422         // Non-admin shall not see all menus
423         if (!isAdmin()) {
424                 $AND = " AND `visible`='Y' AND `locked`='N'";
425         } // END - if
426
427         // Load SQL data and add the menu to the output stream...
428         $result_main = SQL_QUERY_ESC("SELECT `title`, `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$AND." ORDER BY `sort` ASC",
429                 array($mode), __FUNCTION__, __LINE__);
430
431         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
432         if (SQL_NUMROWS($result_main) > 0) {
433                 // There are menus available, so we simply display them... :)
434                 $GLOBALS['rows'] = '';
435                 while ($content = SQL_FETCHARRAY($result_main)) {
436                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].':'.getWhat()."*<br />");
437                         // Init variables
438                         enableBlockMode(false);
439                         $action = $content['action'];
440
441                         // Load menu header template
442                         $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
443
444                         // Sub menu
445                         $result_sub = SQL_QUERY_ESC("SELECT `title` AS sub_title, `what` AS sub_what FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$AND." ORDER BY `sort`",
446                                 array($mode, $content['action']), __FUNCTION__, __LINE__);
447
448                         // Get number of rows
449                         $totalWhats = SQL_NUMROWS($result_sub);
450
451                         // Do we have some entries?
452                         if ($totalWhats > 0) {
453                                 // Init counter
454                                 $cnt = 0;
455
456                                 // Load all sub menus
457                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
458                                         // Merge both arrays in one
459                                         $content = merge_array($content, $content2);
460
461                                         // Init content
462                                         $OUT = '';
463
464                                         // Full file name for checking menu
465                                         //* DEBUG: */ print(__LINE__.":!!!!".$content['sub_what']."!!!<br />");
466                                         $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
467                                         if (isIncludeReadable($inc)) {
468                                                 // Mark currently selected menu - open
469                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
470                                                         $OUT = "<strong>";
471                                                 } // END - if
472
473                                                 // Navigation link
474                                                 $OUT .= "<a name=\"menu\" class=\"menu_blur\" href=\"{?URL?}/modules.php?module=".getModule()."&amp;what=".$content['sub_what']."\" target=\"_self\">";
475                                         } else {
476                                                 // Not found! - open
477                                                 $OUT .= "<em style=\"cursor:help\" class=\"admin_note\" title=\"{--MENU_WHAT_404--}\">";
478                                         }
479
480                                         // Menu title
481                                         $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
482
483                                         if (isIncludeReadable($inc)) {
484                                                 $OUT .= "</a>";
485
486                                                 // Mark currently selected menu - close
487                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
488                                                         $OUT .= "</strong>";
489                                                 } // END - if
490                                         } else {
491                                                 // Not found! - close
492                                                 $OUT .= "</em>";
493                                         }
494
495                                         // Cunt it up
496                                         $cnt++;
497
498                                         // Rewrite array
499                                         $content =  array(
500                                                 'menu' => $OUT,
501                                                 'what' => $content['sub_what']
502                                         );
503
504                                         // Add regular menu row or bottom row?
505                                         if ($cnt < $totalWhats) {
506                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
507                                         } else {
508                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
509                                         }
510                                 }
511                         } else {
512                                 // This is a menu block... ;-)
513                                 enableBlockMode();
514
515                                 // Load menu block
516                                 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
517                                 if (isFileReadable($INC)) {
518                                         // Load include file
519                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
520                                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
521                                         loadInclude($INC);
522                                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
523                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
524                                 }
525                                 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
526                         }
527
528                         $main_cnt++;
529
530                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
531                         if (SQL_NUMROWS($result_main) > $main_cnt) {
532                                 // Add seperator
533                                 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
534
535                                 // Should we display adverts in this menu?
536                                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
537                                         // Display advert template
538                                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
539
540                                         // Add seperator again
541                                         $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
542                                 } // END - if
543                         } // END - if
544                 } // END - while
545
546                 // Free memory
547                 SQL_FREERESULT($result_main);
548
549                 // Should we display adverts in this menu?
550                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
551                         // Add seperator again
552                         $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
553
554                         // Display advert template
555                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
556                 } // END - if
557
558                 // Prepare data
559                 $content = array(
560                         'rows' => $GLOBALS['rows'],
561                         'mode' => $mode
562                 );
563
564                 // Load main template
565                 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
566                 loadTemplate('menu_table', false, $content);
567         } // END - if
568 }
569
570 // Checks wether the current user is a member
571 function isMember () {
572         // By default no member
573         $ret = false;
574
575         // Fix missing 'last_online' array, damn stupid code :(((
576         // @TODO Try to rewrite this to one or more functions
577         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
578
579         // is the cache entry there?
580         if (isset($GLOBALS['is_member'])) {
581                 // Then return it
582                 return $GLOBALS['is_member'];
583         } // END - if
584
585         // Init global 'status'
586         $GLOBALS['status'] = false;
587
588         // Fix "deleted" cookies first
589         fixDeletedCookies(array('userid', 'u_hash'));
590
591         // Are cookies set?
592         if ((isUserIdSet()) && (isSessionVariableSet('u_hash'))) {
593                 // Cookies are set with values, but are they valid?
594                 $result = SQL_QUERY_ESC("SELECT `password`, `status`, `last_module`, `last_online` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
595                         array(getUserId()), __FUNCTION__, __LINE__);
596                 if (SQL_NUMROWS($result) == 1) {
597                         // Load data from cookies
598                         list($password, $GLOBALS['status'], $mod, $onl) = SQL_FETCHROW($result);
599
600                         // Validate password by created the difference of it and the secret key
601                         $valPass = generatePassString($password);
602
603                         // Transfer last module and online time
604                         if ((!empty($mod)) && (empty($GLOBALS['last_online']['module']))) {
605                                 // @TODO Try to rewrite this to one or more functions
606                                 $GLOBALS['last_online']['module'] = $mod;
607                                 $GLOBALS['last_online']['online'] = $onl;
608                         } // END - if
609
610                         // So did we now have valid data and an unlocked user?
611                         if (($GLOBALS['status'] == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
612                                 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
613                                 $ret = true;
614                         } else {
615                                 // Maybe got locked etc.
616                                 //* DEBUG: */ print(__LINE__."!!!<br />");
617                                 destroyUserSession();
618                         }
619                 } else {
620                         // Cookie data is invalid!
621                         //* DEBUG: */ print(__LINE__."***<br />");
622                         destroyUserSession();
623                 }
624
625                 // Free memory
626                 SQL_FREERESULT($result);
627         } else {
628                 // Cookie data is invalid!
629                 //* DEBUG: */ print(__LINE__."///<br />");
630                 destroyUserSession();
631         }
632
633         // Cache status
634         $GLOBALS['is_member'] = $ret;
635
636         // Return status
637         return $ret;
638 }
639
640 // This patched function will reduce many SELECT queries for the specified or current admin login
641 function isAdmin ($admin = '') {
642         // Init variables
643         $ret = false; $passCookie = ''; $valPass = '';
644         //* DEBUG: */ print(__FUNCTION__.':'.$admin.'<br />');
645
646         // If admin login is not given take current from cookies...
647         if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
648                 // Get admin login and password from session/cookies
649                 $admin = getSession('admin_login');
650                 $passCookie = getSession('admin_md5');
651         } // END - if
652         //* DEBUG: */ print(__FUNCTION__.':'.$admin.'/'.$passCookie.'<br />');
653
654         // Do we have cache?
655         if (!isset($GLOBALS['is_admin'][$admin])) {
656                 // Search in array for entry
657                 if (isset($GLOBALS['admin_hash'])) {
658                         // Use cached string
659                         $valPass = $GLOBALS['admin_hash'];
660                 } elseif ((!empty($passCookie)) && (isAdminHashSet($admin) === true) && (!empty($admin))) {
661                         // Login data is valid or not?
662                         $valPass = generatePassString(getAdminHash($admin));
663
664                         // Cache it away
665                         $GLOBALS['admin_hash'] = $valPass;
666
667                         // Count cache hits
668                         incrementStatsEntry('cache_hits');
669                 } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (isAdminHashSet($admin) === false)) {
670                         // Search for admin
671                         $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
672                                 array($admin), __FUNCTION__, __LINE__);
673
674                         // Is he admin?
675                         $passDB = '';
676                         if (SQL_NUMROWS($result) == 1) {
677                                 // Admin login was found so let's load password from DB
678                                 list($passDB) = SQL_FETCHROW($result);
679
680                                 // Temporary cache it
681                                 setAdminHash($admin, $passDB);
682
683                                 // Generate password hash
684                                 $valPass = generatePassString($passDB);
685                         } // END - if
686
687                         // Free memory
688                         SQL_FREERESULT($result);
689                 }
690
691                 if (!empty($valPass)) {
692                         // Check if password is valid
693                         //* DEBUG: */ print(__FUNCTION__ . ':(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie).'<br />');
694                         $GLOBALS['is_admin'][$admin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
695                 } // END - if
696         } // END - if
697
698         // Return result of comparision
699         return $GLOBALS['is_admin'][$admin];
700 }
701
702 // Generates a list of "max receiveable emails per day"
703 function addMaxReceiveList ($mode, $default = '', $return = false) {
704         $OUT = '';
705         $result = false;
706
707         switch ($mode) {
708                 case 'guest':
709                         // Guests (in the registration form) are not allowed to select 0 mails per day.
710                         $result = SQL_QUERY("SELECT value, comment FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE value > 0 ORDER BY value",
711                         __FUNCTION__, __LINE__);
712                         break;
713
714                 case 'member':
715                         // Members are allowed to set to zero mails per day (we will change this soon!)
716                         $result = SQL_QUERY("SELECT value, comment FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY value",
717                         __FUNCTION__, __LINE__);
718                         break;
719
720                 default: // Invalid!
721                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
722                         break;
723         }
724
725         // Some entries are found?
726         if (SQL_NUMROWS($result) > 0) {
727                 $OUT = '';
728                 while ($content = SQL_FETCHARRAY($result)) {
729                         $OUT .= "      <option value=\"".$content['value']."\"";
730                         if (postRequestElement('max_mails') == $content['value']) $OUT .= ' selected="selected"';
731                         $OUT .= ">".$content['value']." {--PER_DAY--}";
732                         if (!empty($content['comment'])) $OUT .= " (".$content['comment'].')';
733                         $OUT .= "</option>\n";
734                 }
735
736                 // Load template
737                 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
738         } else {
739                 // Maybe the admin has to setup some maximum values?
740                 debug_report_bug('Nothing is being done here?');
741         }
742
743         // Free result
744         SQL_FREERESULT($result);
745
746         if ($return === true) {
747                 // Return generated HTML code
748                 return $OUT;
749         } else {
750                 // Output directly (default)
751                 outputHtml($OUT);
752         }
753 }
754
755 // Checks wether the given email address is used.
756 function isEmailTaken ($email) {
757         // Query the database
758         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE email LIKE '{PER}%s{PER}' LIMIT 1",
759                 array($email), __FUNCTION__, __LINE__);
760
761         // Is the email there?
762         $ret = (SQL_NUMROWS($result) == 1);
763
764         // Free the result
765         SQL_FREERESULT($result);
766
767         // Return result
768         return $ret;
769 }
770
771 // Validate the given menu action
772 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
773         // Is the cache entry there and we shall not update?
774         if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
775                 // Count cache hit
776                 incrementStatsEntry('cache_hits');
777
778                 // Then use this cache
779                 return $GLOBALS['action_valid'][$mode][$action][$what];
780         } // END - if
781
782         // By default nothing is valid
783         $ret = false;
784
785         // Look in all menus or only unlocked
786         $add = '';
787         if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
788
789         //* DEBUG: */ print(__LINE__.':'.$mode.'/'.$action.'/'.$what."*<br />");
790         if (($mode != 'admin') && ($updateEntry === true)) {
791                 // Update guest or member menu
792                 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
793                         array($mode, $action, $what), __FUNCTION__, __LINE__, false);
794         } elseif (($what != 'overview') && (!empty($what))) {
795                 // Other actions
796                 $sql = SQL_QUERY_ESC("SELECT `id`, `what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what`='%s'".$add." ORDER BY `action` DESC LIMIT 1",
797                         array($mode, $action, $what), __FUNCTION__, __LINE__, false);
798         } else {
799                 // Admin login overview
800                 $sql = SQL_QUERY_ESC("SELECT `id`, `what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND (`what`='' OR `what` IS NULL)".$add." ORDER BY `action` DESC LIMIT 1",
801                         array($mode, $action), __FUNCTION__, __LINE__, false);
802         }
803
804         // Run SQL command
805         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
806         if ($updateEntry === true) {
807                 // Check updated/affected rows
808                 $ret = (SQL_AFFECTEDROWS() == 1);
809         } else {
810                 // Check found rows
811                 $ret = (SQL_NUMROWS($result) == 1);
812         }
813
814         // Free memory
815         SQL_FREERESULT($result);
816
817         // Set cache entry
818         $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
819
820         // Return result
821         return $ret;
822 }
823
824 //
825 function sendModeMails ($mod, $modes) {
826         // Load hash
827         $result_main = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
828                 array(getUserId()), __FUNCTION__, __LINE__);
829         if (SQL_NUMROWS($result_main) == 1) {
830                 // Load hash from database
831                 list($hashDB) = SQL_FETCHROW($result_main);
832
833                 // Extract salt from cookie
834                 $salt = substr(getSession('u_hash'), 0, -40);
835
836                 // Now let's compare passwords
837                 $hash = generatePassString($hashDB);
838                 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
839                         // Load user's data               0        1        2         3        4      5    6      7
840                         $result = SQL_QUERY_ESC("SELECT gender, surname, family, street_nr, country, zip, city, email FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND password='%s' LIMIT 1",
841                                 array(getUserId(), $hashDB), __FUNCTION__, __LINE__);
842                         if (SQL_NUMROWS($result) == 1) {
843                                 // Load the data
844                                 $content = SQL_FETCHARRAY($result, 0, false);
845
846                                 // Free result
847                                 SQL_FREERESULT($result);
848
849                                 // Translate gender
850                                 $content['gender'] = translateGender($content['gender']);
851
852                                 // Clear/init the content variable
853                                 $content['info'] = '';
854
855                                 switch ($mod) {
856                                         case 'mydata':
857                                                 foreach ($modes as $mode) {
858                                                         switch ($mode) {
859                                                                 case 'normal': break; // Do not add any special lines
860                                                                 case 'email': // Email was changed!
861                                                                         $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
862                                                                         break;
863
864                                                                 case 'pass': // Password was changed
865                                                                         $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
866                                                                         break;
867
868                                                                 default:
869                                                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
870                                                                         $content['message'] = getMessage('MEMBER_UNKNOWN_MODE').": ".$mode."\n\n";
871                                                                         break;
872                                                         } // END - switch
873                                                 } // END - if
874
875                                                 if (isExtensionActive('country')) {
876                                                         // Replace code with description
877                                                         $content['country'] = generateCountryInfo(postRequestElement('country_code'));
878                                                 } // END - if
879
880                                                 // Merge content with data from POST
881                                                 $content = merge_array($content, postRequestArray());
882
883                                                 // Load template
884                                                 $message = loadEmailTemplate('member_mydata_notify', $content, getUserId());
885
886                                                 if (getConfig('admin_notify') == 'Y') {
887                                                         // The admin needs to be notified about a profile change
888                                                         $message_admin = 'admin_mydata_notify';
889                                                         $sub_adm   = getMessage('ADMIN_CHANGED_DATA');
890                                                 } else {
891                                                         // No mail to admin
892                                                         $message_admin = '';
893                                                         $sub_adm   = '';
894                                                 }
895
896                                                 // Set subject lines
897                                                 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
898
899                                                 // Output success message
900                                                 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
901                                                 break;
902
903                                         default: // Unsupported module!
904                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
905                                                 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
906                                                 break;
907                                 } // END - switch
908                         } else {
909                                 // Could not load profile data
910                                 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
911                         }
912                 } else {
913                         // Passwords mismatch
914                         $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
915                 }
916         } else {
917                 // Could not load profile
918                 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
919         }
920
921         // Send email to user if required
922         if ((!empty($sub_mem)) && (!empty($message))) {
923                 // Send member mail
924                 sendEmail($content['email'], $sub_mem, $message);
925         } // END - if
926
927         // Send only if no other error has occured
928         if (empty($content)) {
929                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
930                         // Send admin mail
931                         sendAdminNotification($sub_adm, $message_admin, $content, getUserId());
932                 } elseif (getConfig('admin_notify') == 'Y') {
933                         // Cannot send mails to admin!
934                         $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
935                 } else {
936                         // No mail to admin
937                         $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
938                 }
939         } // END - if
940
941         // Load template
942         loadTemplate('admin_settings_saved', false, $content);
943 }
944
945 // Get action value from mode (admin/guest/member) and what-value
946 function getModeAction ($mode, $what) {
947         // Init status
948         $ret = '';
949
950         //* DEBUG: */ print(__LINE__.'='.$mode.'/'.$what.'/'.getAction()."=<br />");
951         if ((empty($what)) && ($mode != 'admin')) {
952                 $what = getConfig('index_home');
953         } // END - if
954
955         if ($mode == 'admin') {
956                 // Action value for admin area
957                 if (isGetRequestElementSet('action')) {
958                         // Use from request!
959                         return getRequestElement('action');
960                 } elseif (isActionSet()) {
961                         // Get it directly from URL
962                         return getAction();
963                 } elseif (($what == 'overview') || (!isWhatSet())) {
964                         // Default value for admin area
965                         $ret = 'login';
966                 }
967         } elseif (isActionSet()) {
968                 // Get it directly from URL
969                 return getAction();
970         }
971         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret.'<br />');
972
973         // Does the module have a menu?
974         if (ifModuleHasMenu($mode)) {
975                 // Rewriting modules to menu
976                 $mode = mapModuleToTable($mode);
977
978                 // Guest and member menu is 'main' as the default
979                 if (empty($ret)) $ret = 'main';
980
981                 // Load from database
982                 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
983                         array($mode, $what), __FUNCTION__, __LINE__);
984                 if (SQL_NUMROWS($result) == 1) {
985                         // Load action value and pray that this one is the right you want... ;-)
986                         list($ret) = SQL_FETCHROW($result);
987                 } // END - if
988
989                 // Free memory
990                 SQL_FREERESULT($result);
991         } elseif ((!isExtensionInstalled('sql_patches')) && ($mode != 'admin')) {
992                 // No sql_patches installed, but maybe we need to register an admin?
993                 if (isAdminRegistered()) {
994                         // Redirect to admin area
995                         redirectToUrl('admin.php');
996                 } // END - if
997         }
998
999         // Return action value
1000         return $ret;
1001 }
1002
1003 // Get category name back
1004 function getCategory ($cid) {
1005         // Default is not found
1006         $ret = getMessage('_CATEGORY_404');
1007
1008         // Is the category id set?
1009         if ($cid == 0) {
1010                 // No category
1011                 $ret = getMessage('_CATEGORY_NONE');
1012         } elseif ($cid > 0) {
1013                 // Lookup the category in database
1014                 $result = SQL_QUERY_ESC("SELECT cat FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
1015                 array(bigintval($cid)), __FUNCTION__, __LINE__);
1016                 if (SQL_NUMROWS($result) == 1) {
1017                         // Category found... :-)
1018                         list($ret) = SQL_FETCHROW($result);
1019                 } // END - if
1020
1021                 // Free result
1022                 SQL_FREERESULT($result);
1023         } // END - if
1024
1025         // Return result
1026         return $ret;
1027 }
1028
1029 // Get a string of "mail title" and price back
1030 function getPaymentTitlePrice ($pid, $full=false) {
1031         // Default is not found
1032         $ret = getMessage('_PAYMENT_404');
1033
1034         // Load payment data
1035         $result = SQL_QUERY_ESC("SELECT mail_title, price FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1036         array(bigintval($pid)), __FUNCTION__, __LINE__);
1037         if (SQL_NUMROWS($result) == 1) {
1038                 // Payment type found... :-)
1039                 if ($full === false) {
1040                         // Return only title
1041                         list($ret) = SQL_FETCHROW($result);
1042                 } else {
1043                         // Return title and price
1044                         list($t, $p) = SQL_FETCHROW($result);
1045                         $ret = $t.' / '.translateComma($p).' {?POINTS?}';
1046                 }
1047         }
1048
1049         // Free result
1050         SQL_FREERESULT($result);
1051
1052         // Return result
1053         return $ret;
1054 }
1055
1056 // Get (basicly) the price of given payment id
1057 function getPaymentPoints ($pid, $lookFor = 'price') {
1058         // Default value...
1059         $ret = '-1';
1060
1061         // Search for it in database
1062         $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1063         array($lookFor, $pid), __FUNCTION__, __LINE__);
1064
1065         // Is the entry there?
1066         if (SQL_NUMROWS($result) == 1) {
1067                 // Payment type found... :-)
1068                 list($ret) = SQL_FETCHROW($result);
1069         } // END - if
1070
1071         // Free result
1072         SQL_FREERESULT($result);
1073
1074         // Return value
1075         return $ret;
1076 }
1077
1078 // Remove a receiver's ID from $receivers and add a link for him to confirm
1079 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
1080         // Default is not removed
1081         $ret = 'failed';
1082
1083         // Is the userid valid?
1084         if ($userid > 0) {
1085                 // Remove entry from array
1086                 unset($receivers[$key]);
1087
1088                 // Is there already a line for this user available?
1089                 if ($stats_id > 0) {
1090                         // Only when we got a real stats ID continue searching for the entry
1091                         $type = 'NORMAL'; $rowName = 'stats_id';
1092                         if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1093
1094                         // Try to look the entry up
1095                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1096                                 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1097
1098                         // Was it *not* found?
1099                         if (SQL_NUMROWS($result) == 0) {
1100                                 // So we add one!
1101                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
1102                                         array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1103                                 $ret = 'done';
1104                         } else {
1105                                 // Already found
1106                                 $ret = 'already';
1107                         }
1108
1109                         // Free memory
1110                         SQL_FREERESULT($result);
1111                 }
1112         }
1113
1114         // Return status for sending routine
1115         return $ret;
1116 }
1117
1118 // Calculate sum (default) or count records of given criteria
1119 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1120         $ret = 0;
1121         //* DEBUG: */ print($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />');
1122         if ((empty($search)) && ($search != '0')) {
1123                 // Count or sum whole table?
1124                 if ($countRows === true) {
1125                         // Count whole table
1126                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1127                                 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1128                 } else {
1129                         // Sum whole table
1130                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1131                                 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1132                 }
1133         } elseif (($countRows === true) || ($lookFor == 'userid')) {
1134                 // Count rows
1135                 //* DEBUG: */ print("COUNT!<br />");
1136                 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1137                         array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1138         } else {
1139                 // Add all rows
1140                 //* DEBUG: */ print("SUM!<br />");
1141                 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1142                         array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1143         }
1144
1145         // Load row
1146         list($ret) = SQL_FETCHROW($result);
1147
1148         // Free result
1149         SQL_FREERESULT($result);
1150
1151         // Fix empty values
1152         if ((empty($ret)) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1153                 // Float number
1154                 $ret = '0.00000';
1155         } elseif (''.$ret.'' == '') {
1156                 // Fix empty result
1157                 $ret = 0;
1158         }
1159
1160         // Return value
1161         return $ret;
1162 }
1163 // Getter fro ref level percents
1164 function getReferalLevelPercents ($level) {
1165         // Default is zero
1166         $per = 0;
1167
1168         // Do we have cache?
1169         if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
1170                 // First look for level
1171                 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1172                 if ($key !== false) {
1173                         // Entry found!
1174                         $per = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1175
1176                         // Count cache hit
1177                         incrementStatsEntry('cache_hits');
1178                 } // END - if
1179         } elseif (!isExtensionActive('cache')) {
1180                 // Get referal data
1181                 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
1182                         array(bigintval($level)), __FUNCTION__, __LINE__);
1183
1184                 // Entry found?
1185                 if (SQL_NUMROWS($result_level) == 1) {
1186                         // Get percents
1187                         list($per) = SQL_FETCHROW($result_level);
1188                 } // END - if
1189
1190                 // Free result
1191                 SQL_FREERESULT($result_level);
1192         }
1193
1194         // Return percent
1195         return $per;
1196 }
1197
1198 /**
1199  *
1200  * Dynamic referal system, can also send mails!
1201  *
1202  * subject     = Subject line, write in lower-case letters and underscore is allowed
1203  * userid         = Referal ID wich should receive...
1204  * points      = ... xxx points
1205  * sendNotify  = shall I send the referal an email or not?
1206  * rid         = inc/modules/guest/what-confirm.php need this
1207  * locked      = Shall I pay it to normal (false) or locked (true) points ammount?
1208  * add_mode    = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
1209  *               for default value will cause no referal will get points ever!!!)
1210  */
1211 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = 0, $locked = false, $add_mode = 'ref') {
1212         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
1213         // Convert mode to lower-case
1214         $add_mode = strtolower($add_mode);
1215
1216         // When $userid = 0 add points to jackpot
1217         if (($userid == 0) && (isExtensionActive('jackpot'))) {
1218                 // Add points to jackpot
1219                 addPointsToJackpot($points);
1220                 return;
1221         } // END - if
1222
1223         // Prepare data for the filter
1224         $filterData = array(
1225                 'subject'  => $subject,
1226                 'userid'   => $userid,
1227                 'points'   => $points,
1228                 'notify'   => $sendNotify,
1229                 'rid'      => $rid,
1230                 'locked'   => $locked,
1231                 'mode'     => 'add',
1232                 'sub_mode' => $add_mode,
1233         );
1234
1235         // Filter it now
1236         runFilterChain('add_points', $filterData);
1237
1238         // Count up referal depth
1239         if (!isset($GLOBALS['ref_level'])) {
1240                 // Initialialize referal system
1241                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal system initialized!<br />");
1242                 $GLOBALS['ref_level'] = 0;
1243         } else {
1244                 // Increase referal level
1245                 $GLOBALS['ref_level']++;
1246                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />");
1247         }
1248
1249         // Default is 'normal' points
1250         $data = 'points';
1251
1252         // Which points, locked or normal?
1253         if ($locked === true) $data = 'locked_points';
1254
1255         // Check user account
1256         $result_user = SQL_QUERY_ESC("SELECT `refid`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
1257                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1258
1259         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},numRows=".SQL_NUMROWS($result_user).",points={$points}<br />");
1260         if (SQL_NUMROWS($result_user) == 1) {
1261                 // This is the user and his ref
1262                 list($ref, $email) = SQL_FETCHROW($result_user);
1263                 $GLOBALS['cache_array']['add_userid'][$ref] = $userid;
1264
1265                 // Get percents
1266                 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1267                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />");
1268
1269                 // Some percents found?
1270                 if ($per > 0) {
1271                         // Calculate new points
1272                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />");
1273                         $ref_points = $points * $per / 100;
1274
1275                         // Pay refback here if level > 0 and in ref-mode
1276                         if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1277                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},data={$GLOBALS['cache_array']['add_userid'][$userid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - BEFORE!<br />");
1278                                 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1279                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},data={$GLOBALS['cache_array']['add_userid'][$userid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - AFTER!<br />");
1280                         } // END - if
1281
1282                         // Update points...
1283                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`='%s' LIMIT 1",
1284                                 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1285                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},userid={$userid},depth={$GLOBALS['ref_level']},mode={$add_mode} - UPDATE! (".SQL_AFFECTEDROWS().")<br />");
1286
1287                         // No entry updated?
1288                         if (SQL_AFFECTEDROWS() < 1) {
1289                                 // First ref in this level! :-)
1290                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,'%s',%s)",
1291                                         array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1292                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},userid={$userid},depth={$GLOBALS['ref_level']},mode={$add_mode} - INSERTED! (".SQL_AFFECTEDROWS().")<br />");
1293                         } // END - if
1294
1295                         // Points updated, maybe I shall send him an email?
1296                         if (($sendNotify === true) && ($ref > 0) && ($locked === false)) {
1297                                 // Prepare content
1298                                 $content = array(
1299                                         'percents' => $per,
1300                                         'level'    => bigintval($GLOBALS['ref_level']),
1301                                         'points'   => $ref_points,
1302                                         'refid'    => bigintval($ref)
1303                                 );
1304
1305                                 // Load email template
1306                                 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1307
1308                                 sendEmail($email, THANX_REFERRAL_ONE, $message);
1309                         } elseif (($sendNotify) && ($ref == 0) && ($locked === false) && ($add_mode == 'direct')) {
1310                                 // Prepare content
1311                                 $content = array(
1312                                         'text'   => getMessage('REASON_DIRECT_PAYMENT'),
1313                                         'points' => translateComma($ref_points)
1314                                 );
1315
1316                                 // Load message
1317                                 $message = loadEmailTemplate('add-points', $content, $userid);
1318
1319                                 // And sent it away
1320                                 sendEmail($email, getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
1321                                 if (!isGetRequestElementSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1322                         }
1323
1324                         // Maybe there's another ref?
1325                         if (($ref > 0) && ($points > 0) && ($ref != $userid) && ($add_mode == 'ref')) {
1326                                 // Then let's credit him here...
1327                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref},points={$points} - ADVANCE!<br />");
1328                                 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), $ref, $points, $sendNotify, $ref, $locked);
1329                         } // END - if
1330                 } // END - if
1331         } // END - if
1332
1333         // Free result
1334         SQL_FREERESULT($result_user);
1335         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
1336 }
1337
1338 // Updates the referal counter
1339 function updateReferalCounter ($userid) {
1340         // Make it sure referal level zero (member him-/herself) is at least selected
1341         if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1342         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}<br />");
1343
1344         // Update counter
1345         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1346                 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1347
1348         // When no entry was updated then we have to create it here
1349         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS().'<br />');
1350         if (SQL_AFFECTEDROWS() < 1) {
1351                 // First count!
1352                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1353                         array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1354                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid}<br />");
1355         } // END - if
1356
1357         // Check for his referal
1358         $result = SQL_QUERY_ESC("SELECT `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
1359                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1360
1361         // Load refid
1362         list($ref) = SQL_FETCHROW($result);
1363
1364         // Free memory
1365         SQL_FREERESULT($result);
1366         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref}<br />");
1367
1368         // When he has a referal...
1369         if (($ref > 0) && ($ref != $userid)) {
1370                 // Move to next referal level and count his counter one up!
1371                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />");
1372                 $GLOBALS['cache_array']['ref_level'][$userid]++; updateReferalCounter($ref);
1373         } elseif ((($ref == $userid) || ($ref == 0)) && (getExtensionVersion('cache') >= '0.1.2')) {
1374                 // Remove cache here
1375                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />");
1376                 rebuildCacheFile('refsystem', 'refsystem');
1377         }
1378
1379         // "Walk" back here
1380         $GLOBALS['cache_array']['ref_level'][$userid]--;
1381
1382         // Handle refback here if extension is installed
1383         if (isExtensionActive('refback')) {
1384                 updateRefbackTable($userid);
1385         } // END - if
1386 }
1387
1388 // Sends out mail to all administrators. This function is no longer obsolete
1389 // because we need it when there is no ext-admins installed
1390 function sendAdminEmails ($subj, $message) {
1391         // Load all admin email addresses
1392         $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1393         while ($content = SQL_FETCHARRAY($result)) {
1394                 // Send the email out
1395                 sendEmail($content['email'], $subj, $message);
1396         } // END - if
1397
1398         // Free result
1399         SQL_FREERESULT($result);
1400
1401         // Really simple... ;-)
1402 }
1403
1404 // Get ID number from administrator's login name
1405 function getAdminId ($login) {
1406         // By default no admin is found
1407         $ret = '-1';
1408
1409         // Check cache
1410         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$login])) {
1411                 // Use it if found to save SQL queries
1412                 $ret = $GLOBALS['cache_array']['admin']['admin_id'][$login];
1413
1414                 // Update cache hits
1415                 incrementStatsEntry('cache_hits');
1416         } elseif (!isExtensionActive('cache')) {
1417                 // Load from database
1418                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1419                         array($login), __FUNCTION__, __LINE__);
1420                 if (SQL_NUMROWS($result) == 1) {
1421                         list($ret) = SQL_FETCHROW($result);
1422                 } // END - if
1423
1424                 // Free result
1425                 SQL_FREERESULT($result);
1426         }
1427         return $ret;
1428 }
1429
1430 // "Getter" for current admin id
1431 function getCurrentAdminId () {
1432         // Do we have cache?
1433         if (!isset($GLOBALS['current_admin_id'])) {
1434                 // Get the admin login from session
1435                 $adminLogin = getSession('admin_login');
1436
1437                 // "Solve" it into an id
1438                 $adminId = getAdminId($adminLogin);
1439
1440                 // Remember in cache securely
1441                 $GLOBALS['current_admin_id'] = bigintval($adminId);
1442         } // END - if
1443
1444         // Return it
1445         return $GLOBALS['current_admin_id'];
1446 }
1447
1448 // Get password hash from administrator's login name
1449 function getAdminHash ($admin) {
1450         // By default an invalid hash is returned
1451         $ret = '-1';
1452
1453         if (isAdminHashSet($admin)) {
1454                 // Check cache
1455                 $ret = $GLOBALS['cache_array']['admin']['password'][$admin];
1456
1457                 // Update cache hits
1458                 incrementStatsEntry('cache_hits');
1459         } elseif (!isExtensionActive('cache')) {
1460                 // Load from database
1461                 $result = SQL_QUERY_ESC("SELECT password FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1462                         array($admin), __FUNCTION__, __LINE__);
1463                 if (SQL_NUMROWS($result) == 1) {
1464                         // Fetch data
1465                         list($ret) = SQL_FETCHROW($result);
1466
1467                         // Set cache
1468                         setAdminHash($admin, $ret);
1469                 } // END - if
1470
1471                 // Free result
1472                 SQL_FREERESULT($result);
1473         }
1474         return $ret;
1475 }
1476
1477 // "Getter" for admin login
1478 function getAdminLogin ($adminId) {
1479         // By default a non-existent login is returned (other functions react on this!)
1480         $ret = '***';
1481
1482         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1483                 // Get cache
1484                 $ret = $GLOBALS['cache_array']['admin']['login'][$adminId];
1485
1486                 // Update cache hits
1487                 incrementStatsEntry('cache_hits');
1488         } elseif (!isExtensionActive('cache')) {
1489                 // Load from database
1490                 $result = SQL_QUERY_ESC("SELECT login FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1491                 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1492                 if (SQL_NUMROWS($result) == 1) {
1493                         // Fetch data
1494                         list($ret) = SQL_FETCHROW($result);
1495
1496                         // Set cache
1497                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $ret;
1498                 } // END - if
1499
1500                 // Free memory
1501                 SQL_FREERESULT($result);
1502         }
1503         return $ret;
1504 }
1505
1506 // Get email address of admin id
1507 function getAdminEmail ($adminId) {
1508         // By default an invalid emails is returned
1509         $ret = '***';
1510
1511         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1512                 // Get cache
1513                 $ret = $GLOBALS['cache_array']['admin']['email'][$adminId];
1514
1515                 // Update cache hits
1516                 incrementStatsEntry('cache_hits');
1517         } elseif (!isExtensionActive('cache')) {
1518                 // Load from database
1519                 $result_admin_id = SQL_QUERY_ESC("SELECT email FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1520                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1521                 if (SQL_NUMROWS($result_admin_id) == 1) {
1522                         // Get data
1523                         list($ret) = SQL_FETCHROW($result_admin_id);
1524
1525                         // Set cache
1526                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $ret;
1527                 } // END - if
1528
1529                 // Free result
1530                 SQL_FREERESULT($result_admin_id);
1531         }
1532
1533         // Return email
1534         return $ret;
1535 }
1536
1537 // Get default ACL  of admin id
1538 function getAdminDefaultAcl ($adminId) {
1539         // By default an invalid ACL value is returned
1540         $ret = '***';
1541
1542         // Is sql_patches there and was it found in cache?
1543         if (!isExtensionActive('sql_patches')) {
1544                 // Not found, which is bad, so we need to allow all
1545                 $ret =  'allow';
1546         } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1547                 // Use cache
1548                 $ret = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1549
1550                 // Update cache hits
1551                 incrementStatsEntry('cache_hits');
1552         } elseif (!isExtensionActive('cache')) {
1553                 // Load from database
1554                 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1555                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1556                 if (SQL_NUMROWS($result_admin_id) == 1) {
1557                         // Fetch data
1558                         list($ret) = SQL_FETCHROW($result_admin_id);
1559
1560                         // Set cache
1561                         $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $ret;
1562                 }
1563
1564                 // Free result
1565                 SQL_FREERESULT($result_admin_id);
1566         }
1567
1568         // Return email
1569         return $ret;
1570 }
1571
1572 // Generates an option list from various parameters
1573 function generateOptionList ($table, $id, $name, $default='', $special='', $where='') {
1574         $ret = '';
1575         if ($table == '/ARRAY/') {
1576                 // Selection from array
1577                 if (is_array($id) && is_array($name) && count($id) == count($name)) {
1578                         // Both are arrays
1579                         foreach ($id as $idx => $value) {
1580                                 $ret .= '<option value="' . $value . '"';
1581                                 if ($default == $value) $ret .= ' selected="selected"';
1582                                 $ret .= '>' . $name[$idx] . '</option>';
1583                         } // END - foreach
1584                 } // END - if
1585         } else {
1586                 // Data from database
1587                 $SPEC = ', '.$id;
1588                 if (!empty($special)) $SPEC = ', ' . $special;
1589                 $ORDER = $name.$SPEC;
1590                 if ($table == 'country') $ORDER = $special;
1591                 $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY %s",
1592                 array($id, $ORDER, $table, $name), __FUNCTION__, __LINE__);
1593                 if (SQL_NUMROWS($result) > 0) {
1594                         // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1595                         // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1596                         while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1597                                 if (empty($special)) $add = '';
1598                                 $ret .= '<option value="' . $value . '"';
1599                                 if ($default == $value) $ret .= ' selected="selected"';
1600                                 if (!empty($add)) $add = ' ('.$add.')';
1601                                 $ret .= '>' . $title . $add . '</option>';
1602                         } // END - while
1603
1604                         // Free memory
1605                         SQL_FREERESULT($result);
1606                 } else {
1607                         // No data found
1608                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1609                 }
1610         }
1611
1612         // Return - hopefully - the requested data
1613         return $ret;
1614 }
1615 // Activate exchange
1616 function FILTER_ACTIVATE_EXCHANGE () {
1617         // Is the extension 'user' there?
1618         if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == 0)) {
1619                 // Silently abort here
1620                 return false;
1621         } // END - if
1622
1623         // Check total amount of users
1624         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1625
1626         if ($totalUsers >= getConfig('activate_xchange')) {
1627                 // Activate System
1628                 setSqlsArray(array(
1629                         "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1630                         "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1631                 ));
1632
1633                 // Run SQLs
1634                 runFilterChain('run_sqls');
1635
1636                 // Update configuration
1637                 updateConfiguration('activate_xchange' ,0);
1638
1639                 // Rebuild cache
1640                 rebuildCacheFile('modules', 'modules');
1641         } // END - if
1642 }
1643
1644 // Deletes a user account with given reason
1645 function deleteUserAccount ($userid, $reason) {
1646         $points = 0;
1647         $result = SQL_QUERY_ESC("SELECT
1648         (SUM(p.points) - d.used_points) AS points
1649 FROM
1650         `{?_MYSQL_PREFIX?}_user_points` AS p
1651 LEFT JOIN
1652         `{?_MYSQL_PREFIX?}_user_data` AS d
1653 ON
1654         p.userid=d.userid
1655 WHERE
1656         p.userid=%s",
1657                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1658         if (SQL_NUMROWS($result) == 1) {
1659                 // Save his points to add them to the jackpot
1660                 list($points) = SQL_FETCHROW($result);
1661
1662                 // Delete points entries as well
1663                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s", array(bigintval($userid)), __FUNCTION__, __LINE__);
1664
1665                 // Update mediadata as well
1666                 if (getExtensionVersion('mediadata') >= '0.0.4') {
1667                         // Update database
1668                         updateMediadataEntry(array('total_points'), 'sub', $points);
1669                 } // END - if
1670
1671                 // Now, when we have all his points adds them do the jackpot!
1672                 if (isExtensionActive('jackpot')) addPointsToJackpot($points);
1673         } // END - if
1674
1675         // Free the result
1676         SQL_FREERESULT($result);
1677
1678         // Delete category selections as well...
1679         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1680                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1681
1682         // Remove from rallye if found
1683         if (isExtensionActive('rallye')) {
1684                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1685                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1686         } // END - if
1687
1688         // Now a mail to the user and that's all...
1689         $message = loadEmailTemplate('del-user', array('text' => $reason), $userid);
1690         sendEmail($userid, getMessage('ADMIN_DEL_ACCOUNT'), $message);
1691
1692         // Ok, delete the account!
1693         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1694 }
1695
1696 // Generates meta description for given module and 'what' value
1697 function generateMetaDescriptionCode ($mod, $what) {
1698         // Exclude admin and member's area
1699         if (($mod != 'admin') && ($mod != 'login')) {
1700                 // Construct dynamic description
1701                 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . addMenuDescription('guest', 'what-'.$what, true);
1702
1703                 // Output it directly
1704                 outputHtml('<meta name="description" content="' . $DESCR . '" />');
1705         } // END - if
1706
1707         // Remove depth
1708         unset($GLOBALS['ref_level']);
1709 }
1710
1711 // Gets the matching what name from module
1712 function getWhatFromModule ($modCheck) {
1713         // Is the request element set?
1714         if (isGetRequestElementSet('what')) {
1715                 // Then return this!
1716                 return getRequestElement('what');
1717         } // END - if
1718
1719         // Default is empty
1720         $what = '';
1721
1722         //* DEBUG: */ print(__LINE__.'!'.$modCheck."!<br />");
1723         switch ($modCheck) {
1724                 case 'admin':
1725                         $what = 'overview';
1726                         break;
1727
1728                 case 'login':
1729                 case 'index':
1730                         // Is ext-sql_patches installed and newer than 0.0.5?
1731                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1732                                 // Use it from config
1733                                 $what = getConfig('index_home');
1734                         } else {
1735                                 // Use default 'welcome'
1736                                 $what = 'welcome';
1737                         }
1738                         break;
1739
1740                 default:
1741                         $what = '';
1742                         break;
1743         } // END - switch
1744
1745         // Return what value
1746         return $what;
1747 }
1748
1749 // Subtract points from database and mediadata cache
1750 function subtractPoints ($subject, $userid, $points) {
1751         // Add points to used points
1752         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1753                 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1754
1755         // Prepare filter data
1756         $filterData = array(
1757                 'subject' => $subject,
1758                 'userid'  => $userid,
1759                 'points'  => $points,
1760                 'mode'    => 'sub'
1761         );
1762
1763         // Insert booking record
1764         runFilterChain('sub_points', $filterData);
1765 }
1766
1767 // "Getter" for total available receivers
1768 function getTotalReceivers ($mode='normal') {
1769         // Query database
1770         $result_all = SQL_QUERY("SELECT
1771         `userid`
1772 FROM
1773         `{?_MYSQL_PREFIX?}_user_data`
1774 WHERE
1775         `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1776         __FUNCTION__, __LINE__);
1777
1778         // Get num rows
1779         $numRows = SQL_NUMROWS($result_all);
1780
1781         // Free result
1782         SQL_FREERESULT($result_all);
1783
1784         // Return value
1785         return $numRows;
1786 }
1787
1788 // Returns HTML code with an "<option> list" of all categories
1789 function generateCategoryOptionsList ($mode) {
1790         // Prepare WHERE statement
1791         $whereStatement = " WHERE `visible`='Y'";
1792         if (isAdmin()) $whereStatement = '';
1793
1794         // Initialize array...
1795         $CATS = array(
1796                 'id'   => array(),
1797                 'name' => array(),
1798                 'userids' => array()
1799         );
1800
1801         // Get categories
1802         $result = SQL_QUERY("SELECT id, cat FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort`", __FUNCTION__, __LINE__);
1803         if (SQL_NUMROWS($result) > 0) {
1804                 // ... and begin loading stuff
1805                 while ($content = SQL_FETCHARRAY($result)) {
1806                         // Transfer some data
1807                         $CATS['id'][]   = $content['id'];
1808                         $CATS['name'][] = $content['cat'];
1809
1810                         // Check which users are in this category
1811                         $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s",
1812                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1813
1814                         // Start adding all
1815                         $userid_cnt = 0;
1816                         // @TODO Rewrite this to $content = SQL_FETCHARRAY()
1817                         while (list($ucat) = SQL_FETCHROW($result_userids)) {
1818                                 $result_ver = SQL_QUERY_ESC("SELECT
1819         `userid`
1820 FROM
1821         `{?_MYSQL_PREFIX?}_user_data`
1822 WHERE
1823         `userid`=%s AND `status`='CONFIRMED' AND `receive_mails` > 0".runFilterChain('exclude_users', $mode)."
1824 LIMIT 1",
1825                                         array(bigintval($ucat)), __FUNCTION__, __LINE__);
1826
1827                                 // Add user count
1828                                 $userid_cnt += SQL_NUMROWS($result_ver);
1829
1830                                 // Free memory
1831                                 SQL_FREERESULT($result_ver);
1832                         } // END - while
1833
1834                         // Free memory
1835                         SQL_FREERESULT($result_userids);
1836
1837                         // Add counter
1838                         $CATS['userids'][] = $userid_cnt;
1839                 } // END - while
1840
1841                 // Free memory
1842                 SQL_FREERESULT($result);
1843
1844                 // Generate options
1845                 $OUT = '';
1846                 foreach ($CATS['id'] as $key => $value) {
1847                         if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1848                         $OUT .= '      <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1849                 } // END - foreach
1850         } else {
1851                 // No cateogries are defined yet
1852                 $OUT = '<option class="member_failed">{--MEMBER_NO_CATS--}</option>';
1853         }
1854
1855         // Return HTML code
1856         return $OUT;
1857 }
1858
1859 // Add bonus mail to queue
1860 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1861         // Is admin or bonus extension there?
1862         if (!isAdmin()) {
1863                 // Abort here
1864                 return false;
1865         } elseif (!isExtensionActive('bonus')) {
1866                 // Abort here
1867                 return false;
1868         }
1869
1870         // Calculcate target sent
1871         $target = countSelection(explode(';', $receiverList));
1872
1873         // Receiver is zero?
1874         if ($receiver == 0) {
1875                 // Then auto-fix it
1876                 $receiver = $target;
1877         } // END - if
1878
1879         // HTML extension active?
1880         if (isExtensionActive('html_mail')) {
1881                 // No HTML by default
1882                 $HTML = 'N';
1883
1884                 // HTML mode?
1885                 if ($mode == 'html') $HTML = 'Y';
1886
1887                 // Add HTML mail
1888                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1889 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1890 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1891                 array(
1892                         $subject,
1893                         $text,
1894                         $receiverList,
1895                         $points,
1896                         $seconds,
1897                         $url,
1898                         $cat,
1899                         $target,
1900                         bigintval($receiver),
1901                         $HTML
1902                 ), __FUNCTION__, __LINE__);
1903         } else {
1904                 // Add regular mail
1905                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1906 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1907 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1908                 array(
1909                         $subject,
1910                         $text,
1911                         $receiverList,
1912                         $points,
1913                         $seconds,
1914                         $url,
1915                         $cat,
1916                         $target,
1917                         bigintval($receiver),
1918                 ), __FUNCTION__, __LINE__);
1919         }
1920 }
1921
1922 // Generate a receiver list for given category and maximum receivers
1923 function generateReceiverList ($cat, $receiver, $mode = '') {
1924         // Init variables
1925         $CAT_TABS     = '';
1926         $CAT_WHERE    = '';
1927         $receiverList = '';
1928         $result       = false;
1929
1930         // Secure data
1931         $cat      = bigintval($cat);
1932         $receiver = bigintval($receiver);
1933
1934         // Is the receiver zero and mode set?
1935         if (($receiver == 0) && (!empty($mode))) {
1936                 // Auto-fix receiver maximum
1937                 $receiver = getTotalReceivers($mode);
1938         } // END - if
1939
1940         // Category given?
1941         if ($cat > 0) {
1942                 // Select category
1943                 $CAT_TABS  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
1944                 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
1945         } // END - if
1946
1947         // Exclude users in holiday?
1948         if (getExtensionVersion('holiday') >= '0.1.3') {
1949                 // Add something for the holiday extension
1950                 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1951         } // END - if
1952
1953         if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1954                 // Only include HTML receivers
1955                 $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED' AND d.`html`='Y'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
1956                         array(
1957                                 $receiver
1958                         ), __FUNCTION__, __LINE__);
1959         } else {
1960                 // Include all
1961                 $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
1962                         array(
1963                                 $receiver
1964                         ), __FUNCTION__, __LINE__);
1965         }
1966
1967         // Entries found?
1968         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1969                 // Load all entries
1970                 while ($content = SQL_FETCHARRAY($result)) {
1971                         // Add receiver when not empty
1972                         if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1973                 } // END - while
1974
1975                 // Free memory
1976                 SQL_FREERESULT($result);
1977
1978                 // Remove trailing semicolon
1979                 $receiverList = substr($receiverList, 0, -1);
1980         } // END - if
1981
1982         // Return list
1983         return $receiverList;
1984 }
1985
1986 // Get timestamp for given stats type and data
1987 function getTimestampFromUserStats ($type, $data, $userid = 0) {
1988         // Default timestamp is zero
1989         $stamp = 0;
1990
1991         // User id set?
1992         if ((isUserIdSet()) && ($userid == 0)) {
1993                 $userid = getUserId();
1994         } // END - if
1995
1996         // Is the extension installed and updated?
1997         if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
1998                 // Return zero here
1999                 return $stamp;
2000         } // END - if
2001
2002         // Try to find the entry
2003         $result = SQL_QUERY_ESC("SELECT
2004         UNIX_TIMESTAMP(`inserted`) AS stamp
2005 FROM
2006         `{?_MYSQL_PREFIX?}_user_stats_data`
2007 WHERE
2008         `userid`=%s AND `stats_type`='%s' AND `stats_data`='%s'
2009 LIMIT 1",
2010                 array(
2011                         bigintval($userid),
2012                         $type,
2013                         $data
2014                 ), __FUNCTION__, __LINE__);
2015
2016         // Is the entry there?
2017         if (SQL_NUMROWS($result) == 1) {
2018                 // Get this stamp
2019                 list($stamp) = SQL_FETCHROW($result);
2020         } // END - if
2021
2022         // Free result
2023         SQL_FREERESULT($result);
2024
2025         // Return stamp
2026         return $stamp;
2027 }
2028
2029 // Inserts user stats
2030 function insertUserStatsRecord ($userid, $type, $data) {
2031         // Is the extension installed and updated?
2032         if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
2033                 // Return zero here
2034                 return false;
2035         } // END - if
2036
2037         // Does it exist?
2038         if ((!getTimestampFromUserStats($type, $data, $userid)) && (!is_array($data))) {
2039                 // Then insert it!
2040                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
2041                         array(bigintval($userid), $type, $data), __FUNCTION__, __LINE__);
2042         } elseif (is_array($data)) {
2043                 // Invalid data!
2044                 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$type},data={".gettype($data).": Invalid statistics data type!");
2045         }
2046 }
2047
2048 // "Getter" for array for user refs and points in given level
2049 function getUserReferalPoints ($userid, $level) {
2050         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
2051         // Default is no refs and no nickname
2052         $add = '';
2053         $refs = array();
2054
2055         // Do we have nickname extension installed?
2056         if (isExtensionActive('nickname')) {
2057                 $add = ', ud.nickname';
2058         } // END - if
2059
2060         // Get refs from database
2061         $result = SQL_QUERY_ESC("SELECT
2062         ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2063 FROM
2064         `{?_MYSQL_PREFIX?}_user_refs` AS ur
2065 LEFT JOIN
2066         `{?_MYSQL_PREFIX?}_user_points` AS up
2067 ON
2068         ur.refid=up.userid AND ur.level=0
2069 LEFT JOIN
2070         `{?_MYSQL_PREFIX?}_user_data` AS ud
2071 ON
2072         ur.refid=ud.userid
2073 WHERE
2074         ur.userid=%s AND ur.level=%s
2075 ORDER BY ur.refid ASC",
2076                 array(
2077                         bigintval($userid),
2078                         bigintval($level)
2079                 ), __FUNCTION__, __LINE__);
2080
2081         // Are there some entries?
2082         if (SQL_NUMROWS($result) > 0) {
2083                 // Fetch all entries
2084                 while ($row = SQL_FETCHARRAY($result)) {
2085                         // Get total points of this user
2086                         $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
2087
2088                         // Get unconfirmed mails
2089                         $row['unconfirmed']  = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
2090
2091                         // Init clickrate with zero
2092                         $row['clickrate'] = 0;
2093
2094                         // Is at least one mail received?
2095                         if ($row['emails_received'] > 0) {
2096                                 // Calculate clickrate
2097                                 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2098                         } // END - if
2099
2100                         // Activity is 'active' by default because if autopurge is not installed
2101                         $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2102
2103                         // Is autopurge installed and the user inactive?
2104                         if ((isExtensionActive('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online']))  {
2105                                 // Inactive user!
2106                                 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2107                         } // END - if
2108
2109                         // Remove some entries
2110                         unset($row['mails_confirmed']);
2111                         unset($row['emails_received']);
2112                         unset($row['last_online']);
2113
2114                         // Add row
2115                         $refs[$row['id']] = $row;
2116                 } // END - while
2117         } // END - if
2118
2119         // Free result
2120         SQL_FREERESULT($result);
2121
2122         // Return result
2123         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
2124         return $refs;
2125 }
2126
2127 // Recuce the amount of received emails for the receipients for given email
2128 function reduceRecipientReceivedMails ($column, $id, $count) {
2129         // Search for mail in database
2130         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2131                 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2132
2133         // Are there entries?
2134         if (SQL_NUMROWS($result) > 0) {
2135                 // Now load all userids for one big query!
2136                 // @TODO This can be somehow rewritten
2137                 $UIDs = array();
2138                 while (list($userid) = SQL_FETCHROW($result)) {
2139                         $UIDs[$userid] = $userid;
2140                 } // END - while
2141
2142                 // Now update all user accounts
2143                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2144                         array(implode(',', $UIDs), count($UIDs)), __FUNCTION__, __LINE__);
2145         } // END - if
2146
2147         // Free result
2148         SQL_FREERESULT($result);
2149 }
2150
2151 // Creates a new task
2152 function createNewTask ($subject, $notes, $taskType, $userid = 0, $adminId = 0, $strip = true) {
2153         // Insert the task data into the database
2154         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_task_system` (`assigned_admin`, `userid`, `status`, `task_type`, `subject`, `text`, `task_created`) VALUES (%s,%s,'NEW','%s','%s','%s', UNIX_TIMESTAMP())",
2155                 array($adminId, $userid, $taskType, $subject, smartAddSlashes($notes)), __FUNCTION__, __LINE__, true, $strip);
2156 }
2157
2158 // [EOF]
2159 ?>