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