Rewrites to use filters instead of mass if() blocks
[mailer.git] / inc / mysql-manager.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/26/2003 *
4  * ===================                          Last change: 11/29/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : mysql-manager.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : All database-related functions                   *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle datenbank-relevanten Funktionen             *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // "Getter" for module description
44 // @TODO Can we cache this?
45 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD = '') {
46         // Debug message
47         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',what=' . $what . ',column=' . $column . ',add=' . $ADD);
48
49         // Fix empty 'what'
50         if (empty($what)) {
51                 $what = getIndexHome();
52         } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
53                 // Get it from action
54                 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
55         } elseif ($what == 'welcome') {
56                 // Overview page
57                 return '{--WHAT_IS_WELCOME--}';
58         }
59
60         // Default is not found
61         $data['title'] = '??? (' . $what . ')';
62
63         // Look for title
64         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
65                 array(
66                         $mode,
67                         $column,
68                         $what
69                 ), __FUNCTION__, __LINE__);
70
71         // Is there an entry?
72         if (SQL_NUMROWS($result) == 1) {
73                 // Fetch the title
74                 $data = SQL_FETCHARRAY($result);
75         } // END - if
76
77         // Free result
78         SQL_FREERESULT($result);
79
80         // Return it
81         return $data['title'];
82 }
83
84 // Add link into output stream (or return it) for 'You Are Here' navigation
85 function addYouAreHereLink ($accessLevel, $FQFN, $return = FALSE) {
86         // Use only filename of the FQFN...
87         $file = basename($FQFN);
88
89         // Init variables
90         $linkAdd = '';
91         $OUT = '';
92         $ADD = '';
93         $prefix = '';
94
95         // First we have to do some analysis...
96         if (substr($file, 0, 7) == 'action-') {
97                 // This is an action file!
98                 $type = 'action';
99                 $search = substr($file, 7);
100
101                 // Get access level from it
102                 $modCheck = getModuleFromFileName($file, $accessLevel);
103
104                 // Add what
105                 $ADD = " AND (`what`='' OR `what` IS NULL)";
106         } elseif (substr($file, 0, 5) == 'what-') {
107                 // This is a 'what file'!
108                 $type = 'what';
109                 $search = substr($file, 5);
110
111                 // Get access level from it
112                 $modCheck = getModuleFromFileName($file, $accessLevel);
113
114                 // Is there admin? Then display all
115                 $ADD = " AND `visible`='Y' AND `locked`='N'";
116                 if (isAdmin()) {
117                         // Display all!
118                         $ADD = '';
119                 } // END - if
120
121                 $dummy = substr($search, 0, -4);
122                 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
123         } elseif ($accessLevel == 'sponsor') {
124                 // Sponsor menu
125                 $type     = 'what';
126                 $search   = $file;
127                 $modCheck = getModule();
128         } else {
129                 // Other
130                 $type     = 'menu';
131                 $search   = $file;
132                 $modCheck = getModule();
133         }
134
135         // Begin the navigation line
136         if (!isset($GLOBALS['nav_depth'])) {
137                 // Init nav_depth
138                 $GLOBALS['nav_depth'] = '0';
139
140                 // Run the pre-filter chain
141                 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => '', 'add' => $ADD));
142
143                 // Add pre-content
144                 $prefix = $ret['content'];
145
146                 // Add default content
147                 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--}&nbsp;<strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $linkAdd . '%}">Home</a></strong>';
148         } elseif ($return === FALSE) {
149                 // Count depth
150                 $GLOBALS['nav_depth']++;
151         }
152
153         // Add arrow
154         $prefix .= '&nbsp;-&gt;&nbsp;';
155
156         // We need to remove .php and the end
157         if (substr($search, -4, 4) == '.php') {
158                 // Remove the .php
159                 $search = substr($search, 0, -4);
160         } // END - if
161
162         // Is ext-sql_patches installed?
163         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isExtensionInstalledAndNewer()=' . intval(isExtensionInstalledAndNewer('sql_patches', '0.2.3')) . ',youre_here=' . getYoureHere() . ',isAdmin()=' . intval(isAdmin()) . ',modCheck=' . $modCheck);
164         if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (isYoureHereEnabled())) || ((isAdmin()) && ($modCheck == 'admin'))) {
165                 // Output HTML code
166                 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&amp;' . $type . '=' . $search . $linkAdd . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
167
168                 // Can we close the you-are-here navigation?
169                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',getWhat()=' . getWhat() . ',accessLevel=' . $accessLevel . ',isWhatSet()=' . intval(isWhatSet()));
170                 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (($accessLevel == 'admin') && (getWhat() == 'welcome'))))) {
171                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
172                         // Add closing div and br-tag
173                         $GLOBALS['nav_depth'] = '0';
174
175                         // Run the post-filter chain
176                         $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => $OUT, 'add' => $ADD));
177
178                         // Get content from filter back
179                         $OUT = $ret['content'];
180
181                         // Close div-tag, so not the filters have to do it
182                         $OUT .= '</div>';
183                 } // END - if
184         } // END - if
185
186         // Return or output HTML code?
187         if ($return === TRUE) {
188                 // Return HTML code
189                 return $OUT;
190         } else {
191                 // Output HTML code here
192                 outputHtml($OUT);
193         }
194 }
195
196 // Adds a menu (mode = guest/member/admin/sponsor) to output
197 function addMenu ($mode, $action, $what) {
198         // Init some variables
199         $main_cnt = '0';
200
201         // is the menu action valid?
202         if (!isMenuActionValid($mode, $action, $what, TRUE)) {
203                 return getCode('MENU_NOT_VALID');
204         } // END - if
205
206         // Non-admin shall not see all menus
207         $ADD = " AND `visible`='Y' AND `locked`='N'";
208         if (isAdmin()) {
209                 // Is admin, so make all visible
210                 $ADD = '';
211         } // END - if
212
213         // Load SQL data and add the menu to the output stream...
214         $result_main = SQL_QUERY_ESC("SELECT
215         `title`,
216         `what`,
217         `action`,
218         `visible`,
219         `locked`
220 FROM
221         `{?_MYSQL_PREFIX?}_%s_menu`
222 WHERE
223         (`what`='' OR `what` IS NULL)
224         ".$ADD."
225 ORDER BY
226         `sort` ASC",
227                 array($mode), __FUNCTION__, __LINE__);
228
229         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
230         if (!SQL_HASZERONUMS($result_main)) {
231                 // There are menus available, so we simply display them... :)
232                 $GLOBALS['rows'] = '';
233                 while ($content = SQL_FETCHARRAY($result_main)) {
234                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
235                         // Disable the block-mode
236                         enableBlockMode(FALSE);
237
238                         // Load menu header template
239                         $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', TRUE, $content);
240
241                         // Sub menu
242                         $result_sub = SQL_QUERY_ESC("SELECT
243         `title` AS `sub_title`,
244         `what` AS `sub_what`,
245         `visible` AS `sub_visible`,
246         `locked` AS `sub_locked`
247 FROM
248         `{?_MYSQL_PREFIX?}_%s_menu`
249 WHERE
250         `action`='%s' AND
251         `what` != '' AND
252         `what` IS NOT NULL
253         " . $ADD . "
254 ORDER BY
255         `sort` ASC",
256                                 array(
257                                         $mode,
258                                         $content['action']
259                                 ), __FUNCTION__, __LINE__);
260
261                         // Are there some entries?
262                         if (!SQL_HASZERONUMS($result_sub)) {
263                                 // Init counter
264                                 $count = '0';
265
266                                 // Load all sub menus
267                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
268                                         // Merge both arrays in one
269                                         $content = merge_array($content, $content2);
270
271                                         // Init content
272                                         $OUT = '';
273
274                                         // Full file name for checking menu
275                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
276                                         $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
277                                         if (isIncludeReadable($inc)) {
278                                                 // Mark currently selected menu - open
279                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
280                                                         $OUT = '<strong>';
281                                                 } // END - if
282
283                                                 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
284                                                 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
285                                                         // Use index.php as link
286                                                         $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
287                                                 } else {
288                                                         // Regular navigation link
289                                                         $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&amp;what=' . $content['sub_what'] . '%}" target="_self">';
290                                                 }
291                                         } else {
292                                                 // Not found - open
293                                                 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
294                                         }
295
296                                         // Menu title
297                                         $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
298
299                                         if (isIncludeReadable($inc)) {
300                                                 $OUT .= '</a>';
301
302                                                 // Mark currently selected menu - close
303                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
304                                                         $OUT .= '</strong>';
305                                                 } // END - if
306                                         } else {
307                                                 // Not found - close
308                                                 $OUT .= '</span>';
309                                         }
310
311                                         // Cunt it up
312                                         $count++;
313
314                                         // Rewrite array
315                                         $content = array(
316                                                 'menu'    => $OUT,
317                                                 'what'    => $content['sub_what'],
318                                                 'visible' => $content['sub_visible'],
319                                                 'locked'  => $content['locked'],
320                                         );
321
322                                         // Add regular menu row or bottom row?
323                                         if ($count < SQL_NUMROWS($result_sub)) {
324                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', TRUE, $content);
325                                         } else {
326                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', TRUE, $content);
327                                         }
328                                 } // END - while
329                         } else {
330                                 // This is a menu block... ;-)
331                                 enableBlockMode();
332
333                                 // Load menu block
334                                 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
335                                 if (isFileReadable($INC)) {
336                                         // Load include file
337                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', TRUE, $mode);
338                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
339                                         loadInclude($INC);
340                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
341                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', TRUE, $mode);
342                                 }
343                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
344                         }
345
346                         // Free result
347                         SQL_FREERESULT($result_sub);
348
349                         // Count one up
350                         $main_cnt++;
351
352                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
353                         if (SQL_NUMROWS($result_main) > $main_cnt) {
354                                 // Add separator
355                                 $GLOBALS['rows'] .= loadTemplate('menu_separator', TRUE, $mode);
356
357                                 // Prepare filter data array
358                                 $filterData = array(
359                                         'output'    => '',
360                                         'exclusive' => FALSE,
361                                         'action'    => $action,
362                                         'mode'      => $mode,
363                                 );
364
365                                 // Run filter chain
366                                 $filterData = runFilterChain($mode . '_menu_advert', $filterData);
367
368                                 // Add content output
369                                 $GLOBALS['rows'] .= $filterData['output'];
370                         } // END - if
371                 } // END - while
372
373                 // Free memory
374                 SQL_FREERESULT($result_main);
375
376                 // Prepare filter data array
377                 $filterData = array(
378                         'output'    => '',
379                         'exclusive' => FALSE,
380                         'action'    => $action,
381                         'mode'      => $mode,
382                 );
383
384                 // Run filter chain
385                 $filterData = runFilterChain($mode . '_menu_advert_end', $filterData);
386
387                 // Add content output
388                 $GLOBALS['rows'] .= $filterData['output'];
389
390                 // Prepare data
391                 $content = array(
392                         'rows'      => $GLOBALS['rows'],
393                         'menu_mode' => $mode
394                 );
395
396                 // Load main template
397                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
398                 loadTemplate('menu_table', FALSE, $content);
399         } // END - if
400 }
401
402 // Checks whether the current user is a member
403 function isMember () {
404         // By default no member
405         $ret = FALSE;
406
407         // Fix missing 'last_online' array, damn stupid code :(((
408         // @TODO Try to rewrite this to one or more functions
409         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
410                 $GLOBALS['last_online'] = array();
411         } // END - if
412
413         // Is the cache entry there?
414         if (isset($GLOBALS[__FUNCTION__])) {
415                 // Then return it
416                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
417                 return $GLOBALS[__FUNCTION__];
418         } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
419                 // Destroy any existing user session data
420                 destroyMemberSession();
421                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
422
423                 // Abort further processing
424                 return FALSE;
425         }
426
427         // Get userid secured from session
428         setMemberId(getSession('userid'));
429
430         // ... and set it as currently handled user id
431         setCurrentUserId(getMemberId());
432
433         // Init user data array
434         initUserData();
435
436         // Fix "deleted" cookies
437         fixDeletedCookies(array('userid', 'u_hash'));
438
439         // Are cookies set and can the member data be loaded?
440         if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === TRUE)) {
441                 // Validate password by created the difference of it and the secret key
442                 $valPass = encodeHashForCookie(getUserData('password'));
443
444                 // So did we now have valid data and an unlocked user?
445                 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
446                         // Transfer last module and online time
447                         $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
448                         $GLOBALS['last_online']['online'] = getUserData('last_online');
449
450                         // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
451                         $ret = TRUE;
452                 } // END - if
453         } // END - if
454
455         // Is $ret still false?
456         if ($ret === FALSE) {
457                 // Yes, so destroy the session
458                 destroyMemberSession();
459         } // END - if
460
461         // Cache status
462         $GLOBALS[__FUNCTION__] = $ret;
463
464         // Return status
465         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
466         return $ret;
467 }
468
469 // Fetch user data for given user id
470 function fetchUserData ($value, $column = 'userid') {
471         // Extension ext-user must be there at any case
472         if (!isExtensionActive('user')) {
473                 // Absent ext-user is really not good
474                 return FALSE;
475         } elseif (is_null($value)) {
476                 // This shall never happen, so please report it
477                 reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
478         }
479
480         // If we should look for userid secure&set it here
481         if (substr($column, -2, 2) == 'id') {
482                 // Secure userid
483                 $value = bigintval($value);
484
485                 // Don't look for invalid userids...
486                 if (!isValidId($value)) {
487                         // Invalid, so abort here
488                         reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
489                 } // END - if
490
491                 // Unset cached values if found and different
492                 if ((isCurrentUserIdSet()) && (getCurrentUserId() != $value)) {
493                         // Unset it
494                         unsetCurrentUserId();
495                 } elseif (isUserDataValid()) {
496                         // Use cache, so it is fine
497                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
498                         return TRUE;
499                 } // END - if
500         } elseif (isUserDataValid()) {
501                 // Using cache is fine
502                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
503                 return TRUE;
504         }
505
506         // By default none was found
507         $found = FALSE;
508
509         // Extra SQL statements
510         $ADD = runFilterChain('convert_user_data_columns', ' ');
511
512         // Query for the user
513         $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
514                 array(
515                         $column,
516                         $value
517                 ), __FUNCTION__, __LINE__);
518
519         // Is there a record?
520         if (SQL_NUMROWS($result) == 1) {
521                 // Load data from cookies
522                 $data = SQL_FETCHARRAY($result);
523
524                 // Set the userid for later use
525                 setCurrentUserId($data['userid']);
526
527                 // And cache the data for this userid
528                 $GLOBALS['user_data'][getCurrentUserId()] = $data;
529
530                 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
531                 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
532                         // Backup the raw one and zero it
533                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
534                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
535
536                         // Is it not zero?
537                         if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
538                                 // Seperate data/time
539                                 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
540
541                                 // Seperate data and time again
542                                 $array['date'] = explode('-', $array[0]);
543                                 $array['time'] = explode(':', $array[1]);
544
545                                 // Now pass it to mktime()
546                                 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
547                                         $array['time'][0],
548                                         $array['time'][1],
549                                         $array['time'][2],
550                                         $array['date'][1],
551                                         $array['date'][2],
552                                         $array['date'][0]
553                                 );
554                         } // END - if
555                 } // END - if
556
557                 // Found, but valid?
558                 $found = isUserDataValid();
559         } // END - if
560
561         // Free memory
562         SQL_FREERESULT($result);
563
564         // Return result
565         return $found;
566 }
567
568 /*
569  * Checks whether the current session bears a valid admin id and password hash.
570  *
571  * This patched function will reduce many SELECT queries for the current admin
572  * login.
573  */
574 function isAdmin () {
575         // Is there cache?
576         if (isset($GLOBALS[__FUNCTION__])) {
577                 // Return it
578                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isAdmin()=' . intval($GLOBALS[__FUNCTION__]));
579                 return $GLOBALS[__FUNCTION__];
580         } // END - if
581
582         // No admin in installation phase!
583         if ((isInstallationPhase()) || (!isAdminRegistered())) {
584                 $GLOBALS[__FUNCTION__] = FALSE;
585                 return FALSE;
586         } // END - if
587
588         // Init variables
589         $ret = FALSE;
590         $adminId = '0';
591         $passwordFromCookie = '';
592         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
593
594         // If admin login is not given take current from cookies...
595         if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
596                 // Get admin login and password from session/cookies
597                 $adminId            = getCurrentAdminId();
598                 $passwordFromCookie = getAdminMd5();
599         } // END - if
600         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',passwordFromCookie=' . $passwordFromCookie);
601
602         // Abort if admin id is zero
603         if (($adminId == '0') || (empty($passwordFromCookie))) {
604                 // A very noisy debug message ...
605                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
606
607                 // Abort here now
608                 $GLOBALS[__FUNCTION__] = FALSE;
609                 return FALSE;
610         } // END - if
611
612         // Init it with failed
613         $GLOBALS[__FUNCTION__] = FALSE;
614
615         // Search in array for entry
616         if (isset($GLOBALS['admin_hash'])) {
617                 // Use cached string
618                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using admin_hash=' . $GLOBALS['admin_hash'] . ' from cache');
619         } elseif ((!empty($adminId)) && (!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === TRUE)) {
620                 // Get admin hash and hash it
621                 $GLOBALS['admin_hash'] = encodeHashForCookie(getAdminHash($adminId));
622                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valPass=' . $GLOBALS['admin_hash']);
623
624                 // Count cache hits
625                 incrementStatsEntry('cache_hits');
626         } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === FALSE))) {
627                 // Get admin hash and hash it
628                 $GLOBALS['admin_hash'] = encodeHashForCookie(getAdminHash($adminId));
629                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valPass=' . $GLOBALS['admin_hash']);
630         }
631
632         // Check if password is valid
633         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $GLOBALS['admin_hash'] . '==' . $passwordFromCookie . ')='.intval($GLOBALS['admin_hash'] == $passwordFromCookie));
634         $GLOBALS[__FUNCTION__] = ((!empty($GLOBALS['admin_hash'])) && ($GLOBALS['admin_hash'] == $passwordFromCookie));
635
636         // Return result of comparision
637         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isAdmin()=' . intval($GLOBALS[__FUNCTION__]));
638         return $GLOBALS[__FUNCTION__];
639 }
640
641 // Generates a list of "max receiveable emails per day"
642 function addMaxReceiveList ($mode, $default = '') {
643         $OUT = '';
644         $result = FALSE;
645
646         switch ($mode) {
647                 case 'guest':
648                         // Guests (in the registration form) are not allowed to select 0 mails per day.
649                         $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
650                         __FUNCTION__, __LINE__);
651                         break;
652
653                 case 'admin':
654                 case 'member':
655                         // Members are allowed to set to zero mails per day (we will change this soon!)
656                         $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
657                         __FUNCTION__, __LINE__);
658                         break;
659
660                 default: // Invalid!
661                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
662                         break;
663         }
664
665         // Some entries are found?
666         if (!SQL_HASZERONUMS($result)) {
667                 $OUT = '';
668                 while ($content = SQL_FETCHARRAY($result)) {
669                         $OUT .= '      <option value="' . $content['value'] . '"';
670
671                         if (postRequestElement('max_mails') == $content['value']) {
672                                 $OUT .= ' selected="selected"';
673                         } // END - if
674
675                         $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
676                         if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
677                         $OUT .= '</option>';
678                 }
679
680                 // Load template
681                 $OUT = loadTemplate(($mode . '_receive_table'), TRUE, $OUT);
682         } else {
683                 // Maybe the admin has to setup some maximum values?
684                 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
685         }
686
687         // Free result
688         SQL_FREERESULT($result);
689
690         // Return generated HTML code
691         return $OUT;
692 }
693
694 // Checks whether the given email address is used.
695 function isEmailTaken ($email) {
696         // Default is no userid
697         $useridSql = ' IS NOT NULL';
698
699         // Is a member logged in?
700         if (isMember()) {
701                 // Get userid
702                 $useridSql = '!= ' . bigintval(getMemberId());
703         } // END - if
704
705         // Replace dot with {DOT}
706         $email = str_replace('.', '{DOT}', $email);
707
708         // Query the database
709         $result = SQL_QUERY_ESC("SELECT
710         COUNT(`userid`) AS `cnt`
711 FROM
712         `{?_MYSQL_PREFIX?}_user_data`
713 WHERE
714         '%s' REGEXP `email` AND
715         `userid` %s
716 LIMIT 1",
717                 array(
718                         $email,
719                         $useridSql
720                 ), __FUNCTION__, __LINE__);
721
722         // Is the email there?
723         list($count) = SQL_FETCHROW($result);
724
725         // Free the result
726         SQL_FREERESULT($result);
727
728         // Return result
729         return ($count == 1);
730 }
731
732 // Validate the given menu action
733 function isMenuActionValid ($mode, $action, $what, $updateEntry = FALSE) {
734         // Is the cache entry there and we shall not update?
735         if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === FALSE)) {
736                 // Count cache hit
737                 incrementStatsEntry('cache_hits');
738
739                 // Then use this cache
740                 return $GLOBALS['action_valid'][$mode][$action][$what];
741         } // END - if
742
743         // By default nothing is valid
744         $ret = FALSE;
745
746         // Look in all menus or only unlocked
747         $add = '';
748         if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
749
750         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
751         if (($mode != 'admin') && ($updateEntry === TRUE)) {
752                 // Update guest or member menu
753                 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
754                         array(
755                                 $mode,
756                                 $action,
757                                 $what
758                         ), __FUNCTION__, __LINE__, FALSE);
759         } elseif (($what != 'welcome') && (!empty($what))) {
760                 // Other actions
761                 $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",
762                         array(
763                                 $mode,
764                                 $action,
765                                 $what
766                         ), __FUNCTION__, __LINE__, FALSE);
767         } else {
768                 // Admin login overview
769                 $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",
770                         array(
771                                 $mode,
772                                 $action
773                         ), __FUNCTION__, __LINE__, FALSE);
774         }
775
776         // Run SQL command
777         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
778
779         // Should we look for affected rows (only update) or found rows?
780         if ($updateEntry === TRUE) {
781                 // Check updated/affected rows
782                 $ret = (!SQL_HASZEROAFFECTED());
783         } else {
784                 // Check found rows
785                 $ret = (!SQL_HASZERONUMS($result));
786         }
787
788         // Free memory
789         SQL_FREERESULT($result);
790
791         // Set cache entry
792         $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
793
794         // Return result
795         return $ret;
796 }
797
798 // Get action value from mode (admin/guest/member) and what-value
799 function getActionFromModuleWhat ($module, $what) {
800         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
801         // Init status
802         $data['action'] = '';
803
804         if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
805                 // ext-sql_patches is missing so choose depending on mode
806                 $what = determineWhat($module);
807         } elseif ((empty($what)) && ($module != 'admin')) {
808                 // Use configured 'home'
809                 $what = getIndexHome();
810         } // END - if
811
812         if ($module == 'admin') {
813                 // Action value for admin area
814                 if (isGetRequestElementSet('action')) {
815                         // Use from request!
816                         return getRequestElement('action');
817                 } elseif (isActionSet()) {
818                         // Get it directly from URL
819                         return getAction();
820                 } elseif (($what == 'welcome') || (!isWhatSet())) {
821                         // Default value for admin area
822                         $data['action'] = 'login';
823                 }
824         } elseif (isActionSet()) {
825                 // Get it directly from URL
826                 return getAction();
827         }
828         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
829
830         // Does the module have a menu?
831         if (ifModuleHasMenu($module)) {
832                 // Rewriting modules to menu
833                 $module = mapModuleToTable($module);
834
835                 // Guest and member menu is 'main' as the default
836                 if (empty($data['action'])) {
837                         $data['action'] = 'main';
838                 } // END - if
839
840                 // Load from database
841                 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
842                         array(
843                                 $module,
844                                 $what
845                         ), __FUNCTION__, __LINE__);
846                 if (SQL_NUMROWS($result) == 1) {
847                         // Load action value and pray that this one is the right you want... ;-)
848                         $data = SQL_FETCHARRAY($result);
849                 } // END - if
850
851                 // Free memory
852                 SQL_FREERESULT($result);
853         } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
854                 // No ext-sql_patches installed, but maybe we need to register an admin?
855                 if (isAdminRegistered()) {
856                         // Redirect to admin area
857                         redirectToUrl('admin.php');
858                 } // END - if
859         }
860
861         // Return action value
862         return $data['action'];
863 }
864
865 // Get category name back
866 function getCategory ($cid) {
867         // Default is not found
868         $data['cat'] = '{--_CATEGORY_404--}';
869
870         // Is the category id set?
871         if (!isValidId($cid)) {
872                 // No category
873                 $data['cat'] = '{--_CATEGORY_NONE--}';
874         } elseif (isValidId($cid)) {
875                 // Lookup the category in database
876                 $result = SQL_QUERY_ESC('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
877                         array(bigintval($cid)), __FUNCTION__, __LINE__);
878                 if (SQL_NUMROWS($result) == 1) {
879                         // Category found... :-)
880                         $data = SQL_FETCHARRAY($result);
881                 } // END - if
882
883                 // Free result
884                 SQL_FREERESULT($result);
885         } // END - if
886
887         // Return result
888         return $data['cat'];
889 }
890
891 // Get a string of "mail title" and price back
892 function getPaymentTitlePrice ($paymentsId, $full = FALSE) {
893         // Only title or also including price?
894         if ($full === FALSE) {
895                 $ret = getPaymentData($paymentsId, 'main_title');
896         } else {
897                 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
898         }
899
900         // Return result
901         return $ret;
902 }
903
904 // Get payment price
905 function getPaymentPrice ($paymentsId) {
906         // Return result
907         return getPaymentData($paymentsId, 'price');
908 }
909
910 // Get payment time
911 function getPaymentTime ($paymentsId) {
912         // Return result
913         return getPaymentData($paymentsId, 'time');
914 }
915
916 // Get payment 'payment'
917 function getPaymentPayment ($paymentsId) {
918         // Return result
919         return getPaymentData($paymentsId, 'payment');
920 }
921
922 // "Getter" for payment data (cached)
923 function getPaymentData ($paymentsId, $lookFor) {
924         // Default value...
925         $data[$lookFor] = NULL;
926
927         // Is there cache?
928         if (isset($GLOBALS['cache_array']['payments'][$lookFor][$paymentsId])) {
929                 // Use it if found to save SQL queries
930                 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$paymentsId];
931
932                 // Update cache hits
933                 incrementStatsEntry('cache_hits');
934         } elseif (!isExtensionActive('cache')) {
935                 // Search for it in database
936                 $result = SQL_QUERY_ESC('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
937                         array(
938                                 $lookFor,
939                                 bigintval($paymentsId)
940                         ), __FUNCTION__, __LINE__);
941
942                 // Is the entry there?
943                 if (SQL_NUMROWS($result) == 1) {
944                         // Payment type found... :-)
945                         $data = SQL_FETCHARRAY($result);
946                 } // END - if
947
948                 // Free result
949                 SQL_FREERESULT($result);
950         }
951
952         // Return value
953         return $data[$lookFor];
954 }
955
956 // Remove a receiver's id from $receivers and add a link for him to confirm
957 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = FALSE) {
958         // Default is not removed
959         $ret = 'failed';
960
961         // Is the userid valid?
962         if (isValidId($userid)) {
963                 // Remove entry from array
964                 unset($receivers[$key]);
965
966                 // Is there already a line for this user available?
967                 if (isValidId($statsId)) {
968                         // Default is 'normal' mail
969                         $type = 'NORMAL';
970                         $rowName = 'stats_id';
971
972                         // Only when we got a real stats id continue searching for the entry
973                         if ($isBonusMail === TRUE) {
974                                 $type = 'BONUS';
975                                 $rowName = 'bonus_id';
976                         } // END - if
977
978                         // Try to look the entry up
979                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
980                                 array(
981                                         $rowName,
982                                         bigintval($statsId),
983                                         bigintval($userid),
984                                         $type
985                                 ), __FUNCTION__, __LINE__);
986
987                         // Was it *not* found?
988                         if (SQL_HASZERONUMS($result)) {
989                                 // So we add one!
990                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES (%s,%s,'%s')",
991                                         array(
992                                                 $rowName,
993                                                 bigintval($statsId),
994                                                 bigintval($userid),
995                                                 $type
996                                         ), __FUNCTION__, __LINE__);
997
998                                 // Update 'mails_sent' if ext-sql_patches is updated
999                                 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
1000                                         // Update the pool
1001                                         updatePoolDataById($poolId, 'mails_sent', 1, '+');
1002                                 } // END - if
1003                                 $ret = 'done';
1004                         } else {
1005                                 // Already found
1006                                 $ret = 'already';
1007                         }
1008
1009                         // Free memory
1010                         SQL_FREERESULT($result);
1011                 } // END - if
1012         } // END - if
1013
1014         // Return status for sending routine
1015         return $ret;
1016 }
1017
1018 // Calculate sum (default) or count records of given criteria
1019 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = FALSE, $add = '', $mode = '=') {
1020         // Debug message
1021         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
1022         if ((empty($search)) && (!is_null($search))) {
1023                 // Count or sum whole table?
1024                 if ($countRows === TRUE) {
1025                         // Count whole table
1026                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1027                         $result = SQL_QUERY_ESC('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1028                                 array(
1029                                         $lookFor,
1030                                         $tableName
1031                                 ), __FUNCTION__, __LINE__);
1032                 } else {
1033                         // Sum whole table
1034                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1035                         $result = SQL_QUERY_ESC('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1036                                 array(
1037                                         $lookFor,
1038                                         $tableName
1039                                 ), __FUNCTION__, __LINE__);
1040                 }
1041         } elseif (($countRows === TRUE) || ($lookFor == 'userid')) {
1042                 // Count rows
1043                 if (is_null($search)) {
1044                         // Fix mode
1045                         if ($mode == '=') {
1046                                 $mode = 'IS';
1047                         } elseif ($mode == '!=') {
1048                                 $mode = 'IS NOT';
1049                         }
1050
1051                         // Look for NULL/0
1052                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT-NULL!');
1053                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE (`%s` %s NULL OR `%s`=0)" . $add . ' LIMIT 1',
1054                                 array(
1055                                         $lookFor,
1056                                         $tableName,
1057                                         $whereStatement,
1058                                         $mode,
1059                                         $whereStatement
1060                                 ), __FUNCTION__, __LINE__);
1061                 } else {
1062                         // Regular entry
1063                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1064                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1065                                 array(
1066                                         $lookFor,
1067                                         $tableName,
1068                                         $whereStatement,
1069                                         $mode,
1070                                         $search
1071                                 ), __FUNCTION__, __LINE__);
1072                 }
1073         } else {
1074                 // Sum all rows
1075                 if (is_null($search)) {
1076                         // Fix mode
1077                         if ($mode == '=') {
1078                                 $mode = 'IS';
1079                         } elseif ($mode == '!=') {
1080                                 $mode = 'IS NOT';
1081                         }
1082
1083                         // Look for NULL/0
1084                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM-NULL!');
1085                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE (`%s` %s NULL OR `%s`=0)" . $add . ' LIMIT 1',
1086                                 array(
1087                                         $lookFor,
1088                                         $tableName,
1089                                         $whereStatement,
1090                                         $mode,
1091                                         $whereStatement
1092                                 ), __FUNCTION__, __LINE__);
1093                 } else {
1094                         // Regular entry
1095                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1096                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1097                                 array(
1098                                         $lookFor,
1099                                         $tableName,
1100                                         $whereStatement,
1101                                         $mode,
1102                                         $search
1103                                 ), __FUNCTION__, __LINE__);
1104                 }
1105         }
1106
1107         // Load row
1108         $data = SQL_FETCHARRAY($result);
1109
1110         // Free result
1111         SQL_FREERESULT($result);
1112
1113         // Fix empty values
1114         if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1115                 // Float number
1116                 $data['res'] = '0.00000';
1117         } elseif ('' . $data['res'] . '' == '') {
1118                 // Fix empty result
1119                 $data['res'] = '0';
1120         }
1121
1122         // Return value
1123         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1124         return $data['res'];
1125 }
1126
1127 /**
1128  * Sends out mail to all administrators. This function is no longer obsolete
1129  * because we need it when there is no ext-admins installed
1130  */
1131 function sendAdminEmails ($subject, $message, $isBugReport = FALSE) {
1132         // Default is no special header
1133         $mailHeader = '';
1134
1135         // Is it a bug report?
1136         if ($isBugReport === TRUE) {
1137                 // Then add a reply-to line back to the author (me)
1138                 $mailHeader = 'Reply-To: webmaster@mxchange.org' . PHP_EOL;
1139         } // END - if
1140
1141         // Load all admin email addresses
1142         $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1143
1144         // And send the notification to all of them
1145         while ($content = SQL_FETCHARRAY($result)) {
1146                 // Send the email out
1147                 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1148         } // END - if
1149
1150         // Free result
1151         SQL_FREERESULT($result);
1152
1153         // Really simple... ;-)
1154 }
1155
1156 // Get id number from administrator's login name
1157 function getAdminId ($adminLogin) {
1158         // By default no admin is found
1159         $data['id'] = -1;
1160
1161         // Check cache
1162         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1163                 // Use it if found to save SQL queries
1164                 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1165
1166                 // Update cache hits
1167                 incrementStatsEntry('cache_hits');
1168         } elseif (!isExtensionActive('cache')) {
1169                 // Load from database
1170                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1171                         array($adminLogin), __FUNCTION__, __LINE__);
1172
1173                 // Is there an entry?
1174                 if (SQL_NUMROWS($result) == 1) {
1175                         // Get it
1176                         $data = SQL_FETCHARRAY($result);
1177                 } // END - if
1178
1179                 // Free result
1180                 SQL_FREERESULT($result);
1181         }
1182
1183         // Return the id
1184         return $data['id'];
1185 }
1186
1187 // "Getter" for current admin id
1188 function getCurrentAdminId () {
1189         // Log debug message
1190         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1191
1192         // Is there cache?
1193         if (!isset($GLOBALS['current_admin_id'])) {
1194                 // Get the admin login from session
1195                 $adminId = getSession('admin_id');
1196
1197                 // Remember in cache securely
1198                 setCurrentAdminId(bigintval($adminId));
1199         } // END - if
1200
1201         // Return it
1202         return $GLOBALS['current_admin_id'];
1203 }
1204
1205 // Setter for current admin id
1206 function setCurrentAdminId ($currentAdminId) {
1207         // Set it secured
1208         $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1209 }
1210
1211 // Get password hash from administrator's login name
1212 function getAdminHash ($adminId) {
1213         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ' - ENTERED!');
1214         // By default an invalid hash is returned
1215         $data['password'] = -1;
1216
1217         // Is admin hash set?
1218         if (isAdminHashSet($adminId)) {
1219                 // Check cache
1220                 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1221
1222                 // Update cache hits
1223                 incrementStatsEntry('cache_hits');
1224         } elseif (!isExtensionActive('cache')) {
1225                 // Load from database
1226                 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1227                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1228
1229                 // Is there an entry?
1230                 if (SQL_NUMROWS($result) == 1) {
1231                         // Fetch data
1232                         $data = SQL_FETCHARRAY($result);
1233
1234                         // Set cache
1235                         setAdminHash($adminId, $data['password']);
1236                 } // END - if
1237
1238                 // Free result
1239                 SQL_FREERESULT($result);
1240         }
1241
1242         // Return password hash
1243         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',data[password]=' . $data['password'] . ' - EXIT!');
1244         return $data['password'];
1245 }
1246
1247 // "Getter" for admin login
1248 function getAdminLogin ($adminId) {
1249         // By default a non-existent login is returned (other functions react on this!)
1250         $data['login'] = '***';
1251
1252         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1253                 // Get cache
1254                 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1255
1256                 // Update cache hits
1257                 incrementStatsEntry('cache_hits');
1258         } elseif (!isExtensionActive('cache')) {
1259                 // Load from database
1260                 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1261                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1262
1263                 // Entry found?
1264                 if (SQL_NUMROWS($result) == 1) {
1265                         // Fetch data
1266                         $data = SQL_FETCHARRAY($result);
1267
1268                         // Set cache
1269                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1270                 } // END - if
1271
1272                 // Free memory
1273                 SQL_FREERESULT($result);
1274         }
1275
1276         // Return the result
1277         return $data['login'];
1278 }
1279
1280 // Get email address of admin id
1281 function getAdminEmail ($adminId) {
1282         // By default an invalid emails is returned
1283         $data['email'] = '***';
1284
1285         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1286                 // Get cache
1287                 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1288
1289                 // Update cache hits
1290                 incrementStatsEntry('cache_hits');
1291         } elseif (!isExtensionActive('cache')) {
1292                 // Load from database
1293                 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1294                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1295
1296                 // Entry found?
1297                 if (SQL_NUMROWS($result_admin_id) == 1) {
1298                         // Get data
1299                         $data = SQL_FETCHARRAY($result_admin_id);
1300
1301                         // Set cache
1302                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1303                 } // END - if
1304
1305                 // Free result
1306                 SQL_FREERESULT($result_admin_id);
1307         }
1308
1309         // Return email
1310         return $data['email'];
1311 }
1312
1313 // Get default ACL of admin id
1314 function getAdminDefaultAcl ($adminId) {
1315         // By default an invalid ACL value is returned
1316         $data['default_acl'] = 'NO-ACL';
1317
1318         // Is ext-sql_patches there and was it found in cache?
1319         if (!isExtensionActive('sql_patches')) {
1320                 // Not found, which is bad, so we need to allow all
1321                 $data['default_acl'] = 'allow';
1322         } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1323                 // Use cache
1324                 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1325
1326                 // Update cache hits
1327                 incrementStatsEntry('cache_hits');
1328         } elseif (!isExtensionActive('cache')) {
1329                 // Load from database
1330                 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1331                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1332
1333                 // Is there an entry?
1334                 if (SQL_NUMROWS($result_admin_id) == 1) {
1335                         // Fetch data
1336                         $data = SQL_FETCHARRAY($result_admin_id);
1337
1338                         // Set cache
1339                         $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1340                 }
1341
1342                 // Free result
1343                 SQL_FREERESULT($result_admin_id);
1344         }
1345
1346         // Return default ACL
1347         return $data['default_acl'];
1348 }
1349
1350 // Get menu mode (la_mode) of admin id
1351 function getAdminMenuMode ($adminId) {
1352         // By default an invalid mode
1353         $data['la_mode'] = 'INVALID';
1354
1355         // Is ext-sql_patches there and was it found in cache?
1356         if (!isExtensionActive('sql_patches')) {
1357                 // Not found, which is bad, so we need to allow all
1358                 $data['la_mode'] = 'global';
1359         } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1360                 // Use cache
1361                 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1362
1363                 // Update cache hits
1364                 incrementStatsEntry('cache_hits');
1365         } elseif (!isExtensionActive('cache')) {
1366                 // Load from database
1367                 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1368                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1369
1370                 // Is there an entry?
1371                 if (SQL_NUMROWS($result_admin_id) == 1) {
1372                         // Fetch data
1373                         $data = SQL_FETCHARRAY($result_admin_id);
1374
1375                         // Set cache
1376                         $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1377                 }
1378
1379                 // Free result
1380                 SQL_FREERESULT($result_admin_id);
1381         }
1382
1383         // Return default ACL
1384         return $data['la_mode'];
1385 }
1386
1387 // Generates an option list from various parameters
1388 function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '') {
1389         $ret = '';
1390         if ($table == '/ARRAY/') {
1391                 // Selection from array
1392                 if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
1393                         // Both are arrays
1394                         foreach ($key as $idx => $optionValue) {
1395                                 $ret .= '<option value="' . $optionValue . '"';
1396                                 if ($default == $optionValue) {
1397                                         // Selected by default
1398                                         $ret .= ' selected="selected"';
1399                                 } elseif (isset($disabled[$optionValue])) {
1400                                         // Disabled!
1401                                         $ret .= ' disabled="disabled"';
1402                                 }
1403
1404                                 // Is the call-back function set?
1405                                 if (!empty($callback)) {
1406                                         // Call it
1407                                         $value[$idx] = call_user_func_array($callback, array($key[$idx]));
1408                                 } // END - if
1409
1410                                 // Finish option tag
1411                                 $ret .= '>' . $value[$idx] . '</option>';
1412                         } // END - foreach
1413                 } else {
1414                         // Problem in request
1415                         reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: key[' . count($key) . ']=' . gettype($key) . ',value[' . count($value) . ']=' . gettype($value) . ',callback=' . $callback);
1416                 }
1417         } else {
1418             ///////////////////////
1419                 // Data from database /
1420                 ///////////////////////
1421
1422                 // Init extra column (if requested)
1423                 $extraColumn = '';
1424                 if (!empty($extra)) {
1425                         $extraColumn = ',`' . $extra . '` AS `extra`';
1426                 } // END - if
1427
1428                 // Run SQL query
1429                 $result = SQL_QUERY_ESC("SELECT `%s` AS `key`, `%s` AS `value`" . $extraColumn . " FROM `{?_MYSQL_PREFIX?}_%s` " . $whereStatement . " ORDER BY `%s` ASC",
1430                         array(
1431                                 $key,
1432                                 $value,
1433                                 $table,
1434                                 $value
1435                         ), __FUNCTION__, __LINE__);
1436
1437                 // Is there rows?
1438                 if (!SQL_HASZERONUMS($result)) {
1439                         // Found data so add them as OPTION lines
1440                         while ($content = SQL_FETCHARRAY($result)) {
1441                                 // Is extra set?
1442                                 if (!isset($content['extra'])) {
1443                                         // Set it to empty
1444                                         $content['extra'] = '';
1445                                 } // END - if
1446
1447                                 $ret .= '<option value="' . $content['key'] . '"';
1448
1449                                 if ($default == $content['key']) {
1450                                         // Selected by default
1451                                         $ret .= ' selected="selected"';
1452                                 } elseif (isset($disabled[$content['key']])) {
1453                                         // Disabled!
1454                                         $ret .= ' disabled="disabled"';
1455                                 }
1456
1457                                 // Add it, if set
1458                                 if (!empty($content['extra'])) {
1459                                         $content['extra'] = ' (' . $content['extra'] . ')';
1460                                 } // END - if
1461
1462                                 // Is the call-back function set?
1463                                 if (!empty($callback)) {
1464                                         // Call it
1465                                         $content['value'] = call_user_func_array($callback, array($content['value']));
1466                                 } // END - if
1467
1468                                 // Finish option list
1469                                 $ret .= '>' . $content['value'] . $content['extra'] . '</option>';
1470                         } // END - while
1471                 } else {
1472                         // No data found
1473                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1474                 }
1475
1476                 // Free memory
1477                 SQL_FREERESULT($result);
1478         }
1479
1480         // Return - hopefully - the requested data
1481         return $ret;
1482 }
1483
1484 // Deletes a user account with given reason
1485 function deleteUserAccount ($userid, $reason) {
1486         // Init points
1487         $data['points'] = '0';
1488
1489         // Search for the points and user data
1490         $result = SQL_QUERY_ESC("SELECT
1491         (SUM(`p`.`points`) - `d`.`used_points`) AS `points`
1492 FROM
1493         `{?_MYSQL_PREFIX?}_user_points` AS `p`
1494 LEFT JOIN
1495         `{?_MYSQL_PREFIX?}_user_data` AS `d`
1496 ON
1497         `p`.`userid`=`d`.`userid`
1498 WHERE
1499         `p`.`userid`=%s
1500 LIMIT 1",
1501                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1502
1503         // Is there an entry?
1504         if (SQL_NUMROWS($result) == 1) {
1505                 // Save his points to add them to the jackpot
1506                 $data = SQL_FETCHARRAY($result);
1507
1508                 // Delete points entries as well
1509                 // @TODO Rewrite these lines to a filter
1510                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1511                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1512
1513                 // Update mediadata as well
1514                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1515                         // Update database
1516                         updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1517                 } // END - if
1518
1519                 // Now, when we have all his points adds them do the jackpot!
1520                 if (isExtensionActive('jackpot')) {
1521                         addPointsToJackpot($data['points']);
1522                 } // END - if
1523         } // END - if
1524
1525         // Free the result
1526         SQL_FREERESULT($result);
1527
1528         // Delete category selections as well...
1529         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1530                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1531
1532         // Remove from rallye if found
1533         // @TODO Rewrite this to a filter
1534         if (isExtensionActive('rallye')) {
1535                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1536                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1537         } // END - if
1538
1539         // Add reason and translate points
1540         $data['text'] = $reason;
1541
1542         // Now a mail to the user and that's all...
1543         $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1544         sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1545
1546         // Ok, delete the account!
1547         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1548 }
1549
1550 // Gets the matching what name from module
1551 function getWhatFromModule ($modCheck) {
1552         // Is the request element set?
1553         if (isGetRequestElementSet('what')) {
1554                 // Then return this!
1555                 return getRequestElement('what');
1556         } // END - if
1557
1558         // Default is empty
1559         $what = '';
1560
1561         // Check on given module
1562         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1563         switch ($modCheck) {
1564                 case 'index': // Guest area
1565                         // Is ext-sql_patches installed and newer than 0.0.5?
1566                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1567                                 // Use it from config
1568                                 $what = getIndexHome();
1569                         } else {
1570                                 // Use default 'welcome'
1571                                 $what = 'welcome';
1572                         }
1573                         break;
1574
1575                 default: // Default for all other menus (getIndexHome() is for index module only)
1576                         $what = 'welcome';
1577                         break;
1578         } // END - switch
1579
1580         // Return what value
1581         return $what;
1582 }
1583
1584 // Returns HTML code with an option list of all categories
1585 function generateCategoryOptionsList ($mode, $userid = NULL) {
1586         // Prepare WHERE statement
1587         $whereStatement = " WHERE `visible`='Y'";
1588         if (isAdmin()) $whereStatement = '';
1589
1590         // Initialize array...
1591         $categories = array(
1592                 'id'      => array(),
1593                 'name'    => array(),
1594                 'userids' => array()
1595         );
1596
1597         // Get categories
1598         $result = SQL_QUERY('SELECT
1599         `id`,
1600         `cat`
1601 FROM
1602         `{?_MYSQL_PREFIX?}_cats`
1603 ' . $whereStatement . '
1604 ORDER BY
1605         `sort` ASC',
1606                 __FUNCTION__, __LINE__);
1607
1608         // Are there entries?
1609         if (!SQL_HASZERONUMS($result)) {
1610                 // ... and begin loading stuff
1611                 while ($content = SQL_FETCHARRAY($result)) {
1612                         // Transfer some data
1613                         $categories['id'][]   = $content['id'];
1614                         array_push($categories['name'], $content['cat']);
1615
1616                         // Check which users are in this category
1617                         $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1618                                 array(
1619                                         bigintval($content['id']),
1620                                         convertNullToZero($userid)
1621                                 ), __FUNCTION__, __LINE__);
1622
1623                         // Init count
1624                         $userid_cnt = '0';
1625
1626                         // Start adding all
1627                         while ($data = SQL_FETCHARRAY($result_userids)) {
1628                                 // Add user count
1629                                 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', TRUE, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1630                         } // END - while
1631
1632                         // Free memory
1633                         SQL_FREERESULT($result_userids);
1634
1635                         // Add counter
1636                         array_push($categories['userids'], $userid_cnt);
1637                 } // END - while
1638
1639                 // Free memory
1640                 SQL_FREERESULT($result);
1641
1642                 // Generate options
1643                 $OUT = '';
1644                 foreach ($categories['id'] as $key => $value) {
1645                         $OUT .= '      <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1646                 } // END - foreach
1647         } else {
1648                 // No cateogries are defined yet
1649                 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1650         }
1651
1652         // Return HTML code
1653         return $OUT;
1654 }
1655
1656 // Add bonus mail to queue
1657 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1658         // Is admin or bonus extension there?
1659         if (!isAdmin()) {
1660                 // Abort here
1661                 return FALSE;
1662         } elseif (!isExtensionActive('bonus')) {
1663                 // Abort here
1664                 return FALSE;
1665         }
1666
1667         // Calculcate target sent
1668         $target = countSelection(explode(';', $receiverList));
1669
1670         // Receiver is zero?
1671         if ($receiver == '0') {
1672                 // Then auto-fix it
1673                 $receiver = $target;
1674         } // END - if
1675
1676         // HTML extension active?
1677         if (isExtensionActive('html_mail')) {
1678                 // Add HTML mail
1679                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1680         `subject`,
1681         `text`,
1682         `receivers`,
1683         `points`,
1684         `time`,
1685         `data_type`,
1686         `timestamp`,
1687         `url`,
1688         `cat_id`,
1689         `target_send`,
1690         `mails_sent`,
1691         `html_msg`
1692 ) VALUES (
1693         '%s',
1694         '%s',
1695         '%s',
1696         %s,
1697         %s,
1698         'NEW',
1699         UNIX_TIMESTAMP(),
1700         '%s',
1701         %s,
1702         %s,
1703         %s,
1704         '%s'
1705 )",
1706                 array(
1707                         $subject,
1708                         $text,
1709                         $receiverList,
1710                         $points,
1711                         bigintval($seconds),
1712                         $url,
1713                         bigintval($categoryId),
1714                         $target,
1715                         bigintval($receiver),
1716                         convertBooleanToYesNo($mode == 'html')
1717                 ), __FUNCTION__, __LINE__);
1718         } else {
1719                 // Add regular mail
1720                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1721         `subject`,
1722         `text`,
1723         `receivers`,
1724         `points`,
1725         `time`,
1726         `data_type`,
1727         `timestamp`,
1728         `url`,
1729         `cat_id`,
1730         `target_send`,
1731         `mails_sent`
1732 ) VALUES (
1733         '%s',
1734         '%s',
1735         '%s',
1736         %s,
1737         %s,
1738         'NEW',
1739         UNIX_TIMESTAMP(),
1740         '%s',
1741         %s,
1742         %s,
1743         %s
1744 )",
1745                 array(
1746                         $subject,
1747                         $text,
1748                         $receiverList,
1749                         $points,
1750                         bigintval($seconds),
1751                         $url,
1752                         bigintval($categoryId),
1753                         $target,
1754                         bigintval($receiver),
1755                 ), __FUNCTION__, __LINE__);
1756         }
1757 }
1758
1759 // Generate a receiver list for given category and maximum receivers
1760 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1761         // Init variables
1762         $extraColumns = '';
1763         $receiverList = '';
1764         $result       = FALSE;
1765
1766         // Secure data
1767         $categoryId = bigintval($categoryId);
1768         $receiver   = bigintval($receiver);
1769
1770         // Is the receiver zero and mode set?
1771         if (($receiver == '0') && (!empty($mode))) {
1772                 // Auto-fix receiver maximum
1773                 $receiver = getTotalReceivers($mode);
1774         } // END - if
1775
1776         // Exclude (maybe exclude) testers
1777         $addWhere = runFilterChain('user_exclusion_sql', ' ');
1778
1779         // Category given?
1780         if (isValidId($categoryId)) {
1781                 // Select category
1782                 $extraColumns  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS `c` ON `d`.`userid`=`c`.`userid`";
1783                 $addWhere = sprintf(" AND `c`.`cat_id`=%s", $categoryId);
1784         } // END - if
1785
1786         // Exclude users in holiday?
1787         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1788                 // Add something for the holiday extension
1789                 $addWhere .= " AND `d`.`holiday_active`='N'";
1790         } // END - if
1791
1792         // Include only HTML recipients?
1793         if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1794                 $addWhere .= " AND `d`.`html`='Y'";
1795         } // END - if
1796
1797         // Run query
1798         $result = SQL_QUERY_ESC("SELECT
1799         `d`.`userid`
1800 FROM
1801         `{?_MYSQL_PREFIX?}_user_data` AS `d`
1802         " . $extraColumns . "
1803 WHERE
1804         `d`.`status`='CONFIRMED'
1805         " . $addWhere . "
1806 ORDER BY
1807         `d`.`{?order_select?}` {?order_mode?}
1808 LIMIT %s",
1809                 array(
1810                         $receiver
1811                 ), __FUNCTION__, __LINE__);
1812
1813         // Entries found?
1814         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1815                 // Load all entries
1816                 while ($content = SQL_FETCHARRAY($result)) {
1817                         // Add receiver when not empty
1818                         if (!empty($content['userid'])) {
1819                                 $receiverList .= $content['userid'] . ';';
1820                         } // END - if
1821                 } // END - while
1822
1823                 // Free memory
1824                 SQL_FREERESULT($result);
1825
1826                 // Remove trailing semicolon
1827                 $receiverList = substr($receiverList, 0, -1);
1828         } // END - if
1829
1830         // Return list
1831         return $receiverList;
1832 }
1833
1834 // Recuce the amount of received emails for the receipients for given email
1835 function reduceRecipientReceivedMails ($column, $id, $count) {
1836         // Search for mail in database
1837         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1838                 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1839
1840         // Are there entries?
1841         if (!SQL_HASZERONUMS($result)) {
1842                 // Now load all userids for one big query!
1843                 $userids = array();
1844                 while ($data = SQL_FETCHARRAY($result)) {
1845                         // By default reduce and found no emails
1846                         $num = 0;
1847
1848                         // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1849                         // @TODO Rewrite this to a filter
1850                         if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1851                                 // User email
1852                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1853                         } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1854                                 // Bonus mail
1855                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1856                         }
1857
1858                         // Reduce this users total received emails?
1859                         if ($num === 0) {
1860                                 $userids[$data['userid']] = $data['userid'];
1861                         } // END - if
1862                 } // END - while
1863
1864                 if (count($userids) > 0) {
1865                         // Now update all user accounts
1866                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1867                                 array(
1868                                         implode(',', $userids),
1869                                         count($userids)
1870                                 ), __FUNCTION__, __LINE__);
1871                 } else {
1872                         // Nothing deleted
1873                         displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1874                 }
1875         } // END - if
1876
1877         // Free result
1878         SQL_FREERESULT($result);
1879 }
1880
1881 // Creates a new task
1882 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = TRUE) {
1883         // Insert the task data into the database
1884         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())",
1885                 array(
1886                         convertZeroToNull($adminId),
1887                         convertZeroToNull($userid),
1888                         $taskType,
1889                         $subject,
1890                         $notes
1891                 ), __FUNCTION__, __LINE__, TRUE, $strip);
1892
1893         // Return insert id which is the task id
1894         return SQL_INSERTID();
1895 }
1896
1897 // Updates last module / online time
1898 function updateLastActivity ($userid) {
1899         // Is 'what' set?
1900         if (isWhatSet()) {
1901                 // Run the update query
1902                 SQL_QUERY_ESC("UPDATE
1903         `{?_MYSQL_PREFIX?}_user_data`
1904 SET
1905         `{%%pipe,getUserLastWhatName%%}`='{%%pipe,getWhat%%}',
1906         `last_online`=UNIX_TIMESTAMP(),
1907         `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1908 WHERE
1909         `userid`=%s
1910 LIMIT 1",
1911                 array(
1912                         bigintval($userid)
1913                 ), __FUNCTION__, __LINE__);
1914         } else {
1915                 // No what set, needs to be ignored (last_module is last_what)
1916                 SQL_QUERY_ESC("UPDATE
1917         `{?_MYSQL_PREFIX?}_user_data`
1918 SET
1919         `{%%pipe,getUserLastWhatName%%}`=NULL,
1920         `last_online`=UNIX_TIMESTAMP(),
1921         `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1922 WHERE
1923         `userid`=%s
1924 LIMIT 1",
1925                 array(
1926                         bigintval($userid)
1927                 ), __FUNCTION__, __LINE__);
1928         }
1929 }
1930
1931 // List all given joined rows (callback function from XML)
1932 function doGenericJoinedListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1933         // Verify that tableName and columns are not empty
1934         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1935                 // No tableName specified
1936                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1937         } elseif (count($columns) == 0) {
1938                 // No columns specified
1939                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1940         }
1941
1942         // This is the minimum query, so at least columns and tableName must have entries
1943         $sql = 'SELECT ';
1944
1945         // Get the sql part back from given array
1946         $sql .= getSqlPartFromXmlArray($columns);
1947
1948         // Add "FROM"
1949         $sql .= getSqlXmlFromTable($tableName);
1950
1951         // Add "JOIN"
1952         $sql .= getSqlXmlJoinedTable($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable);
1953
1954         // Add "WHERE"
1955         $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
1956
1957         // Add "ORDER BY"
1958         $sql .= getSqlXmlOrderBy($orderByColumns);
1959
1960         // Now handle all over to the inner function which will execute the listing
1961         doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
1962 }
1963
1964 // List all given rows (callback function from XML)
1965 function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1966         // Verify that tableName and columns are not empty
1967         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1968                 // No tableName specified
1969                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1970         } elseif (count($columns) == 0) {
1971                 // No columns specified
1972                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1973         }
1974
1975         // This is the minimum query, so at least columns and tableName must have entries
1976         $sql = 'SELECT ';
1977
1978         // Get the sql part back from given array
1979         $sql .= getSqlPartFromXmlArray($columns);
1980
1981         // Add "FROM"
1982         $sql .= getSqlXmlFromTable($tableName);
1983
1984         // Add "WHERE"
1985         $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
1986
1987         // Add "ORDER BY"
1988         $sql .= getSqlXmlOrderBy($orderByColumns);
1989
1990         // Now handle all over to the inner function which will execute the listing
1991         doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
1992 }
1993
1994 // Do the listing of entries
1995 function doListEntries ($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array(), $content = array()) {
1996         // Run the SQL query
1997         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
1998
1999         // Are there some URLs left?
2000         if (!SQL_HASZERONUMS($result)) {
2001                 // List all URLs
2002                 $OUT = '';
2003                 while ($row = SQL_FETCHARRAY($result)) {
2004                         // "Translate" content
2005                         foreach ($callbackColumns as $columnName => $callbackName) {
2006                                 // Fill the callback arguments
2007                                 $args = array($row[$columnName]);
2008
2009                                 // Is there more to add?
2010                                 if (isset($extraParameters[$columnName])) {
2011                                         // Add them as well
2012                                         $args = merge_array($args, $extraParameters[$columnName]);
2013                                 } // END - if
2014
2015                                 // Call the callback-function
2016                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, TRUE).'</pre>');
2017                                 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
2018                                 $row[$columnName] = call_user_func_array($callbackName, $args);
2019                         } // END - foreach
2020
2021                         // Load row template
2022                         $OUT .= loadTemplate(trim($rowTemplate[0]), TRUE, $row);
2023                 } // END - while
2024
2025                 // Is at least one entry set in content?
2026                 if ((is_array($content)) && (count($content) > 0)) {
2027                         // Then add generic 'rows' element
2028                         $content['rows'] = $OUT;
2029                 } else {
2030                         // Direct output is content
2031                         $content = $OUT;
2032                 }
2033
2034                 // Load main template
2035                 loadTemplate(trim($tableTemplate[0]), FALSE, $content);
2036         } else {
2037                 // No URLs in surfbar
2038                 displayMessage('{--' .$noEntryMessageId[0] . '--}');
2039         }
2040
2041         // Free result
2042         SQL_FREERESULT($result);
2043 }
2044
2045 // Adds a given entry to the database
2046 function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2047         //* DEBUG: */ die(__FUNCTION__.':columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,timeColumns=<pre>'.print_r($timeColumns,TRUE).'</pre>,columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>,POST=<pre>'.print_r($_POST,TRUE).'</pre>');
2048         // Verify that tableName and columns are not empty
2049         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2050                 // No tableName specified
2051                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2052         } elseif (count($columns) == 0) {
2053                 // No columns specified
2054                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
2055         }
2056
2057         // Init columns and value elements
2058         $sqlColumns = array();
2059         $sqlValues  = array();
2060
2061         // Default is that all went fine
2062         $GLOBALS['__XML_PARSE_RESULT'] = TRUE;
2063
2064         // Is there "time columns"?
2065         if (count($timeColumns) > 0) {
2066                 // Then "walk" through all entries
2067                 foreach ($timeColumns as $column) {
2068                         // Convert all (possible) selections
2069                         convertSelectionsToEpocheTimeInPostData($column . '_ye');
2070                 } // END - foreach
2071         } // END - if
2072
2073         // Add columns and values
2074         foreach ($columns as $key => $columnName) {
2075                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
2076                 // Is columnIndex set?
2077                 if (!is_null($columnIndex)) {
2078                         // Check conditions
2079                         //* DEBUG: */ die('columnName=<pre>'.print_r($columnName,TRUE).'</pre>columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>'.debug_get_printable_backtrace());
2080                         assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
2081
2082                         // Then use that index "blindly"
2083                         $columnName = $columnName[$columnIndex];
2084                 } // END - if
2085
2086                 // Debug message
2087                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName[' . gettype($columnName) . ']=' . $columnName . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . intval(isset($extraValues[$key])) . ',extraValuesName=' . intval(isset($extraValues[$columnName . '_list'])));
2088
2089                 // Copy entry securely to the final arrays
2090                 $sqlColumns[$key] = SQL_ESCAPE($columnName);
2091                 $sqlValues[$key]  = SQL_ESCAPE(postRequestElement($columnName));
2092
2093                 // Search for it
2094                 $search = key(search_array($columns, 'column', $columnName));
2095
2096                 // Try to handle call-back functions and/or extra values on the list
2097                 //* DEBUG: */ outputHtml($key . '/' . $columnName . '=<pre>'.print_r($columns,true).'</pre>search_array()=<pre>'.print_r(search_array($columns, 'column', $columnName), TRUE).'</pre>');
2098                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
2099                 if (is_string($key)) {
2100                         // Key is a string
2101                         $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key . '_list', $sqlValues[$key], array(''), $search);
2102                 } else {
2103                         // Is a number
2104                         $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key, $sqlValues[$key], array(''), $search);
2105                 }
2106
2107                 // Is the value not a number?
2108                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
2109                 if (($sqlValues[$key] != 'NULL') && (is_string($sqlValues[$key]))) {
2110                         // Add quotes around it
2111                         $sqlValues[$key] = chr(39) . $sqlValues[$key] . chr(39);
2112                 } // END - if
2113
2114                 // Is the value false?
2115                 if ($sqlValues[$key] === FALSE) {
2116                         // One "parser" didn't like it
2117                         $GLOBALS['__XML_PARSE_RESULT'] = FALSE;
2118                         break;
2119                 } // END - if
2120         } // END - foreach
2121
2122         // If all values are okay, continue
2123         if ($sqlValues[$key] !== FALSE) {
2124                 // Build the SQL query
2125                 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`, `', $sqlColumns) . "`) VALUES (" . implode(',', $sqlValues) . ')';
2126
2127                 // Run the SQL query
2128                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2129
2130                 // Add id number
2131                 setPostRequestElement('id', SQL_INSERTID());
2132
2133                 // Prepare filter data array
2134                 $filterData = array(
2135                         'mode'          => 'add',
2136                         'table_name'    => $tableName,
2137                         'content'       => postRequestArray(),
2138                         'id'            => SQL_INSERTID(),
2139                         'subject'       => '',
2140                         // @TODO Used generic 'userid' here
2141                         'userid_column' => array('userid'),
2142                         'raw_userid'    => array('userid'),
2143                         'affected'      => SQL_AFFECTEDROWS(),
2144                         'sql'           => $sql,
2145                 );
2146
2147                 // Send "build mail" out
2148                 runFilterChain('send_build_mail', $filterData);
2149         } // END - if
2150 }
2151
2152 // Edit rows by given id numbers
2153 function doGenericEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $subject = '') {
2154         // Is there "time columns"?
2155         if (count($timeColumns) > 0) {
2156                 // Then "walk" through all entries
2157                 foreach ($timeColumns as $column) {
2158                         // Convert all (possible) selections
2159                         convertSelectionsToEpocheTimeInPostData($column . '_ye');
2160                 } // END - foreach
2161         } // END - if
2162
2163         // Change them all
2164         $affected = '0';
2165         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2166                 // Secure id number
2167                 $id = bigintval($id);
2168
2169                 // Prepare content array (new values)
2170                 $content = array();
2171
2172                 // Prepare SQL for this row
2173                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
2174                         SQL_ESCAPE($tableName[0])
2175                 );
2176
2177                 // "Walk" through all entries
2178                 foreach (postRequestArray() as $key => $entries) {
2179                         // Skip raw userid which is always invalid
2180                         if (($key == $rawUserId[0]) || ($key == ($rawUserId[0] . '_raw')) || ($key == 'do_edit')) {
2181                                 // Continue with next field
2182                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
2183                                 continue;
2184                         } // END - if
2185
2186                         // Debug message
2187                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',id=' . $id . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,TRUE).'</pre>');
2188
2189                         // Is entries an array?
2190                         if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
2191                                 // Search for the right array index
2192                                 $search = key(search_array($columns, 'column', $key));
2193
2194                                 // Add this entry to content
2195                                 $content[$key] = $entries[$id];
2196
2197                                 // Debug message
2198                                 //* BUG: */ die($key.'/'.$id.'/'.$search.'=<pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre>');
2199
2200                                 // Handle possible call-back functions and/or extra values
2201                                 $entries[$id] = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries[$id], $userIdColumn, $search);
2202
2203                                 // Add key/value pair to SQL string
2204                                 $sql .= addKeyValueSql($key, $entries[$id]);
2205                         } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
2206                                 // Search for it
2207                                 $search = key(search_array($columns, 'column', $key));
2208                                 //* BUG: */ die($key.'/<pre>'.print_r($search, TRUE).'</pre>=<pre>'.print_r($columns, TRUE).'</pre>');
2209
2210                                 // Debug message
2211                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - BEFORE!');
2212
2213                                 // Add normal entries as well
2214                                 $content[$key] = $entries;
2215
2216                                 // Handle possible call-back functions and/or extra values
2217                                 $entries = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search);
2218
2219                                 // Debug message
2220                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - AFTER!');
2221
2222                                 // Add key/value pair to SQL string
2223                                 $sql .= addKeyValueSql($key, $entries);
2224                         }
2225                 } // END - foreach
2226
2227                 // Finish SQL command
2228                 $sql = substr($sql, 0, -1) . " WHERE `" . SQL_ESCAPE($idColumn[0]) . "`=" . $id;
2229                 if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2230                         // Add user id as well
2231                         $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2232                 } // END - if
2233                 $sql .= " LIMIT 1";
2234
2235                 // Run this query
2236                 //* BUG: */ die($sql.'<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
2237                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2238
2239                 // Add affected rows
2240                 $edited = SQL_AFFECTEDROWS();
2241                 $affected += $edited;
2242
2243                 // Load all data from that id
2244                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2245                         array(
2246                                 $tableName[0],
2247                                 $idColumn[0],
2248                                 $id
2249                         ), __FUNCTION__, __LINE__);
2250
2251                 // Fetch the data and merge it into $content
2252                 $content = merge_array($content, SQL_FETCHARRAY($result));
2253
2254                 // Prepare filter data array
2255                 $filterData = array(
2256                         'mode'          => 'edit',
2257                         'table_name'    => $tableName,
2258                         'content'       => $content,
2259                         'id'            => $id,
2260                         'subject'       => $subject,
2261                         'userid_column' => $userIdColumn,
2262                         'raw_userid'    => $rawUserId,
2263                         'affected'      => $edited,
2264                         'sql'           => $sql,
2265                 );
2266
2267                 // Send "build mail" out
2268                 runFilterChain('send_build_mail', $filterData);
2269
2270                 // Free the result
2271                 SQL_FREERESULT($result);
2272         } // END - foreach
2273
2274         // Delete cache?
2275         if ((count($cacheFiles) > 0) && (!empty($cacheFiles[0]))) {
2276                 // Delete cache file(s)
2277                 foreach ($cacheFiles as $cache) {
2278                         // Skip any empty entries
2279                         if (empty($cache)) {
2280                                 // This may cause trouble in loadCacheFile()
2281                                 continue;
2282                         } // END - if
2283
2284                         // Is the cache file loadable?
2285                         if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2286                                 // Then remove it
2287                                 $GLOBALS['cache_instance']->removeCacheFile();
2288                         } // END - if
2289                 } // END - foreach
2290         } // END - if
2291
2292         // Return affected rows
2293         return $affected;
2294 }
2295
2296 // Delete rows by given id numbers
2297 function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2298         // The base SQL command:
2299         $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
2300
2301         // Is a user id provided?
2302         //* BUG: */ die('<pre>'.print_r($rawUserId,TRUE).'</pre><pre>'.print_r($userIdColumn,TRUE).'</pre>');
2303         if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2304                 // Add user id as well
2305                 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2306         } // END - if
2307
2308         // $idColumn[0] in POST must be an array again
2309         if (!is_array(postRequestElement($idColumn[0]))) {
2310                 // This indicates that you have conflicting form field naming with XML names
2311                 reportBug(__FUNCTION__, __LINE__, 'You have a wrong form field element, idColumn[0]=' . $idColumn[0]);
2312         } // END - if
2313
2314         // Delete them all
2315         //* BUG: */ die($sql.'<pre>'.print_r($tableName,TRUE).'</pre><pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre><pre>'.print_r($extraValues,TRUE).'</pre><pre>'.print_r($deleteNow,TRUE).'</pre><pre>'.print_r($idColumn,TRUE).'</pre>');
2316         $idList = '';
2317         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2318                 // Is id zero?
2319                 if (!isValidId($id)) {
2320                         // Then skip this
2321                         continue;
2322                 } // END - if
2323
2324                 // Is there a userid?
2325                 if (isPostRequestElementSet($userIdColumn[0])) {
2326                         // Load all data from that id
2327                         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2328                                 array(
2329                                         $tableName[0],
2330                                         $idColumn[0],
2331                                         $id
2332                                 ), __FUNCTION__, __LINE__);
2333
2334                         // Fetch the data
2335                         $content = SQL_FETCHARRAY($result);
2336
2337                         // Free the result
2338                         SQL_FREERESULT($result);
2339
2340                         // Send "build mails" out
2341                         sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
2342                 } // END - if
2343
2344                 // Add id number
2345                 $idList .= $id . ',';
2346         } // END - foreach
2347
2348         // Run the query
2349         SQL_QUERY_ESC($sql,
2350                 array(
2351                         $tableName[0],
2352                         $idColumn[0],
2353                         convertNullToZero(substr($idList, 0, -1))
2354                 ), __FUNCTION__, __LINE__);
2355
2356         // Return affected rows
2357         return SQL_AFFECTEDROWS();
2358 }
2359
2360 // Build a special template list
2361 // @TODO cacheFiles is not yet supported
2362 function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2363         // $tableName and $idColumn must bove be arrays!
2364         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2365                 // $tableName is no array
2366                 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2367         } elseif (!is_array($idColumn)) {
2368                 // $idColumn is no array
2369                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2370         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
2371                 // $tableName is no array
2372                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2373         }
2374
2375         // Init row output
2376         $OUT = '';
2377
2378         // "Walk" through all entries
2379         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'listType=<pre>'.print_r($listType,TRUE).'</pre>,tableName<pre>'.print_r($tableName,TRUE).'</pre>,columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,idColumn=<pre>'.print_r($idColumn,TRUE).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,TRUE).'</pre>,rawUserId=<pre>'.print_r($rawUserId,TRUE).'</pre>');
2380         foreach (postRequestElement($idColumn[0]) as $id => $selected) {
2381                 // Secure id number
2382                 $id = bigintval($id);
2383
2384                 // Get result from a given column array and table name
2385                 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
2386
2387                 // Is there one entry?
2388                 if (SQL_NUMROWS($result) == 1) {
2389                         // Load all data
2390                         $row = SQL_FETCHARRAY($result);
2391
2392                         // Filter all data
2393                         foreach ($row as $key => $value) {
2394                                 // Search index
2395                                 $idx  = searchXmlArray($key, $columns, 'column');
2396
2397                                 // Default name is NULL
2398                                 $name = NULL;
2399
2400                                 // Is the name there?
2401                                 if (isset($columns[$idx]['name'])) {
2402                                         // Then use it
2403                                         $name = $columns[$idx]['name'];
2404                                 } // END - if
2405
2406                                 // Skip any missing entries
2407                                 if ($idx === FALSE) {
2408                                         // Skip this one
2409                                         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
2410                                         continue;
2411                                 } // END - if
2412
2413                                 // Is there a userid?
2414                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2415                                 if ($key == $userIdColumn[0]) {
2416                                         // Add it again as raw id
2417                                         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2418                                         $row[$userIdColumn[0]] = convertZeroToNull($value);
2419                                         $row[$userIdColumn[0] . '_raw'] = $row[$userIdColumn[0]];
2420                                 } // END - if
2421
2422                                 // If the key matches the idColumn variable, we need to temporary remember it
2423                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
2424                                 if ($key == $idColumn[0]) {
2425                                         /*
2426                                          * Found, so remember it securely (to make sure only id
2427                                          * numbers can pass, don't use alpha-numerical values!)
2428                                          */
2429                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
2430                                         $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
2431                                 } // END - if
2432
2433                                 // Try to handle call-back functions and/or extra values
2434                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',row[' . $key . ']=' . $row[$key]);
2435                                 //if ($key == 'forced_campaign_created') die($idx.'=<pre>'.print_r($columns,true).'</pre><pre>'.print_r($extraValues,true).'</pre>');
2436                                 $row[$key] = doHandleExtraValues($filterFunctions, $extraValues, $idx, $row[$key], $userIdColumn, ((!is_null($name)) ? $name : $key), $id);
2437                         } // END - foreach
2438
2439                         // Then list it
2440                         $OUT .= loadTemplate(sprintf("%s_%s_%s_row",
2441                                 $prefix,
2442                                 $listType,
2443                                 $tableName[0]
2444                                 ), TRUE, $row
2445                         );
2446                 } // END - if
2447
2448                 // Free the result
2449                 SQL_FREERESULT($result);
2450         } // END - foreach
2451
2452         // Is there an entry in $content?
2453         if ((is_array($content)) && (count($content) > 0)) {
2454                 // Use generic 'rows'
2455                 $content['rows'] = $OUT;
2456         } else {
2457                 // Use direct output
2458                 $content = $OUT;
2459         }
2460
2461         // Load master template
2462         loadTemplate(
2463                 sprintf("%s_%s_%s",
2464                         $prefix,
2465                         $listType,
2466                         $tableName[0]
2467                 ), FALSE, $content
2468         );
2469 }
2470
2471 // Adds key/value pair to a working SQL string together
2472 function addKeyValueSql ($key, $value) {
2473         // Init SQL
2474         $sql = '';
2475
2476         // Is it NULL?
2477         if (($value == 'NULL') || (is_null($value))) {
2478                 // Add key with NULL
2479                 $sql .= sprintf(' `%s`=NULL,',
2480                         SQL_ESCAPE($key)
2481                 );
2482         } elseif ((is_double($value)) || (is_float($value)) || (is_int($value))) {
2483                 // Is a number, so addd it directly
2484                 $sql .= sprintf(" `%s`=%s,",
2485                         SQL_ESCAPE($key),
2486                         $value
2487                 );
2488         } else {
2489                 // Else add the value escape'd
2490                 $sql .= sprintf(" `%s`='%s',",
2491                         SQL_ESCAPE($key),
2492                         SQL_ESCAPE($value)
2493                 );
2494         }
2495
2496         // Return SQL string
2497         return $sql;
2498 }
2499
2500 // [EOF]
2501 ?>