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, 2010 by Mailer Developer Team *
20 * For more information visit: http://www.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='') {
48 $what = getIndexHome();
51 // Default is not found
52 $data['title'] = '??? (' . $what . ')';
55 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
60 ), __FUNCTION__, __LINE__);
63 if (SQL_NUMROWS($result) == 1) {
65 $data = SQL_FETCHARRAY($result);
69 SQL_FREERESULT($result);
72 return $data['title'];
75 // Add link into output stream (or return it) for 'You Are Here' navigation
76 function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
77 // Use only filename of the FQFN...
78 $file = basename($FQFN);
86 // First we have to do some analysis...
87 if (substr($file, 0, 7) == 'action-') {
88 // This is an action file!
90 $search = substr($file, 7);
92 // Get access level from it
93 $modCheck = getModuleFromFileName($file, $accessLevel);
96 $ADD = " AND (`what`='' OR `what` IS NULL)";
97 } elseif (substr($file, 0, 5) == 'what-') {
98 // This is a 'what file'!
100 $search = substr($file, 5);
101 $ADD = " AND `visible`='Y' AND `locked`='N'";
103 // Get access level from it
104 $modCheck = getModuleFromFileName($file, $accessLevel);
106 // Do we have admin? Then display all
107 if (isAdmin()) $ADD = '';
109 $dummy = substr($search, 0, -4);
110 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
111 } elseif (($accessLevel == 'sponsor') || ($accessLevel == 'engine')) {
112 // Sponsor / engine menu
115 $modCheck = getModule();
121 $modCheck = getModule();
125 // Begin the navigation line
126 if (!isset($GLOBALS['nav_depth'])) {
128 $GLOBALS['nav_depth'] = '0';
130 // Run the pre-filter chain
131 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
134 $prefix = $ret['content'];
136 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--} <strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $LINK_ADD . '%}">Home</a></strong>';
137 } elseif ($return === false) {
139 $GLOBALS['nav_depth']++;
142 $prefix .= ' -> ';
144 // We need to remove .php and the end
145 if (substr($search, -4, 4) == '.php') {
147 $search = substr($search, 0, -4);
150 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
152 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&' . $type . '=' . $search . $LINK_ADD . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
154 // Can we close the you-are-here navigation?
155 //* DEBUG: */ debugOutput(__LINE__.'*'.$type.'/'.getWhat().'*');
156 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
157 //* DEBUG: */ debugOutput(__LINE__.'+'.$type.'+');
158 // Add closing div and br-tag
160 $GLOBALS['nav_depth'] = '0';
162 // Run the post-filter chain
163 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
165 // Add additional content
166 $OUT .= $ret['content'];
170 // Return or output HTML code?
171 if ($return === true) {
175 // Output HTML code here
180 // Adds a menu (mode = guest/member/admin/sponsor) to output
181 function addMenu ($mode, $action, $what) {
182 // Init some variables
186 // is the menu action valid?
187 if (!isMenuActionValid($mode, $action, $what, true)) {
188 return getCode('MENU_NOT_VALID');
191 // Non-admin shall not see all menus
193 $ADD = " AND `visible`='Y' AND `locked`='N'";
196 // Load SQL data and add the menu to the output stream...
197 $result_main = SQL_QUERY_ESC("SELECT
198 `title`, `what`, `action`, `visible`, `locked`
200 `{?_MYSQL_PREFIX?}_%s_menu`
202 (`what`='' OR `what` IS NULL)
206 array($mode), __FUNCTION__, __LINE__);
208 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.':'.getWhat().'*');
209 if (!SQL_HASZERONUMS($result_main)) {
210 // There are menus available, so we simply display them... :)
211 $GLOBALS['rows'] = '';
212 while ($content = SQL_FETCHARRAY($result_main)) {
213 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . ':' . getWhat() . '*');
214 // Disable the block-mode
215 enableBlockMode(false);
217 // Load menu header template
218 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
221 $result_sub = SQL_QUERY_ESC("SELECT
222 `title` AS `sub_title`,
223 `what` AS `sub_what`,
224 `visible` AS `sub_visible`,
225 `locked` AS `sub_locked`
227 `{?_MYSQL_PREFIX?}_%s_menu`
235 array($mode, $content['action']), __FUNCTION__, __LINE__);
237 // Do we have some entries?
238 if (!SQL_HASZERONUMS($result_sub)) {
242 // Load all sub menus
243 while ($content2 = SQL_FETCHARRAY($result_sub)) {
244 // Merge both arrays in one
245 $content = merge_array($content, $content2);
250 // Full file name for checking menu
251 //* DEBUG: */ debugOutput(__LINE__ . ':!!!!' . $content['sub_what'] . '!!!');
252 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
253 if (isIncludeReadable($inc)) {
254 // Mark currently selected menu - open
255 if ((!empty($what)) && (($what == $content['sub_what']))) {
260 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
263 $OUT .= '<em style="cursor:help" class="notice" title="{%message,MENU_WHAT_404=' . $content['sub_what'] . '%}">';
267 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
269 if (isIncludeReadable($inc)) {
272 // Mark currently selected menu - close
273 if ((!empty($what)) && (($what == $content['sub_what']))) {
277 // Not found! - close
287 'what' => $content['sub_what'],
288 'visible' => $content['sub_visible'],
289 'locked' => $content['locked'],
292 // Add regular menu row or bottom row?
293 if ($count < SQL_NUMROWS($result_sub)) {
294 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
296 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
300 // This is a menu block... ;-)
304 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
305 if (isFileReadable($INC)) {
307 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
308 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat().'*');
310 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat().'*');
311 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
313 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat().'*');
317 SQL_FREERESULT($result_sub);
322 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.':'.getWhat().'*');
323 if (SQL_NUMROWS($result_main) > $main_cnt) {
325 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
327 // Should we display adverts in this menu?
328 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
329 // Display advert template
330 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
332 // Add seperator again
333 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
339 SQL_FREERESULT($result_main);
341 // Should we display adverts in this menu?
342 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
343 // Add seperator again
344 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
346 // Display advert template
347 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
352 'rows' => $GLOBALS['rows'],
356 // Load main template
357 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat().'*');
358 loadTemplate('menu_table', false, $content);
362 // Checks wether the current user is a member
363 function isMember () {
364 // By default no member
367 // Fix missing 'last_online' array, damn stupid code :(((
368 // @TODO Try to rewrite this to one or more functions
369 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
371 // Is the cache entry there?
372 if (isset($GLOBALS[__FUNCTION__])) {
374 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
375 return $GLOBALS[__FUNCTION__];
376 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
377 // Destroy any existing user session data
378 destroyMemberSession();
379 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
381 // Abort further processing
385 // Get userid secured from session
386 setMemberId(getSession('userid'));
388 // ... and set it as currently handled user id
389 setCurrentUserId(getMemberId());
391 // Init user data array
394 // Fix "deleted" cookies first
395 fixDeletedCookies(array('userid', 'u_hash'));
397 // Are cookies set and can the member data be loaded?
398 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
399 // Validate password by created the difference of it and the secret key
400 $valPass = encodeHashForCookie(getUserData('password'));
402 // So did we now have valid data and an unlocked user?
403 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
404 // Transfer last module and online time
405 $GLOBALS['last_online']['module'] = getUserData('last_module');
406 $GLOBALS['last_online']['online'] = getUserData('last_online');
408 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
413 // Is $ret still false?
414 if ($ret === false) {
415 // Yes, so destroy the session
416 destroyMemberSession();
420 $GLOBALS[__FUNCTION__] = $ret;
423 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
427 // Fetch user data for given user id
428 function fetchUserData ($userid, $column = 'userid') {
429 // If we should look for userid secure&set it here
430 if (substr($column, -2, 2) == 'id') {
432 $userid = bigintval($userid);
435 setCurrentUserId($userid);
437 // Don't look for invalid userids...
438 if (!isValidUserId($userid)) {
439 // Invalid, so abort here
440 debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $userid . ' is invalid.');
441 } elseif (isUserDataValid()) {
442 // Use cache, so it is fine
445 } elseif (isUserDataValid()) {
446 // Use cache, so it is fine
450 // By default none was found
455 if (isExtensionInstalledAndNewer('user', '0.3.5')) $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
457 // Query for the user
458 $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
459 array($column, $userid), __FUNCTION__, __LINE__);
461 // Do we have a record?
462 if (SQL_NUMROWS($result) == 1) {
463 // Load data from cookies
464 $data = SQL_FETCHARRAY($result);
466 // Set the userid for later use
467 setCurrentUserId($data['userid']);
468 $GLOBALS['user_data'][getCurrentUserId()] = $data;
470 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
471 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
472 // Backup the raw one and zero it
473 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
474 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = null;
477 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
478 // Seperate data/time
479 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
481 // Seperate data and time again
482 $array['date'] = explode('-', $array[0]);
483 $array['time'] = explode(':', $array[1]);
485 // Now pass it to mktime()
486 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
498 $found = isUserDataValid();
502 SQL_FREERESULT($result);
508 // This patched function will reduce many SELECT queries for the specified or current admin login
509 function isAdmin () {
510 // No admin in installation phase!
511 if ((isInstallationPhase()) || (!isAdminRegistered())) {
520 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
522 // If admin login is not given take current from cookies...
523 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
524 // Get admin login and password from session/cookies
525 $adminId = getCurrentAdminId();
526 $passCookie = getAdminMd5();
528 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId.'/'.$passCookie);
530 // Abort if admin id is zero
531 if ($adminId == '0') {
536 if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
537 // Init it with failed
538 $GLOBALS[__FUNCTION__][$adminId] = false;
540 // Search in array for entry
541 if (isset($GLOBALS['admin_hash'])) {
543 $valPass = $GLOBALS['admin_hash'];
544 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
545 // Login data is valid or not?
546 $valPass = encodeHashForCookie(getAdminHash($adminId));
549 $GLOBALS['admin_hash'] = $valPass;
552 incrementStatsEntry('cache_hits');
553 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
554 // Get admin hash and hash it
555 $valPass = encodeHashForCookie(getAdminHash($adminId));
558 $GLOBALS['admin_hash'] = $valPass;
561 if (!empty($valPass)) {
562 // Check if password is valid
563 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
564 $GLOBALS[__FUNCTION__][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
568 // Return result of comparision
569 return $GLOBALS[__FUNCTION__][$adminId];
572 // Generates a list of "max receiveable emails per day"
573 function addMaxReceiveList ($mode, $default = '', $return = false) {
579 // Guests (in the registration form) are not allowed to select 0 mails per day.
580 $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
581 __FUNCTION__, __LINE__);
585 // Members are allowed to set to zero mails per day (we will change this soon!)
586 $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
587 __FUNCTION__, __LINE__);
591 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
595 // Some entries are found?
596 if (!SQL_HASZERONUMS($result)) {
598 while ($content = SQL_FETCHARRAY($result)) {
599 $OUT .= ' <option value="' . $content['value'] . '"';
600 if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
601 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
602 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
607 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
609 // Maybe the admin has to setup some maximum values?
610 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
614 SQL_FREERESULT($result);
616 if ($return === true) {
617 // Return generated HTML code
620 // Output directly (default)
625 // Checks wether the given email address is used.
626 function isEmailTaken ($email) {
627 // Query the database
628 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '%%%s%%' OR `email` LIKE '%%%s%%' LIMIT 1",
629 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
631 // Is the email there?
632 $ret = (SQL_NUMROWS($result) == 1);
635 SQL_FREERESULT($result);
641 // Validate the given menu action
642 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
643 // Is the cache entry there and we shall not update?
644 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
646 incrementStatsEntry('cache_hits');
648 // Then use this cache
649 return $GLOBALS['action_valid'][$mode][$action][$what];
652 // By default nothing is valid
655 // Look in all menus or only unlocked
657 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
659 //* DEBUG: */ debugOutput(__LINE__.':'.$mode.'/'.$action.'/'.$what.'*');
660 if (($mode != 'admin') && ($updateEntry === true)) {
661 // Update guest or member menu
662 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
667 ), __FUNCTION__, __LINE__, false);
668 } elseif (($what != 'overview') && (!empty($what))) {
670 $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",
675 ), __FUNCTION__, __LINE__, false);
677 // Admin login overview
678 $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",
682 ), __FUNCTION__, __LINE__, false);
686 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
688 // Should we look for affected rows (only update) or found rows?
689 if ($updateEntry === true) {
690 // Check updated/affected rows
691 $ret = (!SQL_HASZEROAFFECTED());
694 $ret = (!SQL_HASZERONUMS($result));
698 SQL_FREERESULT($result);
701 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
707 // Get action value from mode (admin/guest/member) and what-value
708 function getActionFromModuleWhat ($module, $what) {
710 $data['action'] = '';
712 //* DEBUG: */ debugOutput(__LINE__ . '=' . $module . '/'.$what . '/' . getAction() . '=');
713 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
714 // sql_patches is missing so choose depending on mode
718 } elseif ($module == 'admin') {
725 } elseif ((empty($what)) && ($module != 'admin')) {
726 // Use configured 'home'
727 $what = getIndexHome();
730 if ($module == 'admin') {
731 // Action value for admin area
732 if (isGetRequestParameterSet('action')) {
734 return getRequestParameter('action');
735 } elseif (isActionSet()) {
736 // Get it directly from URL
738 } elseif (($what == 'overview') || (!isWhatSet())) {
739 // Default value for admin area
740 $data['action'] = 'login';
742 } elseif (isActionSet()) {
743 // Get it directly from URL
746 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ret=' . $data['action']);
748 // Does the module have a menu?
749 if (ifModuleHasMenu($module)) {
750 // Rewriting modules to menu
751 $module = mapModuleToTable($module);
753 // Guest and member menu is 'main' as the default
754 if (empty($data['action'])) $data['action'] = 'main';
756 // Load from database
757 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
758 array($module, $what), __FUNCTION__, __LINE__);
759 if (SQL_NUMROWS($result) == 1) {
760 // Load action value and pray that this one is the right you want... ;-)
761 $data = SQL_FETCHARRAY($result);
765 SQL_FREERESULT($result);
766 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
767 // No sql_patches installed, but maybe we need to register an admin?
768 if (isAdminRegistered()) {
769 // Redirect to admin area
770 redirectToUrl('admin.php');
774 // Return action value
775 return $data['action'];
778 // Get category name back
779 function getCategory ($cid) {
780 // Default is not found
781 $data['cat'] = '{--_CATEGORY_404--}';
783 // Is the category id set?
786 $data['cat'] = '{--_CATEGORY_NONE--}';
787 } elseif ($cid > 0) {
788 // Lookup the category in database
789 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
790 array(bigintval($cid)), __FUNCTION__, __LINE__);
791 if (SQL_NUMROWS($result) == 1) {
792 // Category found... :-)
793 $data = SQL_FETCHARRAY($result);
797 SQL_FREERESULT($result);
804 // Get a string of "mail title" and price back
805 function getPaymentTitlePrice ($pid, $full=false) {
806 // Default is not found
807 $ret = '{--_PAYMENT_404--}';
810 $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
811 array(bigintval($pid)), __FUNCTION__, __LINE__);
812 if (SQL_NUMROWS($result) == 1) {
813 // Payment type found... :-)
814 $data = SQL_FETCHARRAY($result);
816 // Only title or also including price?
817 if ($full === false) {
818 $ret = $data['mail_title'];
820 $ret = $data['mail_title'] . ' / {%pipe,translateComma=' . $data['price'] . '%} {?POINTS?}';
825 SQL_FREERESULT($result);
831 // Get (basicly) the price of given payment id
832 function getPaymentPoints ($pid, $lookFor = 'price') {
834 $data[$lookFor] = '-1';
836 // Search for it in database
837 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
838 array($lookFor, $pid), __FUNCTION__, __LINE__);
840 // Is the entry there?
841 if (SQL_NUMROWS($result) == 1) {
842 // Payment type found... :-)
843 $data = SQL_FETCHARRAY($result);
847 SQL_FREERESULT($result);
850 return $data[$lookFor];
853 // Remove a receiver's id from $receivers and add a link for him to confirm
854 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
855 // Default is not removed
858 // Is the userid valid?
859 if (isValidUserId($userid)) {
860 // Remove entry from array
861 unset($receivers[$key]);
863 // Is there already a line for this user available?
865 // Only when we got a real stats id continue searching for the entry
866 $type = 'NORMAL'; $rowName = 'stats_id';
869 $rowName = 'bonus_id';
872 // Try to look the entry up
873 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
874 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
876 // Was it *not* found?
877 if (SQL_HASZERONUMS($result)) {
879 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
880 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
888 SQL_FREERESULT($result);
892 // Return status for sending routine
896 // Calculate sum (default) or count records of given criteria
897 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
901 //* DEBUG: */ debugOutput($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add);
902 if ((empty($search)) && ($search != '0')) {
903 // Count or sum whole table?
904 if ($countRows === true) {
906 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`".$add,
907 array($lookFor, $tableName), __FUNCTION__, __LINE__);
910 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`".$add,
911 array($lookFor, $tableName), __FUNCTION__, __LINE__);
913 } elseif (($countRows === true) || ($lookFor == 'userid')) {
915 //* DEBUG: */ debugOutput('COUNT!');
916 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
917 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
920 //* DEBUG: */ debugOutput('SUM!');
921 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
922 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
926 $data = SQL_FETCHARRAY($result);
929 SQL_FREERESULT($result);
932 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
934 $data['res'] = '0.00000';
935 } elseif (''.$data['res'].'' == '') {
941 //* DEBUG: */ debugOutput('ret=' . $data['res']);
944 // Getter fro ref level percents
945 function getReferalLevelPercents ($level) {
947 $data['percents'] = '0';
950 if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
951 // First look for level
952 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
953 if ($key !== false) {
955 $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
958 incrementStatsEntry('cache_hits');
960 } elseif (!isExtensionActive('cache')) {
962 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
963 array(bigintval($level)), __FUNCTION__, __LINE__);
966 if (SQL_NUMROWS($result_level) == 1) {
968 $data = SQL_FETCHARRAY($result_level);
972 SQL_FREERESULT($result_level);
976 return $data['percents'];
981 * Dynamic referal system, can also send mails!
983 * subject = Subject line, write in lower-case letters and underscore is allowed
984 * userid = Referal id wich should receive...
985 * points = ... xxx points
986 * sendNotify = shall I send the referal an email or not?
987 * refid = inc/modules/guest/what-confirm.php need this
988 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
989 * add_mode = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
990 * for default value will cause no referal will get points ever!!!)
992 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $refid = '0', $add_mode = 'ref') {
993 // By default nothing has been added
996 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">' . __FUNCTION__ . ' - ENTRY</font> ------------------------<ul><li>');
997 // Convert mode to lower-case
998 $add_mode = strtolower($add_mode);
1000 // When $userid = '0' add points to jackpot
1001 if (($userid == '0') && (isExtensionActive('jackpot'))) {
1002 // Add points to jackpot
1003 addPointsToJackpot($points);
1007 // Count up referal depth
1008 if (!isset($GLOBALS['ref_level'])) {
1009 // Initialialize referal system
1010 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal system initialized!');
1011 $GLOBALS['ref_level'] = '0';
1013 // Increase referal level
1014 $GLOBALS['ref_level']++;
1015 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal level increased. DEPTH='.$GLOBALS['ref_level']);
1018 // Check user account
1019 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points);
1020 if (fetchUserData($userid)) {
1021 // Determine wether the user has some mails to click before he/she gets the points
1022 $locked = ifUserPointsLocked($userid);
1024 // Default is 'normal' points
1027 // Which points, locked or normal?
1028 if ($locked === true) {
1029 $data = 'locked_points';
1032 // This is the user and his ref
1033 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1036 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1037 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points.',depth='.$GLOBALS['ref_level'].',per='.$per.',mode='.$add_mode);
1039 // Some percents found?
1041 // Calculate new points
1042 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points.',per='.$per.',depth='.$GLOBALS['ref_level']);
1043 $ref_points = $points * $per / 100;
1045 // Pay refback here if level > 0 and in ref-mode
1046 if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == 'ref') && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1047 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',data='.$GLOBALS['cache_array']['add_userid'][$userid].',ref_points='.$ref_points.',depth='.$GLOBALS['ref_level'].' - BEFORE!');
1048 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1049 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',data='.$GLOBALS['cache_array']['add_userid'][$userid].',ref_points='.$ref_points.',depth='.$GLOBALS['ref_level'].' - AFTER!');
1053 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
1054 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1055 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):data='.$data.',ref_points='.$ref_points.',userid='.$userid.',depth='.$GLOBALS['ref_level'].',mode='.$add_mode.' - UPDATE! ('.SQL_AFFECTEDROWS().')');
1057 // No entry updated?
1058 if (SQL_HASZEROAFFECTED()) {
1059 // First ref in this level! :-)
1060 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,%s,%s)",
1061 array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1062 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):data='.$data.',ref_points='.$ref_points.',userid='.$userid.',depth='.$GLOBALS['ref_level'].',mode='.$add_mode.' - INSERTED! ('.SQL_AFFECTEDROWS().')');
1065 // Check affected rows
1066 $added = SQL_AFFECTEDROWS();
1067 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):added='.intval($added));
1069 // Prepare data for the filter
1070 $filterData = array(
1071 'subject' => $subject,
1072 'userid' => $userid,
1073 'points' => $points,
1074 'notify' => $sendNotify,
1076 'locked' => $locked,
1078 'sub_mode' => $add_mode,
1083 $filterData = runFilterChain('add_points', $filterData);
1086 $added = $filterData['added'];
1087 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):added='.intval($added));
1089 // Points updated, maybe I shall send him an email?
1090 if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
1094 'level' => bigintval($GLOBALS['ref_level']),
1095 'points' => $ref_points,
1098 // Load email template
1099 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1102 sendEmail($userid, '{--THANX_REFERAL_ONE_SUBJECT--}', $message);
1103 } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($add_mode == 'direct')) {
1106 'reason' => '{--REASON_DIRECT_PAYMENT--}',
1107 'points' => $ref_points
1111 $message = loadEmailTemplate('add-points', $content, $userid);
1114 sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
1115 if (!isGetRequestParameterSet('mid')) {
1116 // Output message to admin
1117 loadTemplate('admin_settings_saved', false, '{--ADMIN_POINTS_ADDED--}');
1121 // Maybe there's another ref?
1122 if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1123 // Then let's credit him here...
1124 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.getUserData('refid').',points='.$points.' - ADVANCE!');
1125 $added = ($added && addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid')));
1130 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.': added=' . intval($added) . ' - EXIT</font> ------------------------<br />');
1134 // Updates the referal counter
1135 function updateReferalCounter ($userid) {
1136 // Make it sure referal level zero (member him-/herself) is at least selected
1137 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1138 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',level='.$GLOBALS['cache_array']['ref_level'][$userid]);
1141 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1142 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1144 // When no entry was updated then we have to create it here
1145 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):updated=' . SQL_AFFECTEDROWS());
1146 if (SQL_HASZEROAFFECTED()) {
1148 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1151 $GLOBALS['cache_array']['ref_level'][$userid]
1152 ), __FUNCTION__, __LINE__);
1153 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid);
1159 // Check for his referal
1160 if (fetchUserData($userid)) {
1162 $ref = getUserData('refid');
1165 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.$ref);
1167 // When he has a referal...
1168 if (($ref > 0) && ($ref != $userid)) {
1169 // Move to next referal level and count his counter one up!
1170 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):ref='.$ref.' - ADVANCE!');
1171 $GLOBALS['cache_array']['ref_level'][$userid]++;
1172 updateReferalCounter($ref);
1173 } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1174 // Remove cache here
1175 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):ref='.$ref.' - CACHE!');
1176 rebuildCache('refsystem', 'refsystem');
1180 $GLOBALS['cache_array']['ref_level'][$userid]--;
1182 // Handle refback here if extension is installed
1183 // @TODO Rewrite this to a filter
1184 if (isExtensionActive('refback')) {
1185 updateRefbackTable($userid);
1189 // Sends out mail to all administrators. This function is no longer obsolete
1190 // because we need it when there is no ext-admins installed
1191 function sendAdminEmails ($subj, $message) {
1192 // Load all admin email addresses
1193 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1194 while ($content = SQL_FETCHARRAY($result)) {
1195 // Send the email out
1196 sendEmail($content['email'], $subj, $message);
1200 SQL_FREERESULT($result);
1202 // Really simple... ;-)
1205 // Get id number from administrator's login name
1206 function getAdminId ($adminLogin) {
1207 // By default no admin is found
1211 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1212 // Use it if found to save SQL queries
1213 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1215 // Update cache hits
1216 incrementStatsEntry('cache_hits');
1217 } elseif (!isExtensionActive('cache')) {
1218 // Load from database
1219 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1220 array($adminLogin), __FUNCTION__, __LINE__);
1222 // Do we have an entry?
1223 if (SQL_NUMROWS($result) == 1) {
1225 $data = SQL_FETCHARRAY($result);
1229 SQL_FREERESULT($result);
1236 // "Getter" for current admin id
1237 function getCurrentAdminId () {
1238 // Log debug message
1239 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1241 // Do we have cache?
1242 if (!isset($GLOBALS['current_admin_id'])) {
1243 // Get the admin login from session
1244 $adminId = getSession('admin_id');
1246 // Remember in cache securely
1247 setCurrentAdminId(bigintval($adminId));
1251 return $GLOBALS['current_admin_id'];
1254 // Setter for current admin id
1255 function setCurrentAdminId ($currentAdminId) {
1257 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1260 // Get password hash from administrator's login name
1261 function getAdminHash ($adminId) {
1262 // By default an invalid hash is returned
1263 $data['password'] = '-1';
1265 if (isAdminHashSet($adminId)) {
1267 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1269 // Update cache hits
1270 incrementStatsEntry('cache_hits');
1271 } elseif (!isExtensionActive('cache')) {
1272 // Load from database
1273 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1274 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1276 // Do we have an entry?
1277 if (SQL_NUMROWS($result) == 1) {
1279 $data = SQL_FETCHARRAY($result);
1282 setAdminHash($adminId, $data['password']);
1286 SQL_FREERESULT($result);
1289 // Return password hash
1290 return $data['password'];
1293 // "Getter" for admin login
1294 function getAdminLogin ($adminId) {
1295 // By default a non-existent login is returned (other functions react on this!)
1296 $data['login'] = '***';
1298 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1300 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1302 // Update cache hits
1303 incrementStatsEntry('cache_hits');
1304 } elseif (!isExtensionActive('cache')) {
1305 // Load from database
1306 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1307 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1310 if (SQL_NUMROWS($result) == 1) {
1312 $data = SQL_FETCHARRAY($result);
1315 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1319 SQL_FREERESULT($result);
1322 // Return the result
1323 return $data['login'];
1326 // Get email address of admin id
1327 function getAdminEmail ($adminId) {
1328 // By default an invalid emails is returned
1329 $data['email'] = '***';
1331 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1333 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1335 // Update cache hits
1336 incrementStatsEntry('cache_hits');
1337 } elseif (!isExtensionActive('cache')) {
1338 // Load from database
1339 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1340 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1343 if (SQL_NUMROWS($result_admin_id) == 1) {
1345 $data = SQL_FETCHARRAY($result_admin_id);
1348 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1352 SQL_FREERESULT($result_admin_id);
1356 return $data['email'];
1359 // Get default ACL of admin id
1360 function getAdminDefaultAcl ($adminId) {
1361 // By default an invalid ACL value is returned
1362 $data['default_acl'] = '***';
1364 // Is sql_patches there and was it found in cache?
1365 if (!isExtensionActive('sql_patches')) {
1366 // Not found, which is bad, so we need to allow all
1367 $data['default_acl'] = 'allow';
1368 } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1370 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1372 // Update cache hits
1373 incrementStatsEntry('cache_hits');
1374 } elseif (!isExtensionActive('cache')) {
1375 // Load from database
1376 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1377 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1378 if (SQL_NUMROWS($result_admin_id) == 1) {
1380 $data = SQL_FETCHARRAY($result_admin_id);
1383 $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1387 SQL_FREERESULT($result_admin_id);
1390 // Return default ACL
1391 return $data['default_acl'];
1394 // Generates an option list from various parameters
1395 function generateOptionList ($table, $id, $name, $default = '', $special = '', $where = '', $disabled = array(), $callback = '') {
1397 if ($table == '/ARRAY/') {
1398 // Selection from array
1399 if ((is_array($id)) && (is_array($name)) && ((count($id)) == (count($name)) || (!empty($callback)))) {
1401 foreach ($id as $idx => $value) {
1402 $ret .= '<option value="' . $value . '"';
1403 if ($default == $value) {
1404 // Selected by default
1405 $ret .= ' selected="selected"';
1406 } elseif (isset($disabled[$value])) {
1408 $ret .= ' disabled="disabled"';
1411 // Is the call-back function set?
1412 if (!empty($callback)) {
1414 $name[$idx] = call_user_func_array($callback, array($id[$idx]));
1417 // Finish option tag
1418 $ret .= '>' . $name[$idx] . '</option>';
1421 // Problem in request
1422 debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
1425 // Data from database
1426 $SPEC = ', `' . $id . '`';
1427 if (!empty($special)) $SPEC = ', `' . $special . '`';
1429 // Query the database
1430 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1436 ), __FUNCTION__, __LINE__);
1439 if (!SQL_HASZERONUMS($result)) {
1440 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1441 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1442 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1443 if (empty($special)) $add = '';
1444 $ret .= '<option value="' . $value . '"';
1445 if ($default == $value) {
1446 // Selected by default
1447 $ret .= ' selected="selected"';
1448 } elseif (isset($disabled[$value])) {
1450 $ret .= ' disabled="disabled"';
1454 if (!empty($add)) $add = ' ('.$add.')';
1456 // Is the call-back function set?
1457 if (!empty($callback)) {
1459 $title = call_user_func_array($callback, array($title));
1462 // Finish option list
1463 $ret .= '>' . $title . $add . '</option>';
1467 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1471 SQL_FREERESULT($result);
1474 // Return - hopefully - the requested data
1477 // Activate exchange
1478 function FILTER_ACTIVATE_EXCHANGE () {
1479 // Is the extension 'user' there?
1480 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1481 // Silently abort here
1485 // Check total amount of users
1486 if (getTotalConfirmedUser() >= getActivateXchange()) {
1488 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1");
1489 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1492 runFilterChain('run_sqls');
1494 // Update configuration
1495 updateConfiguration('activate_xchange' ,0);
1498 rebuildCache('modules', 'modules');
1502 // Deletes a user account with given reason
1503 function deleteUserAccount ($userid, $reason) {
1505 $data['points'] = '0';
1507 $result = SQL_QUERY_ESC("SELECT
1508 (SUM(p.`points`) - d.`used_points`) AS `points`
1510 `{?_MYSQL_PREFIX?}_user_points` AS p
1512 `{?_MYSQL_PREFIX?}_user_data` AS d
1514 p.`userid`=d.`userid`
1518 array(bigintval($userid)), __FUNCTION__, __LINE__);
1520 // Do we have an entry?
1521 if (SQL_NUMROWS($result) == 1) {
1522 // Save his points to add them to the jackpot
1523 $data = SQL_FETCHARRAY($result);
1525 // Delete points entries as well
1526 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1527 array(bigintval($userid)), __FUNCTION__, __LINE__);
1529 // Update mediadata as well
1530 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1532 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1535 // Now, when we have all his points adds them do the jackpot!
1536 if (isExtensionActive('jackpot')) addPointsToJackpot($data['points']);
1540 SQL_FREERESULT($result);
1542 // Delete category selections as well...
1543 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1544 array(bigintval($userid)), __FUNCTION__, __LINE__);
1546 // Remove from rallye if found
1547 // @TODO Rewrite this to a filter
1548 if (isExtensionActive('rallye')) {
1549 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1550 array(bigintval($userid)), __FUNCTION__, __LINE__);
1553 // Add reason and translate points
1554 $data['text'] = $reason;
1556 // Now a mail to the user and that's all...
1557 $message = loadEmailTemplate('del-user', $data, $userid);
1558 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1560 // Ok, delete the account!
1561 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1564 // Gets the matching what name from module
1565 function getWhatFromModule ($modCheck) {
1566 // Is the request element set?
1567 if (isGetRequestParameterSet('what')) {
1568 // Then return this!
1569 return getRequestParameter('what');
1575 //* DEBUG: */ debugOutput(__LINE__.'!'.$modCheck.'!');
1576 switch ($modCheck) {
1583 // Is ext-sql_patches installed and newer than 0.0.5?
1584 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1585 // Use it from config
1586 $what = getIndexHome();
1588 // Use default 'welcome'
1598 // Return what value
1602 // Subtract points from database and mediadata cache
1603 function subtractPoints ($subject, $userid, $points) {
1604 // Add points to used points
1605 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1606 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1608 // Prepare filter data
1609 $filterData = array(
1610 'subject' => $subject,
1611 'userid' => $userid,
1612 'points' => $points,
1614 'added' => (!SQL_HASZEROAFFECTED())
1617 // Insert booking record
1618 $filterData = runFilterChain('sub_points', $filterData);
1621 return $filterData['added'];
1624 // "Getter" for total available receivers
1625 function getTotalReceivers ($mode = 'normal') {
1627 $numRows = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND `receive_mails` > 0' . runFilterChain('exclude_users', $mode));
1633 // Returns HTML code with an option list of all categories
1634 function generateCategoryOptionsList ($mode) {
1635 // Prepare WHERE statement
1636 $whereStatement = " WHERE `visible`='Y'";
1637 if (isAdmin()) $whereStatement = '';
1639 // Initialize array...
1643 'userids' => array()
1647 $result = SQL_QUERY('SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`' . $whereStatement . ' ORDER BY `sort` ASC',
1648 __FUNCTION__, __LINE__);
1650 // Do we have entries?
1651 if (!SQL_HASZERONUMS($result)) {
1652 // ... and begin loading stuff
1653 while ($content = SQL_FETCHARRAY($result)) {
1654 // Transfer some data
1655 $CATS['id'][] = $content['id'];
1656 $CATS['name'][] = $content['cat'];
1658 // Check which users are in this category
1659 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1660 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1666 while ($data = SQL_FETCHARRAY($result_userids)) {
1668 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1672 SQL_FREERESULT($result_userids);
1675 $CATS['userids'][] = $userid_cnt;
1679 SQL_FREERESULT($result);
1683 foreach ($CATS['id'] as $key => $value) {
1684 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1685 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1688 // No cateogries are defined yet
1689 $OUT = '<option class="notice">{--MEMBER_NO_CATEGORIES--}</option>';
1696 // Add bonus mail to queue
1697 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1698 // Is admin or bonus extension there?
1702 } elseif (!isExtensionActive('bonus')) {
1707 // Calculcate target sent
1708 $target = countSelection(explode(';', $receiverList));
1710 // Receiver is zero?
1711 if ($receiver == '0') {
1713 $receiver = $target;
1716 // HTML extension active?
1717 if (isExtensionActive('html_mail')) {
1718 // No HTML by default
1722 if ($mode == 'html') $HTML = 'Y';
1725 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1726 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1727 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1737 bigintval($receiver),
1739 ), __FUNCTION__, __LINE__);
1742 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1743 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1744 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1754 bigintval($receiver),
1755 ), __FUNCTION__, __LINE__);
1759 // Generate a receiver list for given category and maximum receivers
1760 function generateReceiverList ($cat, $receiver, $mode = '') {
1768 $cat = bigintval($cat);
1769 $receiver = bigintval($receiver);
1771 // Is the receiver zero and mode set?
1772 if (($receiver == '0') && (!empty($mode))) {
1773 // Auto-fix receiver maximum
1774 $receiver = getTotalReceivers($mode);
1780 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1781 $CAT_WHERE = sprintf(" AND c.`cat_id`=%s", $cat);
1784 // Exclude users in holiday?
1785 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1786 // Add something for the holiday extension
1787 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1790 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1791 // Only include HTML receivers
1792 $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED' AND d.`html`='Y'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
1795 ), __FUNCTION__, __LINE__);
1798 $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
1801 ), __FUNCTION__, __LINE__);
1805 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1807 while ($content = SQL_FETCHARRAY($result)) {
1808 // Add receiver when not empty
1809 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1813 SQL_FREERESULT($result);
1815 // Remove trailing semicolon
1816 $receiverList = substr($receiverList, 0, -1);
1820 return $receiverList;
1823 // "Getter" for array for user refs and points in given level
1824 function getUserReferalPoints ($userid, $level) {
1825 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">'.__FUNCTION__.' - ENTRY</font> ------------------------<ul><li>');
1826 // Default is no refs and no nickname
1830 // Do we have nickname extension installed?
1831 if (isExtensionActive('nickname')) {
1832 $add = ', ud.nickname';
1835 // Get refs from database
1836 $result = SQL_QUERY_ESC("SELECT
1837 ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
1839 `{?_MYSQL_PREFIX?}_user_refs` AS ur
1841 `{?_MYSQL_PREFIX?}_user_points` AS up
1843 ur.refid=up.userid AND ur.level=0
1845 `{?_MYSQL_PREFIX?}_user_data` AS ud
1849 ur.userid=%s AND ur.level=%s
1855 ), __FUNCTION__, __LINE__);
1857 // Are there some entries?
1858 if (!SQL_HASZERONUMS($result)) {
1859 // Fetch all entries
1860 while ($row = SQL_FETCHARRAY($result)) {
1861 // Get total points of this user
1862 $row['points'] = getTotalPoints($row['refid']);
1864 // Get unconfirmed mails
1865 $row['unconfirmed'] = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
1867 // Init clickrate with zero
1868 $row['clickrate'] = '0';
1870 // Is at least one mail received?
1871 if ($row['emails_received'] > 0) {
1872 // Calculate clickrate
1873 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
1876 // Activity is 'active' by default because if autopurge is not installed
1877 $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
1879 // Is autopurge installed and the user inactive?
1880 if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online'])) {
1882 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
1885 // Remove some entries
1886 unset($row['mails_confirmed']);
1887 unset($row['emails_received']);
1888 unset($row['last_online']);
1891 $refs[$row['id']] = $row;
1896 SQL_FREERESULT($result);
1899 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
1903 // Recuce the amount of received emails for the receipients for given email
1904 function reduceRecipientReceivedMails ($column, $id, $count) {
1905 // Search for mail in database
1906 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1907 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1909 // Are there entries?
1910 if (!SQL_HASZERONUMS($result)) {
1911 // Now load all userids for one big query!
1913 while ($data = SQL_FETCHARRAY($result)) {
1914 // By default we want to reduce and have no mails found
1917 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1918 // @TODO Rewrite this to a filter
1919 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1921 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1922 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1924 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1927 // Reduce this users total received emails?
1928 if ($num === 0) $userids[$data['userid']] = $data['userid'];
1931 if (count($userids) > 0) {
1932 // Now update all user accounts
1933 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1934 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1937 loadTemplate('admin_settings_saved', false, getMaskedMessage('ADMIN_MAIL_NOTHING_DELETED', $id));
1942 SQL_FREERESULT($result);
1945 // Creates a new task
1946 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
1947 // Insert the task data into the database
1948 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())",
1955 ), __FUNCTION__, __LINE__, true, $strip);
1957 // Return insert id which is the task id
1958 return SQL_INSERTID();
1961 // Updates last module / online time
1962 // @TODO Fix inconsistency between last_module and getWhat()
1963 function updateLastActivity($userid) {
1964 // Run the update query
1965 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
1970 ), __FUNCTION__, __LINE__);