2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/26/2003 *
4 * =================== Last change: 11/29/2004 *
6 * -------------------------------------------------------------------- *
7 * File : mysql-manager.php *
8 * -------------------------------------------------------------------- *
9 * Short description : All database-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle datenbank-relevanten Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // "Getter" for module description
44 // @TODO Can we cache this?
45 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD = '') {
47 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',what=' . $what . ',column=' . $column . ',add=' . $ADD);
51 $what = getIndexHome();
52 } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
54 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
55 } elseif ($what == 'welcome') {
57 return '{--WHAT_IS_WELCOME--}';
60 // Default is not found
61 $data['title'] = '??? (' . $what . ')';
64 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
69 ), __FUNCTION__, __LINE__);
72 if (SQL_NUMROWS($result) == 1) {
74 $data = SQL_FETCHARRAY($result);
78 SQL_FREERESULT($result);
81 return $data['title'];
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);
95 // First we have to do some analysis...
96 if (substr($file, 0, 7) == 'action-') {
97 // This is an action file!
99 $search = substr($file, 7);
101 // Get access level from it
102 $modCheck = getModuleFromFileName($file, $accessLevel);
105 $ADD = " AND (`what`='' OR `what` IS NULL)";
106 } elseif (substr($file, 0, 5) == 'what-') {
107 // This is a 'what file'!
109 $search = substr($file, 5);
111 // Get access level from it
112 $modCheck = getModuleFromFileName($file, $accessLevel);
114 // Is there admin? Then display all
115 $ADD = " AND `visible`='Y' AND `locked`='N'";
121 $dummy = substr($search, 0, -4);
122 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
123 } elseif ($accessLevel == 'sponsor') {
127 $modCheck = getModule();
132 $modCheck = getModule();
135 // Begin the navigation line
136 if (!isset($GLOBALS['nav_depth'])) {
138 $GLOBALS['nav_depth'] = '0';
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));
144 $prefix = $ret['content'];
146 // Add default content
147 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--} <strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $linkAdd . '%}">Home</a></strong>';
148 } elseif ($return === false) {
150 $GLOBALS['nav_depth']++;
154 $prefix .= ' -> ';
156 // We need to remove .php and the end
157 if (substr($search, -4, 4) == '.php') {
159 $search = substr($search, 0, -4);
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'))) {
166 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&' . $type . '=' . $search . $linkAdd . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
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';
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));
178 // Get content from filter back
179 $OUT = $ret['content'];
181 // Close div-tag, so not the filters have to do it
186 // Return or output HTML code?
187 if ($return === true) {
191 // Output HTML code here
196 // Adds a menu (mode = guest/member/admin/sponsor) to output
197 function addMenu ($mode, $action, $what) {
198 // Init some variables
201 // is the menu action valid?
202 if (!isMenuActionValid($mode, $action, $what, true)) {
203 return getCode('MENU_NOT_VALID');
206 // Non-admin shall not see all menus
207 $ADD = " AND `visible`='Y' AND `locked`='N'";
209 // Is admin, so make all visible
213 // Load SQL data and add the menu to the output stream...
214 $result_main = SQL_QUERY_ESC("SELECT
221 `{?_MYSQL_PREFIX?}_%s_menu`
223 (`what`='' OR `what` IS NULL)
227 array($mode), __FUNCTION__, __LINE__);
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);
238 // Load menu header template
239 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
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`
248 `{?_MYSQL_PREFIX?}_%s_menu`
259 ), __FUNCTION__, __LINE__);
261 // Are there some entries?
262 if (!SQL_HASZERONUMS($result_sub)) {
266 // Load all sub menus
267 while ($content2 = SQL_FETCHARRAY($result_sub)) {
268 // Merge both arrays in one
269 $content = merge_array($content, $content2);
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']))) {
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">';
288 // Regular navigation link
289 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
293 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
297 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
299 if (isIncludeReadable($inc)) {
302 // Mark currently selected menu - close
303 if ((!empty($what)) && (($what == $content['sub_what']))) {
317 'what' => $content['sub_what'],
318 'visible' => $content['sub_visible'],
319 'locked' => $content['locked'],
322 // Add regular menu row or bottom row?
323 if ($count < SQL_NUMROWS($result_sub)) {
324 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
326 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
330 // This is a menu block... ;-)
334 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
335 if (isFileReadable($INC)) {
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());
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);
343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
347 SQL_FREERESULT($result_sub);
352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
353 if (SQL_NUMROWS($result_main) > $main_cnt) {
355 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
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);
362 // Add separator again
363 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
369 SQL_FREERESULT($result_main);
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);
376 // Display advert template
377 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
382 'rows' => $GLOBALS['rows'],
386 // Load main template
387 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
388 loadTemplate('menu_table', false, $content);
392 // Checks whether the current user is a member
393 function isMember () {
394 // By default no member
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();
403 // Is the cache entry there?
404 if (isset($GLOBALS[__FUNCTION__])) {
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.');
413 // Abort further processing
417 // Get userid secured from session
418 setMemberId(getSession('userid'));
420 // ... and set it as currently handled user id
421 setCurrentUserId(getMemberId());
423 // Init user data array
426 // Fix "deleted" cookies
427 fixDeletedCookies(array('userid', 'u_hash'));
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'));
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');
440 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
445 // Is $ret still false?
446 if ($ret === false) {
447 // Yes, so destroy the session
448 destroyMemberSession();
452 $GLOBALS[__FUNCTION__] = $ret;
455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
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
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');
470 // If we should look for userid secure&set it here
471 if (substr($column, -2, 2) == 'id') {
473 $value = bigintval($value);
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.');
481 // Unset cached values if found and different
482 if ((isCurrentUserIdSet()) && (getCurrentUserId() != $value)) {
484 unsetCurrentUserId();
485 } elseif (isUserDataValid()) {
486 // Use cache, so it is fine
487 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
490 } elseif (isUserDataValid()) {
491 // Using cache is fine
492 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
496 // By default none was found
499 // Extra SQL statements
500 $ADD = runFilterChain('convert_user_data_columns', ' ');
502 // Query for the user
503 $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
507 ), __FUNCTION__, __LINE__);
509 // Is there a record?
510 if (SQL_NUMROWS($result) == 1) {
511 // Load data from cookies
512 $data = SQL_FETCHARRAY($result);
514 // Set the userid for later use
515 setCurrentUserId($data['userid']);
517 // And cache the data for this userid
518 $GLOBALS['user_data'][getCurrentUserId()] = $data;
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;
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']);
531 // Seperate data and time again
532 $array['date'] = explode('-', $array[0]);
533 $array['time'] = explode(':', $array[1]);
535 // Now pass it to mktime()
536 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
548 $found = isUserDataValid();
552 SQL_FREERESULT($result);
559 * Checks whether the current session bears a valid admin id and password hash.
561 * This patched function will reduce many SELECT queries for the current admin
564 function isAdmin () {
565 // No admin in installation phase!
566 if ((isInstallationPhase()) || (!isAdminRegistered())) {
573 $passwordFromCookie = '';
575 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
577 // If admin login is not given take current from cookies...
578 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
579 // Get admin login and password from session/cookies
580 $adminId = getCurrentAdminId();
581 $passwordFromCookie = getAdminMd5();
583 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . 'passwordFromCookie=' . $passwordFromCookie);
585 // Abort if admin id is zero
586 if ($adminId == '0') {
587 // A very noisy debug message ...
588 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
595 if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
596 // Init it with failed
597 $GLOBALS[__FUNCTION__][$adminId] = false;
599 // Search in array for entry
600 if (isset($GLOBALS['admin_hash'])) {
602 $valPass = $GLOBALS['admin_hash'];
603 } elseif ((!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
604 // Login data is valid or not?
605 $valPass = encodeHashForCookie(getAdminHash($adminId));
608 $GLOBALS['admin_hash'] = $valPass;
611 incrementStatsEntry('cache_hits');
612 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
613 // Get admin hash and hash it
614 $valPass = encodeHashForCookie(getAdminHash($adminId));
617 $GLOBALS['admin_hash'] = $valPass;
620 if (!empty($valPass)) {
621 // Check if password is valid
622 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passwordFromCookie . ')='.intval($valPass == $passwordFromCookie));
623 $GLOBALS[__FUNCTION__][$adminId] = ($GLOBALS['admin_hash'] == $passwordFromCookie);
627 // Return result of comparision
628 return $GLOBALS[__FUNCTION__][$adminId];
631 // Generates a list of "max receiveable emails per day"
632 function addMaxReceiveList ($mode, $default = '') {
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__);
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__);
651 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
655 // Some entries are found?
656 if (!SQL_HASZERONUMS($result)) {
658 while ($content = SQL_FETCHARRAY($result)) {
659 $OUT .= ' <option value="' . $content['value'] . '"';
661 if (postRequestElement('max_mails') == $content['value']) {
662 $OUT .= ' selected="selected"';
665 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
666 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
671 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
673 // Maybe the admin has to setup some maximum values?
674 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
678 SQL_FREERESULT($result);
680 // Return generated HTML code
684 // Checks whether the given email address is used.
685 function isEmailTaken ($email) {
686 // Default is no userid
687 $useridSql = ' IS NOT NULL';
689 // Is a member logged in?
692 $useridSql = '!= ' . bigintval(getMemberId());
695 // Replace dot with {DOT}
696 $email = str_replace('.', '{DOT}', $email);
698 // Query the database
699 $result = SQL_QUERY_ESC("SELECT
700 COUNT(`userid`) AS `cnt`
702 `{?_MYSQL_PREFIX?}_user_data`
704 '%s' REGEXP `email` AND
710 ), __FUNCTION__, __LINE__);
712 // Is the email there?
713 list($count) = SQL_FETCHROW($result);
716 SQL_FREERESULT($result);
719 return ($count == 1);
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)) {
727 incrementStatsEntry('cache_hits');
729 // Then use this cache
730 return $GLOBALS['action_valid'][$mode][$action][$what];
733 // By default nothing is valid
736 // Look in all menus or only unlocked
738 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
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",
748 ), __FUNCTION__, __LINE__, false);
749 } elseif (($what != 'welcome') && (!empty($what))) {
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",
756 ), __FUNCTION__, __LINE__, false);
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",
763 ), __FUNCTION__, __LINE__, false);
767 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
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());
775 $ret = (!SQL_HASZERONUMS($result));
779 SQL_FREERESULT($result);
782 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
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);
792 $data['action'] = '';
794 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
795 // 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();
802 if ($module == 'admin') {
803 // Action value for admin area
804 if (isGetRequestElementSet('action')) {
806 return getRequestElement('action');
807 } elseif (isActionSet()) {
808 // Get it directly from URL
810 } elseif (($what == 'welcome') || (!isWhatSet())) {
811 // Default value for admin area
812 $data['action'] = 'login';
814 } elseif (isActionSet()) {
815 // Get it directly from URL
818 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
820 // Does the module have a menu?
821 if (ifModuleHasMenu($module)) {
822 // Rewriting modules to menu
823 $module = mapModuleToTable($module);
825 // Guest and member menu is 'main' as the default
826 if (empty($data['action'])) {
827 $data['action'] = 'main';
830 // Load from database
831 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
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);
842 SQL_FREERESULT($result);
843 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
844 // No sql_patches installed, but maybe we need to register an admin?
845 if (isAdminRegistered()) {
846 // Redirect to admin area
847 redirectToUrl('admin.php');
851 // Return action value
852 return $data['action'];
855 // Get category name back
856 function getCategory ($cid) {
857 // Default is not found
858 $data['cat'] = '{--_CATEGORY_404--}';
860 // Is the category id set?
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);
874 SQL_FREERESULT($result);
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');
887 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
894 // "Getter" for payment data (cached)
895 function getPaymentData ($paymentsId, $lookFor = 'price') {
897 $data[$lookFor] = NULL;
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];
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',
911 bigintval($paymentsId)
912 ), __FUNCTION__, __LINE__);
914 // Is the entry there?
915 if (SQL_NUMROWS($result) == 1) {
916 // Payment type found... :-)
917 $data = SQL_FETCHARRAY($result);
921 SQL_FREERESULT($result);
925 return $data[$lookFor];
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
933 // Is the userid valid?
934 if (isValidUserId($userid)) {
935 // Remove entry from array
936 unset($receivers[$key]);
938 // Is there already a line for this user available?
940 // Default is 'normal' mail
942 $rowName = 'stats_id';
944 // Only when we got a real stats id continue searching for the entry
945 if ($isBonusMail === true) {
947 $rowName = 'bonus_id';
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",
957 ), __FUNCTION__, __LINE__);
959 // Was it *not* found?
960 if (SQL_HASZERONUMS($result)) {
962 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES (%s,%s,'%s')",
968 ), __FUNCTION__, __LINE__);
970 // Update 'mails_sent' if sql_patches is updated
971 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
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__);
983 SQL_FREERESULT($result);
987 // Return status for sending routine
991 // Calculate sum (default) or count records of given criteria
992 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '', $mode = '=') {
996 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
997 if ((empty($search)) && ($search != '0')) {
998 // Count or sum whole table?
999 if ($countRows === true) {
1000 // Count whole table
1001 $result = SQL_QUERY_ESC('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1005 ), __FUNCTION__, __LINE__);
1008 $result = SQL_QUERY_ESC('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1012 ), __FUNCTION__, __LINE__);
1014 } elseif (($countRows === true) || ($lookFor == 'userid')) {
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',
1024 ), __FUNCTION__, __LINE__);
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',
1035 ), __FUNCTION__, __LINE__);
1039 $data = SQL_FETCHARRAY($result);
1042 SQL_FREERESULT($result);
1045 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1047 $data['res'] = '0.00000';
1048 } elseif (''.$data['res'].'' == '') {
1054 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1055 return $data['res'];
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
1062 function sendAdminEmails ($subject, $message, $isBugReport = false) {
1063 // Default is no special header
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' . chr(10);
1072 // Load all admin email addresses
1073 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
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);
1082 SQL_FREERESULT($result);
1084 // Really simple... ;-)
1087 // Get id number from administrator's login name
1088 function getAdminId ($adminLogin) {
1089 // By default no admin is found
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];
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__);
1104 // Is there an entry?
1105 if (SQL_NUMROWS($result) == 1) {
1107 $data = SQL_FETCHARRAY($result);
1111 SQL_FREERESULT($result);
1118 // "Getter" for current admin id
1119 function getCurrentAdminId () {
1120 // Log debug message
1121 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1124 if (!isset($GLOBALS['current_admin_id'])) {
1125 // Get the admin login from session
1126 $adminId = getSession('admin_id');
1128 // Remember in cache securely
1129 setCurrentAdminId(bigintval($adminId));
1133 return $GLOBALS['current_admin_id'];
1136 // Setter for current admin id
1137 function setCurrentAdminId ($currentAdminId) {
1139 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1142 // Get password hash from administrator's login name
1143 function getAdminHash ($adminId) {
1144 // By default an invalid hash is returned
1145 $data['password'] = -1;
1147 if (isAdminHashSet($adminId)) {
1149 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1151 // Update cache hits
1152 incrementStatsEntry('cache_hits');
1153 } elseif (!isExtensionActive('cache')) {
1154 // Load from database
1155 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1156 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1158 // Is there an entry?
1159 if (SQL_NUMROWS($result) == 1) {
1161 $data = SQL_FETCHARRAY($result);
1164 setAdminHash($adminId, $data['password']);
1168 SQL_FREERESULT($result);
1171 // Return password hash
1172 return $data['password'];
1175 // "Getter" for admin login
1176 function getAdminLogin ($adminId) {
1177 // By default a non-existent login is returned (other functions react on this!)
1178 $data['login'] = '***';
1180 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1182 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1184 // Update cache hits
1185 incrementStatsEntry('cache_hits');
1186 } elseif (!isExtensionActive('cache')) {
1187 // Load from database
1188 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1189 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1192 if (SQL_NUMROWS($result) == 1) {
1194 $data = SQL_FETCHARRAY($result);
1197 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1201 SQL_FREERESULT($result);
1204 // Return the result
1205 return $data['login'];
1208 // Get email address of admin id
1209 function getAdminEmail ($adminId) {
1210 // By default an invalid emails is returned
1211 $data['email'] = '***';
1213 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1215 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1217 // Update cache hits
1218 incrementStatsEntry('cache_hits');
1219 } elseif (!isExtensionActive('cache')) {
1220 // Load from database
1221 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1222 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1225 if (SQL_NUMROWS($result_admin_id) == 1) {
1227 $data = SQL_FETCHARRAY($result_admin_id);
1230 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1234 SQL_FREERESULT($result_admin_id);
1238 return $data['email'];
1241 // Get default ACL of admin id
1242 function getAdminDefaultAcl ($adminId) {
1243 // By default an invalid ACL value is returned
1244 $data['default_acl'] = 'NO-ACL';
1246 // Is sql_patches there and was it found in cache?
1247 if (!isExtensionActive('sql_patches')) {
1248 // Not found, which is bad, so we need to allow all
1249 $data['default_acl'] = 'allow';
1250 } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1252 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1254 // Update cache hits
1255 incrementStatsEntry('cache_hits');
1256 } elseif (!isExtensionActive('cache')) {
1257 // Load from database
1258 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1259 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1261 // Is there an entry?
1262 if (SQL_NUMROWS($result_admin_id) == 1) {
1264 $data = SQL_FETCHARRAY($result_admin_id);
1267 $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1271 SQL_FREERESULT($result_admin_id);
1274 // Return default ACL
1275 return $data['default_acl'];
1278 // Get menu mode (la_mode) of admin id
1279 function getAdminMenuMode ($adminId) {
1280 // By default an invalid mode
1281 $data['la_mode'] = 'INVALID';
1283 // Is sql_patches there and was it found in cache?
1284 if (!isExtensionActive('sql_patches')) {
1285 // Not found, which is bad, so we need to allow all
1286 $data['la_mode'] = 'global';
1287 } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1289 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1291 // Update cache hits
1292 incrementStatsEntry('cache_hits');
1293 } elseif (!isExtensionActive('cache')) {
1294 // Load from database
1295 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1296 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1298 // Is there an entry?
1299 if (SQL_NUMROWS($result_admin_id) == 1) {
1301 $data = SQL_FETCHARRAY($result_admin_id);
1304 $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1308 SQL_FREERESULT($result_admin_id);
1311 // Return default ACL
1312 return $data['la_mode'];
1315 // Generates an option list from various parameters
1316 function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '') {
1318 if ($table == '/ARRAY/') {
1319 // Selection from array
1320 if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
1322 foreach ($key as $idx => $optionValue) {
1323 $ret .= '<option value="' . $optionValue . '"';
1324 if ($default == $optionValue) {
1325 // Selected by default
1326 $ret .= ' selected="selected"';
1327 } elseif (isset($disabled[$optionValue])) {
1329 $ret .= ' disabled="disabled"';
1332 // Is the call-back function set?
1333 if (!empty($callback)) {
1335 $value[$idx] = call_user_func_array($callback, array($key[$idx]));
1338 // Finish option tag
1339 $ret .= '>' . $value[$idx] . '</option>';
1342 // Problem in request
1343 reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: key[' . count($key) . ']=' . gettype($key) . ',value[' . count($value) . ']=' . gettype($value) . ',callback=' . $callback);
1346 ///////////////////////
1347 // Data from database /
1348 ///////////////////////
1350 // Init extra column (if requested)
1352 if (!empty($extra)) {
1353 $extraColumn = ',`' . $extra . '` AS `extra`';
1357 $result = SQL_QUERY_ESC("SELECT `%s` AS `key`,`%s` AS `value`" . $extraColumn . " FROM `{?_MYSQL_PREFIX?}_%s` " . $whereStatement . " ORDER BY `%s` ASC",
1363 ), __FUNCTION__, __LINE__);
1366 if (!SQL_HASZERONUMS($result)) {
1367 // Found data so add them as OPTION lines
1368 while ($content = SQL_FETCHARRAY($result)) {
1370 if (!isset($content['extra'])) {
1372 $content['extra'] = '';
1375 $ret .= '<option value="' . $content['key'] . '"';
1377 if ($default == $content['key']) {
1378 // Selected by default
1379 $ret .= ' selected="selected"';
1380 } elseif (isset($disabled[$content['key']])) {
1382 $ret .= ' disabled="disabled"';
1386 if (!empty($content['extra'])) {
1387 $content['extra'] = ' (' . $content['extra'] . ')';
1390 // Is the call-back function set?
1391 if (!empty($callback)) {
1393 $content['value'] = call_user_func_array($callback, array($content['value']));
1396 // Finish option list
1397 $ret .= '>' . $content['value'] . $content['extra'] . '</option>';
1401 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1405 SQL_FREERESULT($result);
1408 // Return - hopefully - the requested data
1412 // Deletes a user account with given reason
1413 function deleteUserAccount ($userid, $reason) {
1415 $data['points'] = '0';
1417 // Search for the points and user data
1418 $result = SQL_QUERY_ESC("SELECT
1419 (SUM(p.`points`) - d.`used_points`) AS `points`
1421 `{?_MYSQL_PREFIX?}_user_points` AS p
1423 `{?_MYSQL_PREFIX?}_user_data` AS d
1425 p.`userid`=d.`userid`
1429 array(bigintval($userid)), __FUNCTION__, __LINE__);
1431 // Is there an entry?
1432 if (SQL_NUMROWS($result) == 1) {
1433 // Save his points to add them to the jackpot
1434 $data = SQL_FETCHARRAY($result);
1436 // Delete points entries as well
1437 // @TODO Rewrite these lines to a filter
1438 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1439 array(bigintval($userid)), __FUNCTION__, __LINE__);
1441 // Update mediadata as well
1442 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1444 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1447 // Now, when we have all his points adds them do the jackpot!
1448 if (isExtensionActive('jackpot')) {
1449 addPointsToJackpot($data['points']);
1454 SQL_FREERESULT($result);
1456 // Delete category selections as well...
1457 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1458 array(bigintval($userid)), __FUNCTION__, __LINE__);
1460 // Remove from rallye if found
1461 // @TODO Rewrite this to a filter
1462 if (isExtensionActive('rallye')) {
1463 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1464 array(bigintval($userid)), __FUNCTION__, __LINE__);
1467 // Add reason and translate points
1468 $data['text'] = $reason;
1470 // Now a mail to the user and that's all...
1471 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1472 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1474 // Ok, delete the account!
1475 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1478 // Gets the matching what name from module
1479 function getWhatFromModule ($modCheck) {
1480 // Is the request element set?
1481 if (isGetRequestElementSet('what')) {
1482 // Then return this!
1483 return getRequestElement('what');
1489 // Check on given module
1490 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1491 switch ($modCheck) {
1492 case 'index': // Guest area
1493 // Is ext-sql_patches installed and newer than 0.0.5?
1494 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1495 // Use it from config
1496 $what = getIndexHome();
1498 // Use default 'welcome'
1503 default: // Default for all other menus (getIndexHome() is for index module only)
1508 // Return what value
1512 // Returns HTML code with an option list of all categories
1513 function generateCategoryOptionsList ($mode, $userid = NULL) {
1514 // Prepare WHERE statement
1515 $whereStatement = " WHERE `visible`='Y'";
1516 if (isAdmin()) $whereStatement = '';
1518 // Initialize array...
1519 $categories = array(
1522 'userids' => array()
1526 $result = SQL_QUERY('SELECT
1530 `{?_MYSQL_PREFIX?}_cats`
1531 ' . $whereStatement . '
1534 __FUNCTION__, __LINE__);
1536 // Are there entries?
1537 if (!SQL_HASZERONUMS($result)) {
1538 // ... and begin loading stuff
1539 while ($content = SQL_FETCHARRAY($result)) {
1540 // Transfer some data
1541 $categories['id'][] = $content['id'];
1542 array_push($categories['name'], $content['cat']);
1544 // Check which users are in this category
1545 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1547 bigintval($content['id']),
1548 convertNullToZero($userid)
1549 ), __FUNCTION__, __LINE__);
1555 while ($data = SQL_FETCHARRAY($result_userids)) {
1557 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1561 SQL_FREERESULT($result_userids);
1564 array_push($categories['userids'], $userid_cnt);
1568 SQL_FREERESULT($result);
1572 foreach ($categories['id'] as $key => $value) {
1573 $OUT .= ' <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1576 // No cateogries are defined yet
1577 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1584 // Add bonus mail to queue
1585 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1586 // Is admin or bonus extension there?
1590 } elseif (!isExtensionActive('bonus')) {
1595 // Calculcate target sent
1596 $target = countSelection(explode(';', $receiverList));
1598 // Receiver is zero?
1599 if ($receiver == '0') {
1601 $receiver = $target;
1604 // HTML extension active?
1605 if (isExtensionActive('html_mail')) {
1607 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1639 bigintval($seconds),
1641 bigintval($categoryId),
1643 bigintval($receiver),
1644 convertBooleanToYesNo($mode == 'html')
1645 ), __FUNCTION__, __LINE__);
1648 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1678 bigintval($seconds),
1680 bigintval($categoryId),
1682 bigintval($receiver),
1683 ), __FUNCTION__, __LINE__);
1687 // Generate a receiver list for given category and maximum receivers
1688 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1695 $categoryId = bigintval($categoryId);
1696 $receiver = bigintval($receiver);
1698 // Is the receiver zero and mode set?
1699 if (($receiver == '0') && (!empty($mode))) {
1700 // Auto-fix receiver maximum
1701 $receiver = getTotalReceivers($mode);
1704 // Exclude (maybe exclude) testers
1705 $addWhere = runFilterChain('user_exclusion_sql', ' ');
1708 if ($categoryId > 0) {
1710 $extraColumns = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1711 $addWhere = sprintf(" AND c.`cat_id`=%s", $categoryId);
1714 // Exclude users in holiday?
1715 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1716 // Add something for the holiday extension
1717 $addWhere .= " AND d.`holiday_active`='N'";
1720 // Include only HTML recipients?
1721 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1722 $addWhere .= " AND d.`html`='Y'";
1726 $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",
1729 ), __FUNCTION__, __LINE__);
1732 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1734 while ($content = SQL_FETCHARRAY($result)) {
1735 // Add receiver when not empty
1736 if (!empty($content['userid'])) {
1737 $receiverList .= $content['userid'] . ';';
1742 SQL_FREERESULT($result);
1744 // Remove trailing semicolon
1745 $receiverList = substr($receiverList, 0, -1);
1749 return $receiverList;
1752 // Recuce the amount of received emails for the receipients for given email
1753 function reduceRecipientReceivedMails ($column, $id, $count) {
1754 // Search for mail in database
1755 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1756 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1758 // Are there entries?
1759 if (!SQL_HASZERONUMS($result)) {
1760 // Now load all userids for one big query!
1762 while ($data = SQL_FETCHARRAY($result)) {
1763 // By default we want to reduce and have no mails found
1766 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1767 // @TODO Rewrite this to a filter
1768 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1770 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1771 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1773 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1776 // Reduce this users total received emails?
1778 $userids[$data['userid']] = $data['userid'];
1782 if (count($userids) > 0) {
1783 // Now update all user accounts
1784 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1785 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1788 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1793 SQL_FREERESULT($result);
1796 // Creates a new task
1797 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = true) {
1798 // Insert the task data into the database
1799 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())",
1801 convertZeroToNull($adminId),
1802 convertZeroToNull($userid),
1806 ), __FUNCTION__, __LINE__, true, $strip);
1808 // Return insert id which is the task id
1809 return SQL_INSERTID();
1812 // Updates last module / online time
1813 function updateLastActivity($userid) {
1816 // Run the update query
1817 SQL_QUERY_ESC("UPDATE
1818 `{?_MYSQL_PREFIX?}_user_data`
1821 `last_online`=UNIX_TIMESTAMP(),
1827 getUserLastWhatName(),
1831 ), __FUNCTION__, __LINE__);
1833 // No what set, needs to be ignored (last_module is last_what)
1834 SQL_QUERY_ESC("UPDATE
1835 `{?_MYSQL_PREFIX?}_user_data`
1838 `last_online`=UNIX_TIMESTAMP(),
1844 getUserLastWhatName(),
1847 ), __FUNCTION__, __LINE__);
1851 // List all given rows (callback function from XML)
1852 function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array()) {
1853 // Verify that tableName and columns are not empty
1854 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1855 // No tableName specified
1856 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1857 } elseif (count($columns) == 0) {
1858 // No columns specified
1859 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1862 // This is the minimum query, so at least columns and tableName must have entries
1865 // Get the sql part back from given array
1866 $SQL .= getSqlPartFromXmlArray($columns);
1868 // Remove last commata and add FROM statement
1869 $SQL .= ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1871 // Are there entries from whereColumns to add?
1872 if (count($whereColumns) > 0) {
1873 // Then add these as well
1874 if (count($whereColumns) == 1) {
1878 // Table/alias included?
1879 if (!empty($whereColumns[0]['table'])) {
1881 $SQL .= $whereColumns[0]['table'] . '.';
1885 $SQL .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
1886 } elseif ((count($whereColumns > 1)) && (count($conditions) > 0)) {
1887 // More than one "WHERE" + condition found
1888 foreach ($whereColumns as $idx => $columnArray) {
1890 $condition = 'WHERE';
1892 // Is the condition element there?
1893 if (isset($conditions[$columnArray['column']])) {
1894 // Assume the condition
1895 $condition = $conditions[$columnArray['column']];
1899 $SQL .= ' ' . $condition;
1901 // Table/alias included?
1902 if (!empty($whereColumns[$idx]['table'])) {
1904 $SQL .= $whereColumns[$idx]['table'] . '.';
1908 $SQL .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
1911 // Did not set $conditions
1912 reportBug(__FUNCTION__, __LINE__, 'Supplied more than "whereColumns" entries but no conditions! Please fix your XML template.');
1916 // Are there entries from orderByColumns to add?
1917 if (count($orderByColumns) > 0) {
1919 $SQL .= ' ORDER BY ';
1920 foreach ($orderByColumns as $orderByColumn => $array) {
1921 // Get keys (table/alias) and values (sorting itself)
1922 $table = trim(implode('', array_keys($array)));
1923 $sorting = trim(implode('', array_keys($array)));
1925 // table/alias can be omitted
1926 if (!empty($table)) {
1927 // table/alias is given
1928 $SQL .= $table . '.';
1931 // Add order-by column
1932 $SQL .= '`' . $orderByColumn . '` ' . $sorting . ',';
1935 // Remove last column
1936 $SQL = substr($SQL, 0, -1);
1939 // Now handle all over to the inner function which will execute the listing
1940 doListEntries($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters);
1943 // Do the listing of entries
1944 function doListEntries ($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array()) {
1945 // Run the SQL query
1946 $result = SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1948 // Are there some URLs left?
1949 if (!SQL_HASZERONUMS($result)) {
1952 while ($content = SQL_FETCHARRAY($result)) {
1953 // "Translate" content
1954 foreach ($callbackColumns as $columnName => $callbackName) {
1955 // Fill the callback arguments
1956 $args = array($content[$columnName]);
1958 // Is there more to add?
1959 if (isset($extraParameters[$columnName])) {
1961 $args = merge_array($args, $extraParameters[$columnName]);
1964 // Call the callback-function
1965 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, true).'</pre>');
1966 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1967 $content[$columnName] = call_user_func_array($callbackName, $args);
1970 // Load row template
1971 $OUT .= loadTemplate(trim($rowTemplate[0]), true, $content);
1974 // Load main template
1975 loadTemplate(trim($tableTemplate[0]), false, $OUT);
1977 // No URLs in surfbar
1978 displayMessage('{--' .$noEntryMessageId[0] . '--}');
1982 SQL_FREERESULT($result);
1985 // Adds a given entry to the database
1986 function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1987 //* DEBUG: */ die('columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,POST=<pre>'.print_r($_POST,true).'</pre>');
1988 // Verify that tableName and columns are not empty
1989 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1990 // No tableName specified
1991 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1992 } elseif (count($columns) == 0) {
1993 // No columns specified
1994 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
1997 // Init columns and value elements
1998 $sqlColumns = array();
1999 $sqlValues = array();
2001 // Default is that all went fine
2002 $GLOBALS['__XML_PARSE_RESULT'] = true;
2004 // Is there "time columns"?
2005 if (count($timeColumns) > 0) {
2006 // Then "walk" through all entries
2007 foreach ($timeColumns as $column) {
2008 // Convert all (possible) selections
2009 convertSelectionsToEpocheTimeInPostData($column . '_ye');
2013 // Add columns and values
2014 foreach ($columns as $key => $columnName) {
2015 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
2016 // Is columnIndex set?
2017 if (!is_null($columnIndex)) {
2019 //* DEBUG: */ die('columnIndex=<pre>'.print_r($columnIndex,true).'</pre>'.debug_get_printable_backtrace());
2020 assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
2022 // Then use that index "blindly"
2023 $columnName = $columnName[$columnIndex];
2027 //* 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'])) . '<br />');
2029 // Copy entry securely to the final arrays
2030 $sqlColumns[$key] = SQL_ESCAPE($columnName);
2031 $sqlValues[$key] = SQL_ESCAPE(postRequestElement($columnName));
2033 // Send data through the filter function if found
2034 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key . '_list']))) {
2035 // Filter function set!
2036 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
2037 $sqlValues[$key] = call_user_func_array($filterFunctions[$key], merge_array(array($columnName), $extraValues[$key . '_list']));
2038 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
2039 } elseif ((isset($filterFunctions[$key])) && (!empty($filterFunctions[$key]))) {
2040 // Run through an extra filter
2041 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
2042 $sqlValues[$key] = handleExtraValues($filterFunctions[$key], $sqlValues[$key], '');
2043 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
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);
2053 // Is the value false?
2054 if ($sqlValues[$key] === false) {
2055 // One "parser" didn't like it
2056 $GLOBALS['__XML_PARSE_RESULT'] = false;
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) . ')';
2066 // Run the SQL query
2067 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2070 setPostRequestElement('id', SQL_INSERTID());
2072 // Prepare filter data array
2073 $filterData = array(
2075 'table_name' => $tableName,
2076 'content' => postRequestArray(),
2077 'id' => SQL_INSERTID(),
2079 // @TODO Used generic 'userid' here
2080 'userid_column' => array('userid'),
2081 'raw_userid' => array('userid'),
2082 'affected' => SQL_AFFECTEDROWS(),
2086 // Send "build mail" out
2087 runFilterChain('send_build_mail', $filterData);
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()) {
2095 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2096 // Prepare content array (new values)
2099 // Prepare SQL for this row
2100 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
2101 SQL_ESCAPE($tableName[0])
2104 // "Walk" through all entries
2105 foreach (postRequestArray() as $key => $entries) {
2106 // Skip raw userid which is always invalid
2107 if ($key == $rawUserId[0]) {
2108 // Continue with next field
2109 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
2114 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,true).'</pre>');
2116 // Is entries an array?
2117 if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
2118 // Add this entry to content
2119 $content[$key] = $entries[$id];
2121 // Send data through the filter function if found
2122 if ($key == $userIdColumn[0]) {
2123 // Is the userid, we have to process it with convertZeroToNull()
2124 $entries[$id] = convertZeroToNull($entries[$id]);
2125 } elseif ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
2126 // Filter function set!
2127 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
2130 // Is the value NULL?
2131 if ($entries[$id] == 'NULL') {
2133 $sql .= sprintf(' `%s`=NULL,',
2137 // Else add the value covered
2138 $sql .= sprintf(" `%s`='%s',",
2140 SQL_ESCAPE($entries[$id])
2143 } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
2144 // Add normal entries as well!
2145 $content[$key] = $entries;
2149 // Finish SQL command
2150 $sql = substr($sql, 0, -1) . " WHERE `" . SQL_ESCAPE($idColumn[0]) . "`=" . bigintval($id);
2151 if ((isset($rawUserId[0])) && (isPostRequestElementSet($rawUserId[0])) && (isset($userIdColumn[0]))) {
2152 // Add user id as well
2153 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2158 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2160 // Add affected rows
2161 $edited = SQL_AFFECTEDROWS();
2162 $affected += $edited;
2164 // Load all data from that id
2165 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2170 ), __FUNCTION__, __LINE__);
2172 // Fetch the data and merge it into $content
2173 $content = merge_array($content, SQL_FETCHARRAY($result));
2175 // Prepare filter data array
2176 $filterData = array(
2178 'table_name' => $tableName,
2179 'content' => $content,
2182 'userid_column' => $userIdColumn,
2183 'raw_userid' => $rawUserId,
2184 'affected' => $edited,
2188 // Send "build mail" out
2189 runFilterChain('send_build_mail', $filterData);
2192 SQL_FREERESULT($result);
2196 if ((count($cacheFiles) > 0) && (!empty($cacheFiles[0]))) {
2197 // Delete cache file(s)
2198 foreach ($cacheFiles as $cache) {
2199 // Skip any empty entries
2200 if (empty($cache)) {
2201 // This may cause trouble in loadCacheFile()
2205 // Is the cache file loadable?
2206 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2208 $GLOBALS['cache_instance']->removeCacheFile();
2213 // Return affected rows
2217 // Delete rows by given id numbers
2218 function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2219 // The base SQL command:
2220 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
2222 // Is a user id provided?
2223 //* BUG: */ die('<pre>'.print_r($rawUserId,true).'</pre><pre>'.print_r($userIdColumn,true).'</pre>');
2224 if ((isset($rawUserId[0])) && (isPostRequestElementSet($rawUserId[0])) && (isset($userIdColumn[0]))) {
2225 // Add user id as well
2226 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2230 //* BUG: */ die($sql.'<br /><pre>'.print_r($idColumn,true).'</pre>');
2232 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2239 // Is there a userid?
2240 if (isPostRequestElementSet($userIdColumn[0])) {
2241 // Load all data from that id
2242 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2247 ), __FUNCTION__, __LINE__);
2250 $content = SQL_FETCHARRAY($result);
2253 SQL_FREERESULT($result);
2255 // Send "build mails" out
2256 sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
2260 $idList .= $id . ',';
2268 convertNullToZero(substr($idList, 0, -1))
2269 ), __FUNCTION__, __LINE__);
2271 // Return affected rows
2272 return SQL_AFFECTEDROWS();
2275 // Build a special template list
2276 function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
2277 // $tableName and $idColumn must bove be arrays!
2278 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2279 // $tableName is no array
2280 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2281 } elseif (!is_array($idColumn)) {
2282 // $idColumn is no array
2283 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2284 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
2285 // $tableName is no array
2286 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2292 // "Walk" through all entries
2293 //* 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>');
2294 foreach (postRequestElement($idColumn[0]) as $id => $selected) {
2296 $id = bigintval($id);
2298 // Get result from a given column array and table name
2299 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
2301 // Is there one entry?
2302 if (SQL_NUMROWS($result) == 1) {
2304 $content = SQL_FETCHARRAY($result);
2307 foreach ($content as $key => $value) {
2309 $idx = searchXmlArray($key, $columns, 'column');
2311 // Skip any missing entries
2312 if ($idx === false) {
2314 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
2318 // Is there a userid?
2319 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2320 if ($key == $userIdColumn[0]) {
2321 // Add it again as raw id
2322 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2323 $content[$userIdColumn[0]] = convertZeroToNull($value);
2324 $content[$userIdColumn[0] . '_raw'] = $content[$userIdColumn[0]];
2327 // If the key matches the idColumn variable, we need to temporary remember it
2328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
2329 if ($key == $idColumn[0]) {
2331 * Found, so remember it securely (to make sure only id
2332 * numbers can pass, don't use alpha-numerical values!)
2334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
2335 $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
2338 // Is there a call-back function and extra-value pair?
2339 if ((isset($filterFunctions[$idx])) && (isset($extraValues[$idx]))) {
2340 // Handle the call in external function
2341 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value);
2342 $content[$key] = handleExtraValues(
2343 $filterFunctions[$idx],
2347 } elseif ((isset($columns[$idx]['name'])) && (isset($filterFunctions[$columns[$idx]['name']])) && (isset($extraValues[$columns[$idx]['name']]))) {
2348 // Handle the call in external function
2349 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',fucntion=' . $filterFunctions[$columns[$idx]['name']] . ',value=' . $value);
2350 $content[$key] = handleExtraValues(
2351 $filterFunctions[$columns[$idx]['name']],
2353 $extraValues[$columns[$idx]['name']]
2359 $OUT .= loadTemplate(sprintf("%s_%s_%s_row",
2368 SQL_FREERESULT($result);
2371 // Load master template
2372 loadTemplate(sprintf("%s_%s_%s",
2380 // Checks whether given URL is blacklisted
2381 function isUrlBlacklisted ($url) {
2382 // Mark it as not listed by default
2385 // Is black-listing enbaled?
2386 if (!isUrlBlacklistEnabled()) {
2387 // No, then all URLs are not in this list
2389 } elseif (!isset($GLOBALS['blacklist_data'][$url])) {
2390 // Check black-list for given URL
2391 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`timestamp`) AS `blist_timestamp` FROM `{?_MYSQL_PREFIX?}_url_blacklist` WHERE `url`='%s' LIMIT 1",
2392 array($url), __FILE__, __LINE__);
2394 // Is there an entry?
2395 if (SQL_NUMROWS($result) == 1) {
2396 // Jupp, we got one listed
2397 $GLOBALS['blacklist_data'][$url] = SQL_FETCHARRAY($result);
2399 // Mark it as listed
2404 SQL_FREERESULT($result);
2406 // Is found in cache -> black-listed