c26a12b991c15b93a9df2ac7756cf8b79b7fca2f
[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 - 2013 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // "Getter" for module 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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
73                 // Fetch the title
74                 $data = sqlFetchArray($result);
75         } // END - if
76
77         // Free result
78         sqlFreeResult($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 = sqlQueryEscaped("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 (!ifSqlHasZeroNums($result_main)) {
231                 // There are menus available, so we simply display them... :)
232                 $GLOBALS['rows'] = '';
233                 while ($content = sqlFetchArray($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 = sqlQueryEscaped("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 (!ifSqlHasZeroNums($result_sub)) {
263                                 // Init counter
264                                 $count = '0';
265
266                                 // Load all sub menus
267                                 while ($content2 = sqlFetchArray($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 < sqlNumRows($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                         sqlFreeResult($result_sub);
348
349                         // Count one up
350                         $main_cnt++;
351
352                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
353                         if (sqlNumRows($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                 sqlFreeResult($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 (isValidUserData()) {
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 (isValidUserData()) {
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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
521                 // Load data from cookies
522                 $data = sqlFetchArray($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 = isValidUserData();
559         } // END - if
560
561         // Free memory
562         sqlFreeResult($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 ((isInstaller()) || (!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 = sqlQuery('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 = sqlQuery('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 (!ifSqlHasZeroNums($result)) {
667                 $OUT = '';
668                 while ($content = sqlFetchArray($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         sqlFreeResult($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 = sqlQueryEscaped("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) = sqlFetchRow($result);
724
725         // Free the result
726         sqlFreeResult($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 = sqlQueryEscaped("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 = sqlQueryEscaped("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 = sqlQueryEscaped("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 = sqlQuery($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 = (!ifSqlHasZeroAffectedRows());
783         } else {
784                 // Check found rows
785                 $ret = (!ifSqlHasZeroNums($result));
786         }
787
788         // Free memory
789         sqlFreeResult($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 = sqlQueryEscaped("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
842                         array(
843                                 $module,
844                                 $what
845                         ), __FUNCTION__, __LINE__);
846
847                 // Entry found?
848                 if (sqlNumRows($result) == 1) {
849                         // Load action value and pray that this one is the right you want... ;-)
850                         $data = sqlFetchArray($result);
851                 } // END - if
852
853                 // Free memory
854                 sqlFreeResult($result);
855         } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
856                 // No ext-sql_patches installed, but maybe we need to register an admin?
857                 if (isAdminRegistered()) {
858                         // Redirect to admin area
859                         redirectToUrl('admin.php');
860                 } // END - if
861         }
862
863         // Return action value
864         return $data['action'];
865 }
866
867 // Get category name back
868 function getCategory ($cid) {
869         // Default is not found
870         $data['cat'] = '{--_CATEGORY_404--}';
871
872         // Is the category id set?
873         if (!isValidId($cid)) {
874                 // No category
875                 $data['cat'] = '{--_CATEGORY_NONE--}';
876         } elseif (isValidId($cid)) {
877                 // Lookup the category in database
878                 $result = sqlQueryEscaped('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
879                         array(bigintval($cid)), __FUNCTION__, __LINE__);
880                 if (sqlNumRows($result) == 1) {
881                         // Category found... :-)
882                         $data = sqlFetchArray($result);
883                 } // END - if
884
885                 // Free result
886                 sqlFreeResult($result);
887         } // END - if
888
889         // Return result
890         return $data['cat'];
891 }
892
893 // Get a string of "mail title" and price back
894 function getPaymentTitlePrice ($paymentsId, $full = FALSE) {
895         // Only title or also including price?
896         if ($full === FALSE) {
897                 $ret = getPaymentData($paymentsId, 'main_title');
898         } else {
899                 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
900         }
901
902         // Return result
903         return $ret;
904 }
905
906 // Get payment price
907 function getPaymentPrice ($paymentsId) {
908         // Return result
909         return getPaymentData($paymentsId, 'price');
910 }
911
912 // Get payment time
913 function getPaymentTime ($paymentsId) {
914         // Return result
915         return getPaymentData($paymentsId, 'time');
916 }
917
918 // Get payment 'payment'
919 function getPaymentPayment ($paymentsId) {
920         // Return result
921         return getPaymentData($paymentsId, 'payment');
922 }
923
924 // "Getter" for payment data (cached)
925 function getPaymentData ($paymentsId, $lookFor) {
926         // Default value...
927         $data[$lookFor] = NULL;
928
929         // Is there cache?
930         if (isset($GLOBALS['cache_array']['payments'][$lookFor][$paymentsId])) {
931                 // Use it if found to save SQL queries
932                 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$paymentsId];
933
934                 // Update cache hits
935                 incrementStatsEntry('cache_hits');
936         } elseif (!isExtensionActive('cache')) {
937                 // Search for it in database
938                 $result = sqlQueryEscaped('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
939                         array(
940                                 $lookFor,
941                                 bigintval($paymentsId)
942                         ), __FUNCTION__, __LINE__);
943
944                 // Is the entry there?
945                 if (sqlNumRows($result) == 1) {
946                         // Payment type found... :-)
947                         $data = sqlFetchArray($result);
948                 } // END - if
949
950                 // Free result
951                 sqlFreeResult($result);
952         }
953
954         // Return value
955         return $data[$lookFor];
956 }
957
958 // Remove a receiver's id from $receivers and add a link for him to confirm
959 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = FALSE) {
960         // Default is not removed
961         $ret = 'failed';
962
963         // Is the userid valid?
964         if (isValidId($userid)) {
965                 // Remove entry from array
966                 unset($receivers[$key]);
967
968                 // Is there already a line for this user available?
969                 if (isValidId($statsId)) {
970                         // Default is 'normal' mail
971                         $type = 'NORMAL';
972                         $rowName = 'stats_id';
973
974                         // Only when we got a real stats id continue searching for the entry
975                         if ($isBonusMail === TRUE) {
976                                 $type = 'BONUS';
977                                 $rowName = 'bonus_id';
978                         } // END - if
979
980                         // Try to look the entry up
981                         $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
982                                 array(
983                                         $rowName,
984                                         bigintval($statsId),
985                                         bigintval($userid),
986                                         $type
987                                 ), __FUNCTION__, __LINE__);
988
989                         // Was it *not* found?
990                         if (ifSqlHasZeroNums($result)) {
991                                 // So we add one!
992                                 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES (%s,%s,'%s')",
993                                         array(
994                                                 $rowName,
995                                                 bigintval($statsId),
996                                                 bigintval($userid),
997                                                 $type
998                                         ), __FUNCTION__, __LINE__);
999
1000                                 // Update 'mails_sent' if ext-sql_patches is updated
1001                                 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
1002                                         // Update the pool
1003                                         updatePoolDataById($poolId, 'mails_sent', 1, '+');
1004                                 } // END - if
1005                                 $ret = 'done';
1006                         } else {
1007                                 // Already found
1008                                 $ret = 'already';
1009                         }
1010
1011                         // Free memory
1012                         sqlFreeResult($result);
1013                 } // END - if
1014         } // END - if
1015
1016         // Return status for sending routine
1017         return $ret;
1018 }
1019
1020 // Calculate sum (default) or count records of given criteria
1021 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = FALSE, $add = '', $mode = '=') {
1022         // Debug message
1023         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
1024         if ((empty($search)) && (!is_null($search))) {
1025                 // Count or sum whole table?
1026                 if ($countRows === TRUE) {
1027                         // Count whole table
1028                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1029                         $result = sqlQueryEscaped('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1030                                 array(
1031                                         $lookFor,
1032                                         $tableName
1033                                 ), __FUNCTION__, __LINE__);
1034                 } else {
1035                         // Sum whole table
1036                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1037                         $result = sqlQueryEscaped('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1038                                 array(
1039                                         $lookFor,
1040                                         $tableName
1041                                 ), __FUNCTION__, __LINE__);
1042                 }
1043         } elseif (($countRows === TRUE) || ($lookFor == 'userid')) {
1044                 // Count rows
1045                 if (is_null($search)) {
1046                         // Fix mode
1047                         if ($mode == '=') {
1048                                 $mode = 'IS';
1049                         } elseif ($mode == '!=') {
1050                                 $mode = 'IS NOT';
1051                         }
1052
1053                         // Look for NULL/0
1054                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT-NULL!');
1055                         $result = sqlQueryEscaped("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE (`%s` %s NULL OR `%s`=0)" . $add . ' LIMIT 1',
1056                                 array(
1057                                         $lookFor,
1058                                         $tableName,
1059                                         $whereStatement,
1060                                         $mode,
1061                                         $whereStatement
1062                                 ), __FUNCTION__, __LINE__);
1063                 } else {
1064                         // Regular entry
1065                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1066                         $result = sqlQueryEscaped("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1067                                 array(
1068                                         $lookFor,
1069                                         $tableName,
1070                                         $whereStatement,
1071                                         $mode,
1072                                         $search
1073                                 ), __FUNCTION__, __LINE__);
1074                 }
1075         } else {
1076                 // Sum all rows
1077                 if (is_null($search)) {
1078                         // Fix mode
1079                         if ($mode == '=') {
1080                                 $mode = 'IS';
1081                         } elseif ($mode == '!=') {
1082                                 $mode = 'IS NOT';
1083                         }
1084
1085                         // Look for NULL/0
1086                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM-NULL!');
1087                         $result = sqlQueryEscaped("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE (`%s` %s NULL OR `%s`=0)" . $add . ' LIMIT 1',
1088                                 array(
1089                                         $lookFor,
1090                                         $tableName,
1091                                         $whereStatement,
1092                                         $mode,
1093                                         $whereStatement
1094                                 ), __FUNCTION__, __LINE__);
1095                 } else {
1096                         // Regular entry
1097                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1098                         $result = sqlQueryEscaped("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1099                                 array(
1100                                         $lookFor,
1101                                         $tableName,
1102                                         $whereStatement,
1103                                         $mode,
1104                                         $search
1105                                 ), __FUNCTION__, __LINE__);
1106                 }
1107         }
1108
1109         // Load row
1110         $data = sqlFetchArray($result);
1111
1112         // Free result
1113         sqlFreeResult($result);
1114
1115         // Fix empty values
1116         if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1117                 // Float number
1118                 $data['res'] = '0.00000';
1119         } elseif ('' . $data['res'] . '' == '') {
1120                 // Fix empty result
1121                 $data['res'] = '0';
1122         }
1123
1124         // Return value
1125         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1126         return $data['res'];
1127 }
1128
1129 /**
1130  * Sends out mail to all administrators. This function is no longer obsolete
1131  * because we need it when there is no ext-admins installed
1132  */
1133 function sendAdminEmails ($subject, $message, $isBugReport = FALSE) {
1134         // Default is no special header
1135         $mailHeader = '';
1136
1137         // Is it a bug report?
1138         if ($isBugReport === TRUE) {
1139                 // Then add a reply-to line back to the author (me)
1140                 $mailHeader = 'Reply-To: webmaster@mxchange.org' . PHP_EOL;
1141         } // END - if
1142
1143         // Load all admin email addresses
1144         $result = sqlQuery('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1145
1146         // And send the notification to all of them
1147         while ($content = sqlFetchArray($result)) {
1148                 // Send the email out
1149                 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1150         } // END - if
1151
1152         // Free result
1153         sqlFreeResult($result);
1154
1155         // Really simple... ;-)
1156 }
1157
1158 // Get id number from administrator's login name
1159 function getAdminId ($adminLogin) {
1160         // By default no admin is found
1161         $data['id'] = -1;
1162
1163         // Check cache
1164         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1165                 // Use it if found to save SQL queries
1166                 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1167
1168                 // Update cache hits
1169                 incrementStatsEntry('cache_hits');
1170         } elseif (!isExtensionActive('cache')) {
1171                 // Load from database
1172                 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1173                         array($adminLogin), __FUNCTION__, __LINE__);
1174
1175                 // Is there an entry?
1176                 if (sqlNumRows($result) == 1) {
1177                         // Get it
1178                         $data = sqlFetchArray($result);
1179                 } // END - if
1180
1181                 // Free result
1182                 sqlFreeResult($result);
1183         }
1184
1185         // Return the id
1186         return $data['id'];
1187 }
1188
1189 // "Getter" for current admin id
1190 function getCurrentAdminId () {
1191         // Log debug message
1192         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1193
1194         // Is there cache?
1195         if (!isset($GLOBALS['current_admin_id'])) {
1196                 // Get the admin login from session
1197                 $adminId = getSession('admin_id');
1198
1199                 // Remember in cache securely
1200                 setCurrentAdminId(bigintval($adminId));
1201         } // END - if
1202
1203         // Return it
1204         return $GLOBALS['current_admin_id'];
1205 }
1206
1207 // Setter for current admin id
1208 function setCurrentAdminId ($currentAdminId) {
1209         // Set it secured
1210         $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1211 }
1212
1213 // Get password hash from administrator's login name
1214 function getAdminHash ($adminId) {
1215         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ' - ENTERED!');
1216         // By default an invalid hash is returned
1217         $data['password'] = -1;
1218
1219         // Is admin hash set?
1220         if (isAdminHashSet($adminId)) {
1221                 // Check cache
1222                 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1223
1224                 // Update cache hits
1225                 incrementStatsEntry('cache_hits');
1226         } elseif (!isExtensionActive('cache')) {
1227                 // Load from database
1228                 $result = sqlQueryEscaped("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1229                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1230
1231                 // Is there an entry?
1232                 if (sqlNumRows($result) == 1) {
1233                         // Fetch data
1234                         $data = sqlFetchArray($result);
1235
1236                         // Set cache
1237                         setAdminHash($adminId, $data['password']);
1238                 } // END - if
1239
1240                 // Free result
1241                 sqlFreeResult($result);
1242         }
1243
1244         // Return password hash
1245         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',data[password]=' . $data['password'] . ' - EXIT!');
1246         return $data['password'];
1247 }
1248
1249 // "Getter" for admin login
1250 function getAdminLogin ($adminId) {
1251         // By default a non-existent login is returned (other functions react on this!)
1252         $data['login'] = '***';
1253
1254         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1255                 // Get cache
1256                 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1257
1258                 // Update cache hits
1259                 incrementStatsEntry('cache_hits');
1260         } elseif (!isExtensionActive('cache')) {
1261                 // Load from database
1262                 $result = sqlQueryEscaped("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1263                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1264
1265                 // Entry found?
1266                 if (sqlNumRows($result) == 1) {
1267                         // Fetch data
1268                         $data = sqlFetchArray($result);
1269
1270                         // Set cache
1271                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1272                 } // END - if
1273
1274                 // Free memory
1275                 sqlFreeResult($result);
1276         }
1277
1278         // Return the result
1279         return $data['login'];
1280 }
1281
1282 // Get email address of admin id
1283 function getAdminEmail ($adminId) {
1284         // By default an invalid emails is returned
1285         $data['email'] = '***';
1286
1287         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1288                 // Get cache
1289                 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1290
1291                 // Update cache hits
1292                 incrementStatsEntry('cache_hits');
1293         } elseif (!isExtensionActive('cache')) {
1294                 // Load from database
1295                 $result_admin_id = sqlQueryEscaped("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1296                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1297
1298                 // Entry found?
1299                 if (sqlNumRows($result_admin_id) == 1) {
1300                         // Get data
1301                         $data = sqlFetchArray($result_admin_id);
1302
1303                         // Set cache
1304                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1305                 } // END - if
1306
1307                 // Free result
1308                 sqlFreeResult($result_admin_id);
1309         }
1310
1311         // Return email
1312         return $data['email'];
1313 }
1314
1315 // Get default ACL of admin id
1316 function getAdminDefaultAcl ($adminId) {
1317         // By default an invalid ACL value is returned
1318         $data['default_acl'] = 'NO-ACL';
1319
1320         // Is ext-sql_patches there and was it found in cache?
1321         if (!isExtensionActive('sql_patches')) {
1322                 // Not found, which is bad, so we need to allow all
1323                 $data['default_acl'] = 'allow';
1324         } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1325                 // Use cache
1326                 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1327
1328                 // Update cache hits
1329                 incrementStatsEntry('cache_hits');
1330         } elseif (!isExtensionActive('cache')) {
1331                 // Load from database
1332                 $result_admin_id = sqlQueryEscaped("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1333                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1334
1335                 // Is there an entry?
1336                 if (sqlNumRows($result_admin_id) == 1) {
1337                         // Fetch data
1338                         $data = sqlFetchArray($result_admin_id);
1339
1340                         // Set cache
1341                         $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1342                 }
1343
1344                 // Free result
1345                 sqlFreeResult($result_admin_id);
1346         }
1347
1348         // Return default ACL
1349         return $data['default_acl'];
1350 }
1351
1352 // Get menu mode (la_mode) of admin id
1353 function getAdminMenuMode ($adminId) {
1354         // By default an invalid mode
1355         $data['la_mode'] = 'INVALID';
1356
1357         // Is ext-sql_patches there and was it found in cache?
1358         if (!isExtensionActive('sql_patches')) {
1359                 // Not found, which is bad, so we need to allow all
1360                 $data['la_mode'] = 'global';
1361         } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1362                 // Use cache
1363                 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1364
1365                 // Update cache hits
1366                 incrementStatsEntry('cache_hits');
1367         } elseif (!isExtensionActive('cache')) {
1368                 // Load from database
1369                 $result_admin_id = sqlQueryEscaped("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1370                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1371
1372                 // Is there an entry?
1373                 if (sqlNumRows($result_admin_id) == 1) {
1374                         // Fetch data
1375                         $data = sqlFetchArray($result_admin_id);
1376
1377                         // Set cache
1378                         $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1379                 }
1380
1381                 // Free result
1382                 sqlFreeResult($result_admin_id);
1383         }
1384
1385         // Return default ACL
1386         return $data['la_mode'];
1387 }
1388
1389 // Generates an option list from various parameters
1390 function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '', $allowNone = FALSE) {
1391         $ret = '';
1392
1393         // Allow none?
1394         if ($allowNone === TRUE) {
1395                 // Add option for none
1396                 $ret .= '<option value="0">{--SELECT_NONE--}</option>';
1397         } // END - if
1398
1399         if ($table == '/ARRAY/') {
1400                 // Selection from array
1401                 if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
1402                         // Both are arrays
1403                         foreach ($key as $idx => $optionValue) {
1404                                 $ret .= '<option value="' . $optionValue . '"';
1405                                 if ($default == $optionValue) {
1406                                         // Selected by default
1407                                         $ret .= ' selected="selected"';
1408                                 } elseif (isset($disabled[$optionValue])) {
1409                                         // Disabled!
1410                                         $ret .= ' disabled="disabled"';
1411                                 }
1412
1413                                 // Is the call-back function set?
1414                                 if (!empty($callback)) {
1415                                         // Call it
1416                                         $value[$idx] = call_user_func_array($callback, array($key[$idx]));
1417                                 } // END - if
1418
1419                                 // Finish option tag
1420                                 $ret .= '>' . $value[$idx] . '</option>';
1421                         } // END - foreach
1422                 } else {
1423                         // Problem in request
1424                         reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: key[' . count($key) . ']=' . gettype($key) . ',value[' . count($value) . ']=' . gettype($value) . ',callback=' . $callback);
1425                 }
1426         } else {
1427             ///////////////////////
1428                 // Data from database /
1429                 ///////////////////////
1430
1431                 // Init extra column (if requested)
1432                 $extraColumn = '';
1433                 if (!empty($extra)) {
1434                         $extraColumn = ',`' . $extra . '` AS `extra`';
1435                 } // END - if
1436
1437                 // Run SQL query
1438                 $result = sqlQueryEscaped("SELECT `%s` AS `key`, `%s` AS `value`" . $extraColumn . " FROM `{?_MYSQL_PREFIX?}_%s` " . $whereStatement . " ORDER BY `%s` ASC",
1439                         array(
1440                                 $key,
1441                                 $value,
1442                                 $table,
1443                                 $value
1444                         ), __FUNCTION__, __LINE__);
1445
1446                 // Is there rows?
1447                 if (!ifSqlHasZeroNums($result)) {
1448                         // Found data so add them as OPTION lines
1449                         while ($content = sqlFetchArray($result)) {
1450                                 // Is extra set?
1451                                 if (!isset($content['extra'])) {
1452                                         // Set it to empty
1453                                         $content['extra'] = '';
1454                                 } // END - if
1455
1456                                 $ret .= '<option value="' . $content['key'] . '"';
1457
1458                                 if ($default == $content['key']) {
1459                                         // Selected by default
1460                                         $ret .= ' selected="selected"';
1461                                 } elseif (isset($disabled[$content['key']])) {
1462                                         // Disabled!
1463                                         $ret .= ' disabled="disabled"';
1464                                 }
1465
1466                                 // Add it, if set
1467                                 if (!empty($content['extra'])) {
1468                                         $content['extra'] = ' (' . $content['extra'] . ')';
1469                                 } // END - if
1470
1471                                 // Is the call-back function set?
1472                                 if (!empty($callback)) {
1473                                         // Call it
1474                                         $content['value'] = call_user_func_array($callback, array($content['value']));
1475                                 } // END - if
1476
1477                                 // Finish option list
1478                                 $ret .= '>' . $content['value'] . $content['extra'] . '</option>';
1479                         } // END - while
1480                 } else {
1481                         // No data found
1482                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1483                 }
1484
1485                 // Free memory
1486                 sqlFreeResult($result);
1487         }
1488
1489         // Return - hopefully - the requested data
1490         return $ret;
1491 }
1492
1493 // Deletes a user account with given reason
1494 function deleteUserAccount ($userid, $reason) {
1495         // Init points
1496         $data['points'] = '0';
1497
1498         // Search for the points and user data
1499         $result = sqlQueryEscaped("SELECT
1500         (SUM(`p`.`points`) - `d`.`used_points`) AS `points`
1501 FROM
1502         `{?_MYSQL_PREFIX?}_user_points` AS `p`
1503 LEFT JOIN
1504         `{?_MYSQL_PREFIX?}_user_data` AS `d`
1505 ON
1506         `p`.`userid`=`d`.`userid`
1507 WHERE
1508         `p`.`userid`=%s
1509 LIMIT 1",
1510                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1511
1512         // Is there an entry?
1513         if (sqlNumRows($result) == 1) {
1514                 // Save his points to add them to the jackpot
1515                 $data = sqlFetchArray($result);
1516
1517                 // Delete points entries as well
1518                 // @TODO Rewrite these lines to a filter
1519                 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1520                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1521
1522                 // Update mediadata as well
1523                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1524                         // Update database
1525                         updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1526                 } // END - if
1527
1528                 // Now, when we have all his points adds them do the jackpot!
1529                 if (isExtensionActive('jackpot')) {
1530                         addPointsToJackpot($data['points']);
1531                 } // END - if
1532         } // END - if
1533
1534         // Free the result
1535         sqlFreeResult($result);
1536
1537         // Delete category selections as well...
1538         sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1539                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1540
1541         // Remove from rallye if found
1542         // @TODO Rewrite this to a filter
1543         if (isExtensionActive('rallye')) {
1544                 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1545                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1546         } // END - if
1547
1548         // Add reason and translate points
1549         $data['text'] = $reason;
1550
1551         // Now a mail to the user and that's all...
1552         $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1553         sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1554
1555         // Ok, delete the account!
1556         sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1557 }
1558
1559 // Gets the matching what name from module
1560 function getWhatFromModule ($modCheck) {
1561         // Is the request element set?
1562         if (isGetRequestElementSet('what')) {
1563                 // Then return this!
1564                 return getRequestElement('what');
1565         } // END - if
1566
1567         // Default is empty
1568         $what = '';
1569
1570         // Check on given module
1571         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1572         switch ($modCheck) {
1573                 case 'index': // Guest area
1574                         // Is ext-sql_patches installed and newer than 0.0.5?
1575                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1576                                 // Use it from config
1577                                 $what = getIndexHome();
1578                         } else {
1579                                 // Use default 'welcome'
1580                                 $what = 'welcome';
1581                         }
1582                         break;
1583
1584                 default: // Default for all other menus (getIndexHome() is for index module only)
1585                         $what = 'welcome';
1586                         break;
1587         } // END - switch
1588
1589         // Return what value
1590         return $what;
1591 }
1592
1593 // Returns HTML code with an option list of all categories
1594 function generateCategoryOptionsList ($mode, $userid = NULL) {
1595         // Prepare WHERE statement
1596         $whereStatement = " WHERE `visible`='Y'";
1597         if (isAdmin()) $whereStatement = '';
1598
1599         // Initialize array...
1600         $categories = array(
1601                 'id'      => array(),
1602                 'name'    => array(),
1603                 'userids' => array()
1604         );
1605
1606         // Get categories
1607         $result = sqlQuery('SELECT
1608         `id`,
1609         `cat`
1610 FROM
1611         `{?_MYSQL_PREFIX?}_cats`
1612 ' . $whereStatement . '
1613 ORDER BY
1614         `sort` ASC',
1615                 __FUNCTION__, __LINE__);
1616
1617         // Are there entries?
1618         if (!ifSqlHasZeroNums($result)) {
1619                 // ... and begin loading stuff
1620                 while ($content = sqlFetchArray($result)) {
1621                         // Transfer some data
1622                         $categories['id'][]   = $content['id'];
1623                         array_push($categories['name'], $content['cat']);
1624
1625                         // Check which users are in this category
1626                         $result_userids = sqlQueryEscaped("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1627                                 array(
1628                                         bigintval($content['id']),
1629                                         convertNullToZero($userid)
1630                                 ), __FUNCTION__, __LINE__);
1631
1632                         // Init count
1633                         $userid_cnt = '0';
1634
1635                         // Start adding all
1636                         while ($data = sqlFetchArray($result_userids)) {
1637                                 // Add user count
1638                                 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', TRUE, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1639                         } // END - while
1640
1641                         // Free memory
1642                         sqlFreeResult($result_userids);
1643
1644                         // Add counter
1645                         array_push($categories['userids'], $userid_cnt);
1646                 } // END - while
1647
1648                 // Free memory
1649                 sqlFreeResult($result);
1650
1651                 // Generate options
1652                 $OUT = '';
1653                 foreach ($categories['id'] as $key => $value) {
1654                         $OUT .= '      <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1655                 } // END - foreach
1656         } else {
1657                 // No cateogries are defined yet
1658                 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1659         }
1660
1661         // Return HTML code
1662         return $OUT;
1663 }
1664
1665 // Add bonus mail to queue
1666 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1667         // Is admin or bonus extension there?
1668         if (!isAdmin()) {
1669                 // Abort here
1670                 return FALSE;
1671         } elseif (!isExtensionActive('bonus')) {
1672                 // Abort here
1673                 return FALSE;
1674         }
1675
1676         // Calculcate target sent
1677         $target = countSelection(explode(';', $receiverList));
1678
1679         // Receiver is zero?
1680         if ($receiver == '0') {
1681                 // Then auto-fix it
1682                 $receiver = $target;
1683         } // END - if
1684
1685         // HTML extension active?
1686         if (isExtensionActive('html_mail')) {
1687                 // Add HTML mail
1688                 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1689         `subject`,
1690         `text`,
1691         `receivers`,
1692         `points`,
1693         `time`,
1694         `data_type`,
1695         `timestamp`,
1696         `url`,
1697         `cat_id`,
1698         `target_send`,
1699         `mails_sent`,
1700         `html_msg`
1701 ) VALUES (
1702         '%s',
1703         '%s',
1704         '%s',
1705         %s,
1706         %s,
1707         'NEW',
1708         UNIX_TIMESTAMP(),
1709         '%s',
1710         %s,
1711         %s,
1712         %s,
1713         '%s'
1714 )",
1715                 array(
1716                         $subject,
1717                         $text,
1718                         $receiverList,
1719                         $points,
1720                         bigintval($seconds),
1721                         $url,
1722                         bigintval($categoryId),
1723                         $target,
1724                         bigintval($receiver),
1725                         convertBooleanToYesNo($mode == 'html')
1726                 ), __FUNCTION__, __LINE__);
1727         } else {
1728                 // Add regular mail
1729                 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1730         `subject`,
1731         `text`,
1732         `receivers`,
1733         `points`,
1734         `time`,
1735         `data_type`,
1736         `timestamp`,
1737         `url`,
1738         `cat_id`,
1739         `target_send`,
1740         `mails_sent`
1741 ) VALUES (
1742         '%s',
1743         '%s',
1744         '%s',
1745         %s,
1746         %s,
1747         'NEW',
1748         UNIX_TIMESTAMP(),
1749         '%s',
1750         %s,
1751         %s,
1752         %s
1753 )",
1754                 array(
1755                         $subject,
1756                         $text,
1757                         $receiverList,
1758                         $points,
1759                         bigintval($seconds),
1760                         $url,
1761                         bigintval($categoryId),
1762                         $target,
1763                         bigintval($receiver),
1764                 ), __FUNCTION__, __LINE__);
1765         }
1766 }
1767
1768 // Generate a receiver list for given category and maximum receivers
1769 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1770         // Init variables
1771         $extraColumns = '';
1772         $receiverList = '';
1773         $result       = FALSE;
1774
1775         // Secure data
1776         $categoryId = bigintval($categoryId);
1777         $receiver   = bigintval($receiver);
1778
1779         // Is the receiver zero and mode set?
1780         if (($receiver == '0') && (!empty($mode))) {
1781                 // Auto-fix receiver maximum
1782                 $receiver = getTotalReceivers($mode);
1783         } // END - if
1784
1785         // Exclude (maybe exclude) testers
1786         $addWhere = runFilterChain('user_exclusion_sql', ' ');
1787
1788         // Category given?
1789         if (isValidId($categoryId)) {
1790                 // Select category
1791                 $extraColumns  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS `c` ON `d`.`userid`=`c`.`userid`";
1792                 $addWhere = sprintf(" AND `c`.`cat_id`=%s", $categoryId);
1793         } // END - if
1794
1795         // Exclude users in holiday?
1796         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1797                 // Add something for the holiday extension
1798                 $addWhere .= " AND `d`.`holiday_active`='N'";
1799         } // END - if
1800
1801         // Run query
1802         $result = sqlQueryEscaped("SELECT
1803         `d`.`userid`
1804 FROM
1805         `{?_MYSQL_PREFIX?}_user_data` AS `d`
1806         " . $extraColumns . "
1807 WHERE
1808         `d`.`status`='CONFIRMED'
1809         " . $addWhere . "
1810 ORDER BY
1811         `d`.`{?order_select?}` {?order_mode?}
1812 LIMIT %s",
1813                 array(
1814                         $receiver
1815                 ), __FUNCTION__, __LINE__);
1816
1817         // Entries found?
1818         if ((sqlNumRows($result) >= $receiver) && ($receiver > 0)) {
1819                 // Load all entries
1820                 while ($content = sqlFetchArray($result)) {
1821                         // Add receiver when not empty
1822                         if (!empty($content['userid'])) {
1823                                 $receiverList .= $content['userid'] . ';';
1824                         } // END - if
1825                 } // END - while
1826
1827                 // Free memory
1828                 sqlFreeResult($result);
1829
1830                 // Remove trailing semicolon
1831                 $receiverList = substr($receiverList, 0, -1);
1832         } // END - if
1833
1834         // Return list
1835         return $receiverList;
1836 }
1837
1838 // Recuce the amount of received emails for the receipients for given email
1839 function reduceRecipientReceivedMails ($column, $id, $count) {
1840         // Search for mail in database
1841         $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1842                 array(
1843                         $column,
1844                         bigintval($id),
1845                         $count
1846                 ), __FUNCTION__, __LINE__
1847         );
1848
1849         // Are there entries?
1850         if (!ifSqlHasZeroNums($result)) {
1851                 // Now load all userids for one big query!
1852                 $userids = array();
1853                 while ($data = sqlFetchArray($result)) {
1854                         // By default reduce and found no emails
1855                         $num = 0;
1856
1857                         // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1858                         // @TODO Rewrite this to a filter
1859                         if ((isset($data['stats_id'])) && (isValidId($data['stats_id']))) {
1860                                 // User email
1861                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1862                         } elseif ((isset($data['bonus_id'])) && (isValidId($data['bonus_id']))) {
1863                                 // Bonus mail
1864                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1865                         }
1866
1867                         // Reduce this users total received emails?
1868                         if ($num === 0) {
1869                                 $userids[$data['userid']] = $data['userid'];
1870                         } // END - if
1871                 } // END - while
1872
1873                 if (isFilledArray($userids)) {
1874                         // Now update all user accounts
1875                         sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1876                                 array(
1877                                         implode(',', $userids),
1878                                         count($userids)
1879                                 ), __FUNCTION__, __LINE__);
1880                 } else {
1881                         // Nothing deleted
1882                         displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1883                 }
1884         } // END - if
1885
1886         // Free result
1887         sqlFreeResult($result);
1888 }
1889
1890 // Creates a new task
1891 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = TRUE) {
1892         // Insert the task data into the database
1893         sqlQueryEscaped("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())",
1894                 array(
1895                         convertZeroToNull($adminId),
1896                         convertZeroToNull($userid),
1897                         $taskType,
1898                         $subject,
1899                         $notes
1900                 ), __FUNCTION__, __LINE__, TRUE, $strip);
1901
1902         // Return insert id which is the task id
1903         return getSqlInsertId();
1904 }
1905
1906 // Updates last module / online time
1907 function updateLastActivity ($userid) {
1908         // Is 'what' set?
1909         if (isWhatSet()) {
1910                 // Run the update query
1911                 sqlQueryEscaped("UPDATE
1912         `{?_MYSQL_PREFIX?}_user_data`
1913 SET
1914         `{%%pipe,getUserLastWhatName%%}`='{%%pipe,getWhat%%}',
1915         `last_online`=UNIX_TIMESTAMP(),
1916         `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1917 WHERE
1918         `userid`=%s
1919 LIMIT 1",
1920                 array(
1921                         bigintval($userid)
1922                 ), __FUNCTION__, __LINE__);
1923         } else {
1924                 // No what set, needs to be ignored (last_module is last_what)
1925                 sqlQueryEscaped("UPDATE
1926         `{?_MYSQL_PREFIX?}_user_data`
1927 SET
1928         `{%%pipe,getUserLastWhatName%%}`=NULL,
1929         `last_online`=UNIX_TIMESTAMP(),
1930         `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1931 WHERE
1932         `userid`=%s
1933 LIMIT 1",
1934                 array(
1935                         bigintval($userid)
1936                 ), __FUNCTION__, __LINE__);
1937         }
1938 }
1939
1940 // List all given joined rows (callback function from XML)
1941 function doGenericJoinedListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1942         // Verify that tableName and columns are not empty
1943         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1944                 // No tableName specified
1945                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1946         } elseif (!isFilledArray($columns)) {
1947                 // No columns specified
1948                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1949         }
1950
1951         // This is the minimum query, so at least columns and tableName must have entries
1952         $sql = 'SELECT ';
1953
1954         // Get the sql part back from given array
1955         $sql .= getSqlPartFromXmlArray($columns);
1956
1957         // Add "FROM"
1958         $sql .= getSqlXmlFromTable($tableName);
1959
1960         // Add "JOIN"
1961         $sql .= getSqlXmlJoinedTable($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable);
1962
1963         // Add "WHERE"
1964         $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
1965
1966         // Add "ORDER BY"
1967         $sql .= getSqlXmlOrderBy($orderByColumns);
1968
1969         // Now handle all over to the inner function which will execute the listing
1970         doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
1971 }
1972
1973 // List all given rows (callback function from XML)
1974 function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1975         // Verify that tableName and columns are not empty
1976         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1977                 // No tableName specified
1978                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1979         } elseif (!isFilledArray($columns)) {
1980                 // No columns specified
1981                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1982         }
1983
1984         // This is the minimum query, so at least columns and tableName must have entries
1985         $sql = 'SELECT ';
1986
1987         // Get the sql part back from given array
1988         $sql .= getSqlPartFromXmlArray($columns);
1989
1990         // Add "FROM"
1991         $sql .= getSqlXmlFromTable($tableName);
1992
1993         // Add "WHERE"
1994         $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
1995
1996         // Add "ORDER BY"
1997         $sql .= getSqlXmlOrderBy($orderByColumns);
1998
1999         // Now handle all over to the inner function which will execute the listing
2000         doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
2001 }
2002
2003 // Do the listing of entries
2004 function doListEntries ($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array(), $content = array()) {
2005         // Run the SQL query
2006         $result = sqlQuery($sql, __FUNCTION__, __LINE__);
2007
2008         // Are there some URLs left?
2009         if (!ifSqlHasZeroNums($result)) {
2010                 // List all URLs
2011                 $OUT = '';
2012                 while ($row = sqlFetchArray($result)) {
2013                         // "Translate" content
2014                         foreach ($callbackColumns as $columnName => $callbackName) {
2015                                 // Fill the callback arguments
2016                                 $args = array($row[$columnName]);
2017
2018                                 // Is there more to add?
2019                                 if (isset($extraParameters[$columnName])) {
2020                                         // Add them as well
2021                                         $args = merge_array($args, $extraParameters[$columnName]);
2022                                 } // END - if
2023
2024                                 // Call the callback-function
2025                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, TRUE).'</pre>');
2026                                 // @TODO If the EL sub-system can support more than one parameter, this call_user_func_array() can be avoided
2027                                 $row[$columnName] = call_user_func_array($callbackName, $args);
2028                         } // END - foreach
2029
2030                         // Load row template
2031                         $OUT .= loadTemplate(trim($rowTemplate[0]), TRUE, $row);
2032                 } // END - while
2033
2034                 // Is at least one entry set in content?
2035                 if (isFilledArray($content)) {
2036                         // Then add generic 'rows' element
2037                         $content['rows'] = $OUT;
2038                 } else {
2039                         // Direct output is content
2040                         $content = $OUT;
2041                 }
2042
2043                 // Load main template
2044                 loadTemplate(trim($tableTemplate[0]), FALSE, $content);
2045         } else {
2046                 // No URLs in surfbar
2047                 displayMessage('{--' .$noEntryMessageId[0] . '--}');
2048         }
2049
2050         // Free result
2051         sqlFreeResult($result);
2052 }
2053
2054 // Adds a given entry to the database
2055 function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2056         //* 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>');
2057         // Verify that tableName and columns are not empty
2058         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2059                 // No tableName specified
2060                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2061         } elseif (!isFilledArray($columns)) {
2062                 // No columns specified
2063                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
2064         }
2065
2066         // Init columns and value elements
2067         $sqlColumns = array();
2068         $sqlValues  = array();
2069
2070         // Default is that all went fine
2071         $GLOBALS['__XML_PARSE_RESULT'] = TRUE;
2072
2073         // Is there "time columns"?
2074         if (isFilledArray($timeColumns)) {
2075                 // Then "walk" through all entries
2076                 foreach ($timeColumns as $column) {
2077                         // Convert all (possible) selections
2078                         convertSelectionsToEpocheTimeInPostData($column . '_ye');
2079                 } // END - foreach
2080         } // END - if
2081
2082         // Add columns and values
2083         foreach ($columns as $key => $columnName) {
2084                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
2085                 // Is columnIndex set?
2086                 if (!is_null($columnIndex)) {
2087                         // Check conditions
2088                         //* DEBUG: */ die('columnName=<pre>'.print_r($columnName,TRUE).'</pre>columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>'.debug_get_printable_backtrace());
2089                         assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
2090
2091                         // Then use that index "blindly"
2092                         $columnName = $columnName[$columnIndex];
2093                 } // END - if
2094
2095                 // Debug message
2096                 //* 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'])));
2097
2098                 // Get value back (no array supported)
2099                 $value = postRequestElement($columnName);
2100
2101                 // Is this an array and element 0 is set?
2102                 if ((is_array($value)) && (isset($value[0]))) {
2103                         // Then only take this
2104                         $value = $value[0];
2105                 } // END - if
2106
2107                 // Copy entry securely to the final arrays
2108                 $sqlColumns[$key] = sqlEscapeString($columnName);
2109                 $sqlValues[$key]  = sqlEscapeString($value);
2110
2111                 // Search for it
2112                 $search = key(search_array($columns, 'column', $columnName));
2113
2114                 // Try to handle call-back functions and/or extra values on the list
2115                 //* DEBUG: */ outputHtml($key . '/' . $columnName . '=<pre>'.print_r($columns,true).'</pre>search_array()=<pre>'.print_r(search_array($columns, 'column', $columnName), TRUE).'</pre>');
2116                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
2117                 if (is_string($key)) {
2118                         // Key is a string
2119                         $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key . '_list', $sqlValues[$key], array(''), $search);
2120                 } else {
2121                         // Is a number
2122                         $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key, $sqlValues[$key], array(''), $search);
2123                 }
2124
2125                 // Is the value not a number?
2126                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
2127                 if (($sqlValues[$key] != 'NULL') && (is_string($sqlValues[$key]))) {
2128                         // Add quotes around it
2129                         $sqlValues[$key] = chr(39) . $sqlValues[$key] . chr(39);
2130                 } // END - if
2131
2132                 // Is the value false?
2133                 if ($sqlValues[$key] === FALSE) {
2134                         // One "parser" didn't like it
2135                         $GLOBALS['__XML_PARSE_RESULT'] = FALSE;
2136                         break;
2137                 } // END - if
2138         } // END - foreach
2139
2140         // If all values are okay, continue
2141         if ($sqlValues[$key] !== FALSE) {
2142                 // Build the SQL query
2143                 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`, `', $sqlColumns) . "`) VALUES (" . implode(',', $sqlValues) . ')';
2144
2145                 // Run the SQL query
2146                 sqlQuery($sql, __FUNCTION__, __LINE__);
2147
2148                 // Add id number
2149                 setPostRequestElement('id', getSqlInsertId());
2150
2151                 // Prepare filter data array
2152                 $filterData = array(
2153                         'mode'          => 'add',
2154                         'table_name'    => $tableName,
2155                         'content'       => postRequestArray(),
2156                         'id'            => getSqlInsertId(),
2157                         'subject'       => '',
2158                         // @TODO Used generic 'userid' here
2159                         'userid_column' => array('userid'),
2160                         'raw_userid'    => array('userid'),
2161                         'affected'      => sqlAffectedRows(),
2162                         'sql'           => $sql,
2163                 );
2164
2165                 // Send "build mail" out
2166                 runFilterChain('send_build_mail', $filterData);
2167         } // END - if
2168 }
2169
2170 // Edit rows by given id numbers
2171 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 = '') {
2172         // Is there "time columns"?
2173         if (isFilledArray($timeColumns)) {
2174                 // Then "walk" through all entries
2175                 foreach ($timeColumns as $column) {
2176                         // Convert all (possible) selections
2177                         convertSelectionsToEpocheTimeInPostData($column . '_ye');
2178                 } // END - foreach
2179         } // END - if
2180
2181         // Change them all
2182         $affected = '0';
2183         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2184                 // Secure id number
2185                 $id = bigintval($id);
2186
2187                 // Prepare content array (new values)
2188                 $content = array();
2189
2190                 // Prepare SQL for this row
2191                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
2192                         sqlEscapeString($tableName[0])
2193                 );
2194
2195                 // "Walk" through all entries
2196                 foreach (postRequestArray() as $key => $entries) {
2197                         // Skip raw userid which is always invalid
2198                         if (($key == $rawUserId[0]) || ($key == ($rawUserId[0] . '_raw')) || ($key == 'do_edit')) {
2199                                 // Continue with next field
2200                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
2201                                 continue;
2202                         } // END - if
2203
2204                         // Debug message
2205                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',id=' . $id . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,TRUE).'</pre>');
2206
2207                         // Is entries an array?
2208                         if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
2209                                 // Search for the right array index
2210                                 $search = key(search_array($columns, 'column', $key));
2211
2212                                 // Add this entry to content
2213                                 $content[$key] = $entries[$id];
2214
2215                                 // Debug message
2216                                 //* BUG: */ die($key.'/'.$id.'/'.$search.'=<pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre>');
2217
2218                                 // Handle possible call-back functions and/or extra values
2219                                 $entries[$id] = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries[$id], $userIdColumn, $search);
2220
2221                                 // Add key/value pair to SQL string
2222                                 $sql .= addKeyValueSql($key, $entries[$id]);
2223                         } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
2224                                 // Search for it
2225                                 $search = key(search_array($columns, 'column', $key));
2226                                 //* BUG: */ die($key.'/<pre>'.print_r($search, TRUE).'</pre>=<pre>'.print_r($columns, TRUE).'</pre>');
2227
2228                                 // Debug message
2229                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - BEFORE!');
2230
2231                                 // Add normal entries as well
2232                                 $content[$key] = $entries;
2233
2234                                 // Handle possible call-back functions and/or extra values
2235                                 $entries = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search);
2236
2237                                 // Debug message
2238                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - AFTER!');
2239
2240                                 // Add key/value pair to SQL string
2241                                 $sql .= addKeyValueSql($key, $entries);
2242                         }
2243                 } // END - foreach
2244
2245                 // Finish SQL command
2246                 $sql = substr($sql, 0, -1) . " WHERE `" . sqlEscapeString($idColumn[0]) . "`=" . $id;
2247                 if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2248                         // Add user id as well
2249                         $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2250                 } // END - if
2251                 $sql .= " LIMIT 1";
2252
2253                 // Run this query
2254                 //* BUG: */ die($sql.'<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
2255                 sqlQuery($sql, __FUNCTION__, __LINE__);
2256
2257                 // Add affected rows
2258                 $edited = sqlAffectedRows();
2259                 $affected += $edited;
2260
2261                 // Load all data from that id
2262                 $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2263                         array(
2264                                 $tableName[0],
2265                                 $idColumn[0],
2266                                 $id
2267                         ), __FUNCTION__, __LINE__);
2268
2269                 // Fetch the data and merge it into $content
2270                 $content = merge_array($content, sqlFetchArray($result));
2271
2272                 // Prepare filter data array
2273                 $filterData = array(
2274                         'mode'          => 'edit',
2275                         'table_name'    => $tableName,
2276                         'content'       => $content,
2277                         'id'            => $id,
2278                         'subject'       => $subject,
2279                         'userid_column' => $userIdColumn,
2280                         'raw_userid'    => $rawUserId,
2281                         'affected'      => $edited,
2282                         'sql'           => $sql,
2283                 );
2284
2285                 // Send "build mail" out
2286                 runFilterChain('send_build_mail', $filterData);
2287
2288                 // Free the result
2289                 sqlFreeResult($result);
2290         } // END - foreach
2291
2292         // Delete cache?
2293         if ((isFilledArray($cacheFiles)) && (!empty($cacheFiles[0]))) {
2294                 // Delete cache file(s)
2295                 foreach ($cacheFiles as $cache) {
2296                         // Skip any empty entries
2297                         if (empty($cache)) {
2298                                 // This may cause trouble in loadCacheFile()
2299                                 continue;
2300                         } // END - if
2301
2302                         // Use rebuildCache() to delete it
2303                         rebuildCache($cache);
2304                 } // END - foreach
2305         } // END - if
2306
2307         // Return affected rows
2308         return $affected;
2309 }
2310
2311 // Delete rows by given id numbers
2312 function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2313         // The base SQL command:
2314         $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
2315
2316         // Is a user id provided?
2317         //* BUG: */ die('<pre>'.print_r($rawUserId,TRUE).'</pre><pre>'.print_r($userIdColumn,TRUE).'</pre>');
2318         if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2319                 // Add user id as well
2320                 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2321         } // END - if
2322
2323         // $idColumn[0] in POST must be an array again
2324         if (!is_array(postRequestElement($idColumn[0]))) {
2325                 // This indicates that you have conflicting form field naming with XML names
2326                 reportBug(__FUNCTION__, __LINE__, 'You have a wrong form field element, idColumn[0]=' . $idColumn[0]);
2327         } // END - if
2328
2329         // Delete them all
2330         //* 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>');
2331         $idList = '';
2332         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2333                 // Is id zero?
2334                 if (!isValidId($id)) {
2335                         // Then skip this
2336                         continue;
2337                 } // END - if
2338
2339                 // Is there a userid?
2340                 if (isPostRequestElementSet($userIdColumn[0])) {
2341                         // Load all data from that id
2342                         $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2343                                 array(
2344                                         $tableName[0],
2345                                         $idColumn[0],
2346                                         $id
2347                                 ), __FUNCTION__, __LINE__);
2348
2349                         // Fetch the data
2350                         $content = sqlFetchArray($result);
2351
2352                         // Free the result
2353                         sqlFreeResult($result);
2354
2355                         // Send "build mails" out
2356                         sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
2357                 } // END - if
2358
2359                 // Add id number
2360                 $idList .= $id . ',';
2361         } // END - foreach
2362
2363         // Run the query
2364         sqlQueryEscaped($sql,
2365                 array(
2366                         $tableName[0],
2367                         $idColumn[0],
2368                         convertNullToZero(substr($idList, 0, -1))
2369                 ), __FUNCTION__, __LINE__);
2370
2371         // Return affected rows
2372         return sqlAffectedRows();
2373 }
2374
2375 // Build a special template list
2376 // @TODO cacheFiles is not yet supported
2377 function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2378         // $tableName and $idColumn must bove be arrays!
2379         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2380                 // $tableName is no array
2381                 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2382         } elseif (!is_array($idColumn)) {
2383                 // $idColumn is no array
2384                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2385         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
2386                 // $tableName is no array
2387                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2388         }
2389
2390         // Init row output
2391         $OUT = '';
2392
2393         // "Walk" through all entries
2394         //* 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>');
2395         foreach (postRequestElement($idColumn[0]) as $id => $selected) {
2396                 // Secure id number
2397                 $id = bigintval($id);
2398
2399                 // Get result from a given column array and table name
2400                 $result = getSqlResultFromArray($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
2401
2402                 // Is there one entry?
2403                 if (sqlNumRows($result) == 1) {
2404                         // Load all data
2405                         $row = sqlFetchArray($result);
2406
2407                         // Filter all data
2408                         foreach ($row as $key => $value) {
2409                                 // Search index
2410                                 $idx  = searchXmlArray($key, $columns, 'column');
2411
2412                                 // Default name is NULL
2413                                 $name = NULL;
2414
2415                                 // Is the name there?
2416                                 if (isset($columns[$idx]['name'])) {
2417                                         // Then use it
2418                                         $name = $columns[$idx]['name'];
2419                                 } // END - if
2420
2421                                 // Skip any missing entries
2422                                 if ($idx === FALSE) {
2423                                         // Skip this one
2424                                         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
2425                                         continue;
2426                                 } // END - if
2427
2428                                 // Is there a userid?
2429                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2430                                 if ($key == $userIdColumn[0]) {
2431                                         // Add it again as raw id
2432                                         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2433                                         $row[$userIdColumn[0]] = convertZeroToNull($value);
2434                                         $row[$userIdColumn[0] . '_raw'] = $row[$userIdColumn[0]];
2435                                 } // END - if
2436
2437                                 // If the key matches the idColumn variable, we need to temporary remember it
2438                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
2439                                 if ($key == $idColumn[0]) {
2440                                         /*
2441                                          * Found, so remember it securely (to make sure only id
2442                                          * numbers can pass, don't use alpha-numerical values!)
2443                                          */
2444                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
2445                                         $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
2446                                 } // END - if
2447
2448                                 // Try to handle call-back functions and/or extra values
2449                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',row[' . $key . ']=' . $row[$key]);
2450                                 //if ($key == 'forced_campaign_created') die($idx.'=<pre>'.print_r($columns,true).'</pre><pre>'.print_r($extraValues,true).'</pre>');
2451                                 $row[$key] = doHandleExtraValues($filterFunctions, $extraValues, $idx, $row[$key], $userIdColumn, ((!is_null($name)) ? $name : $key), $id);
2452                         } // END - foreach
2453
2454                         // Then list it
2455                         $OUT .= loadTemplate(sprintf('%s_%s_%s_row',
2456                                 $prefix,
2457                                 $listType,
2458                                 $tableName[0]
2459                                 ), TRUE, $row
2460                         );
2461                 } // END - if
2462
2463                 // Free the result
2464                 sqlFreeResult($result);
2465         } // END - foreach
2466
2467         // Is there an entry in $content?
2468         if (isFilledArray($content)) {
2469                 // Use generic 'rows'
2470                 $content['rows'] = $OUT;
2471         } else {
2472                 // Use direct output
2473                 $content = $OUT;
2474         }
2475
2476         // Load master template
2477         loadTemplate(
2478                 sprintf('%s_%s_%s',
2479                         $prefix,
2480                         $listType,
2481                         $tableName[0]
2482                 ), FALSE, $content
2483         );
2484 }
2485
2486 // Adds key/value pair to a working SQL string together
2487 function addKeyValueSql ($key, $value) {
2488         // Init SQL
2489         $sql = '';
2490
2491         // Is it NULL?
2492         if (($value == 'NULL') || (is_null($value))) {
2493                 // Add key with NULL
2494                 $sql .= sprintf(' `%s`=NULL,',
2495                         sqlEscapeString($key)
2496                 );
2497         } elseif ((is_double($value)) || (is_float($value)) || (is_int($value))) {
2498                 // Is a number, so addd it directly
2499                 $sql .= sprintf(' `%s`=%s,',
2500                         sqlEscapeString($key),
2501                         $value
2502                 );
2503         } else {
2504                 // Else add the value escape'd
2505                 $sql .= sprintf(" `%s`='%s',",
2506                         sqlEscapeString($key),
2507                         sqlEscapeString($value)
2508                 );
2509         }
2510
2511         // Return SQL string
2512         return $sql;
2513 }
2514
2515 // "Getter" for an array from given table and columns
2516 function getArrayFromTable ($tableName, $columns, $orderBy, $ordered = 'ASC', $whereSql = '') {
2517         // The table must exist
2518         assert(ifSqlTableExists($tableName));
2519
2520         // Search for it
2521         $result = sqlQueryEscaped('SELECT
2522         `' . implode('`, `', $columns) . '`
2523 FROM
2524         `{?_MYSQL_PREFIX?}_%s`
2525 ' . $whereSql . '
2526 ORDER BY
2527         `%s` %S',
2528                 array(
2529                         $tableName,
2530                         $orderBy,
2531                         $ordered
2532                 ), __FUNCTION__, __LINE__
2533         );
2534
2535         // Init array
2536         $rows = array();
2537
2538         // Are there entries?
2539         if (!ifSqlHasZeroNums($result)) {
2540                 // Load all entries
2541                 while ($row = sqlFetchArray($result)) {
2542                         array_push($rows, $row);
2543                 } // END - while
2544         } // END - if
2545
2546         // Free result
2547         sqlFreeResult($result);
2548
2549         // Return all found rows
2550         return $rows;
2551 }
2552
2553 // [EOF]
2554 ?>