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 MySQL-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle MySQL-Relevanten Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // "Getter" for module description
46 // @TODO Can we cache this?
47 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
50 $what = getConfig('index_home');
53 // Default is not found
54 $data['title'] = '??? (' . $what . ')';
57 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
62 ), __FUNCTION__, __LINE__);
65 if (SQL_NUMROWS($result) == 1) {
67 $data = SQL_FETCHARRAY($result);
71 SQL_FREERESULT($result);
74 return $data['title'];
77 // Add menu description pending on given file name (without path!)
78 function addMenuDescription ($accessLevel, $FQFN, $return = false) {
79 // Use only filename of the FQFN...
80 $file = basename($FQFN);
88 // First we have to do some analysis...
89 if (substr($file, 0, 7) == 'action-') {
90 // This is an action file!
92 $search = substr($file, 7);
94 // Get access level from it
95 $modCheck = getModuleFromFileName($file, $accessLevel);
98 $ADD = " AND (`what`='' OR `what` IS NULL)";
99 } elseif (substr($file, 0, 5) == 'what-') {
100 // This is a 'what file'!
102 $search = substr($file, 5);
103 $ADD = " AND `visible`='Y' AND `locked`='N'";
105 // Get access level from it
106 $modCheck = getModuleFromFileName($file, $accessLevel);
108 // Do we have admin? Then display all
109 if (isAdmin()) $ADD = '';
111 $dummy = substr($search, 0, -4);
112 $ADD .= " AND `action`='".getActionFromModuleWhat($accessLevel, $dummy)."'";
113 } elseif (($accessLevel == 'sponsor') || ($accessLevel == 'engine')) {
114 // Sponsor / engine menu
117 $modCheck = getModule();
123 $modCheck = getModule();
127 // Begin the navigation line
128 if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) {
130 $GLOBALS['nav_depth'] = '0';
132 // Run the pre-filter chain
133 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
136 $prefix = $ret['content'];
138 $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>';
139 } elseif ($return === false) {
141 $GLOBALS['nav_depth']++;
144 $prefix .= ' -> ';
146 // We need to remove .php and the end
147 if (substr($search, -4, 4) == '.php') {
149 $search = substr($search, 0, -4);
152 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
154 $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>';
156 // Can we close the you-are-here navigation?
157 //* DEBUG: */ debugOutput(__LINE__.'*'.$type.'/'.getWhat().'*');
158 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
159 //* DEBUG: */ debugOutput(__LINE__.'+'.$type.'+');
160 // Add closing div and br-tag
162 $GLOBALS['nav_depth'] = '0';
164 // Run the post-filter chain
165 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
167 // Add additional content
168 $OUT .= $ret['content'];
172 // Return or output HTML code?
173 if ($return === true) {
177 // Output HTML code here
182 // Adds a menu (mode = guest/member/admin/sponsor) to output
183 function addMenu ($mode, $action, $what) {
184 // Init some variables
188 // is the menu action valid?
189 if (!isMenuActionValid($mode, $action, $what, true)) {
190 return getCode('MENU_NOT_VALID');
193 // Non-admin shall not see all menus
195 $ADD = " AND `visible`='Y' AND `locked`='N'";
198 // Load SQL data and add the menu to the output stream...
199 $result_main = SQL_QUERY_ESC("SELECT
200 `title`, `what`, `action`, `visible`, `locked`
202 `{?_MYSQL_PREFIX?}_%s_menu`
204 (`what`='' OR `what` IS NULL)
208 array($mode), __FUNCTION__, __LINE__);
210 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.':'.getWhat().'*');
211 if (!SQL_HASZERONUMS($result_main)) {
212 // There are menus available, so we simply display them... :)
213 $GLOBALS['rows'] = '';
214 while ($content = SQL_FETCHARRAY($result_main)) {
215 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . ':' . getWhat() . '*');
216 // Disable the block-mode
217 enableBlockMode(false);
219 // Load menu header template
220 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
223 $result_sub = SQL_QUERY_ESC("SELECT
224 `title` AS `sub_title`,
225 `what` AS `sub_what`,
226 `visible` AS `sub_visible`,
227 `locked` AS `sub_locked`
229 `{?_MYSQL_PREFIX?}_%s_menu`
237 array($mode, $content['action']), __FUNCTION__, __LINE__);
239 // Do we have some entries?
240 if (!SQL_HASZERONUMS($result_sub)) {
244 // Load all sub menus
245 while ($content2 = SQL_FETCHARRAY($result_sub)) {
246 // Merge both arrays in one
247 $content = merge_array($content, $content2);
252 // Full file name for checking menu
253 //* DEBUG: */ debugOutput(__LINE__ . ':!!!!' . $content['sub_what'] . '!!!');
254 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
255 if (isIncludeReadable($inc)) {
256 // Mark currently selected menu - open
257 if ((!empty($what)) && (($what == $content['sub_what']))) {
262 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
265 $OUT .= '<em style="cursor:help" class="admin_note" title="{%message,MENU_WHAT_404=' . $content['sub_what'] . '%}">';
269 $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
271 if (isIncludeReadable($inc)) {
274 // Mark currently selected menu - close
275 if ((!empty($what)) && (($what == $content['sub_what']))) {
279 // Not found! - close
289 'what' => $content['sub_what'],
290 'visible' => $content['sub_visible'],
291 'locked' => $content['locked'],
294 // Add regular menu row or bottom row?
295 if ($cnt < SQL_NUMROWS($result_sub)) {
296 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
298 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
302 // This is a menu block... ;-)
306 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
307 if (isFileReadable($INC)) {
309 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
310 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat().'*');
312 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat().'*');
313 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
315 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat().'*');
319 SQL_FREERESULT($result_sub);
324 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.':'.getWhat().'*');
325 if (SQL_NUMROWS($result_main) > $main_cnt) {
327 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
329 // Should we display adverts in this menu?
330 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
331 // Display advert template
332 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
334 // Add seperator again
335 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
341 SQL_FREERESULT($result_main);
343 // Should we display adverts in this menu?
344 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
345 // Add seperator again
346 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
348 // Display advert template
349 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
354 'rows' => $GLOBALS['rows'],
358 // Load main template
359 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat().'*');
360 loadTemplate('menu_table', false, $content);
364 // Checks wether the current user is a member
365 function isMember () {
366 // By default no member
369 // Fix missing 'last_online' array, damn stupid code :(((
370 // @TODO Try to rewrite this to one or more functions
371 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
373 // is the cache entry there?
374 if (isset($GLOBALS['is_member'])) {
376 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS['is_member']) . ')');
377 return $GLOBALS['is_member'];
378 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
380 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
383 // Get it secured from session
384 setMemberId(getSession('userid'));
385 setCurrentUserId(getMemberId());
386 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . getSession('userid') . ' used from cookie/session.');
389 // Init user data array
392 // Fix "deleted" cookies first
393 fixDeletedCookies(array('userid', 'u_hash'));
396 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) {
397 // Cookies are set with values, but are they valid?
398 if (fetchUserData(getMemberId()) === true) {
399 // Validate password by created the difference of it and the secret key
400 $valPass = encodeHashForCookie(getUserData('password'));
402 // Transfer last module and online time
403 $GLOBALS['last_online']['module'] = getUserData('last_module');
404 $GLOBALS['last_online']['online'] = getUserData('last_online');
406 // So did we now have valid data and an unlocked user?
407 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
408 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
411 // Maybe got locked etc.
412 //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status') . ',' . $valPass . '(' . strlen($valPass) . ')/' . getSession('u_hash') . '(' . strlen(getSession('u_hash')) . ')/' . getUserData('password') . '(' . strlen(getUserData('password')) . ')');
413 destroyMemberSession();
416 // Cookie data is invalid!
417 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data invalid or user not found.');
418 destroyMemberSession();
421 // Cookie data is invalid!
422 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data not complete.');
423 destroyMemberSession();
427 $GLOBALS['is_member'] = $ret;
430 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
434 // Fetch user data for given user id
435 function fetchUserData ($userid, $column = 'userid') {
436 // If we should look for userid secure&set it here
437 if (substr($column, -2, 2) == 'id') {
439 $userid = bigintval($userid);
442 setCurrentUserId($userid);
444 // Don't look for invalid userids...
446 // Invalid, so abort here
447 debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $userid . ' is invalid.');
448 } elseif (isUserDataValid()) {
449 // Use cache, so it is fine
452 } elseif (isUserDataValid()) {
453 // Use cache, so it is fine
458 // By default none was found
463 if (isExtensionInstalledAndNewer('user', '0.3.5')) $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
465 // Query for the user
466 $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
467 array($column, $userid), __FUNCTION__, __LINE__);
469 // Do we have a record?
470 if (SQL_NUMROWS($result) == 1) {
471 // Load data from cookies
472 $data = SQL_FETCHARRAY($result);
474 // Set the userid for later use
475 setCurrentUserId($data['userid']);
476 $GLOBALS['user_data'][getCurrentUserId()] = $data;
478 // Rewrite 'last_failure' if found
479 if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
480 // Backup the raw one and zero it
481 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
482 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = '0';
485 if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
486 // Seperate data/time
487 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
489 // Seperate data and time again
490 $array['date'] = explode('-', $array[0]);
491 $array['time'] = explode(':', $array[1]);
493 // Now pass it to mktime()
494 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
506 $found = isUserDataValid();
510 SQL_FREERESULT($result);
516 // This patched function will reduce many SELECT queries for the specified or current admin login
517 function isAdmin () {
518 // No admin in installation phase!
519 if ((isInstallationPhase()) || (!isAdminRegistered())) {
528 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
530 // If admin login is not given take current from cookies...
531 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
532 // Get admin login and password from session/cookies
533 $adminId = getSession('admin_id');
534 $passCookie = getSession('admin_md5');
536 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId.'/'.$passCookie);
538 // Abort if admin id is zero
539 if ($adminId == '0') {
544 if (!isset($GLOBALS['is_admin'][$adminId])) {
545 // Init it with failed
546 $GLOBALS['is_admin'][$adminId] = false;
548 // Search in array for entry
549 if (isset($GLOBALS['admin_hash'])) {
551 $valPass = $GLOBALS['admin_hash'];
552 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
553 // Login data is valid or not?
554 $valPass = encodeHashForCookie(getAdminHash($adminId));
557 $GLOBALS['admin_hash'] = $valPass;
560 incrementStatsEntry('cache_hits');
561 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
562 // Get admin hash and hash it
563 $valPass = encodeHashForCookie(getAdminHash($adminId));
566 $GLOBALS['admin_hash'] = $valPass;
569 if (!empty($valPass)) {
570 // Check if password is valid
571 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
572 $GLOBALS['is_admin'][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
576 // Return result of comparision
577 return $GLOBALS['is_admin'][$adminId];
580 // Generates a list of "max receiveable emails per day"
581 function addMaxReceiveList ($mode, $default = '', $return = false) {
587 // Guests (in the registration form) are not allowed to select 0 mails per day.
588 $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC",
589 __FUNCTION__, __LINE__);
593 // Members are allowed to set to zero mails per day (we will change this soon!)
594 $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC",
595 __FUNCTION__, __LINE__);
599 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
603 // Some entries are found?
604 if (!SQL_HASZERONUMS($result)) {
606 while ($content = SQL_FETCHARRAY($result)) {
607 $OUT .= ' <option value="' . $content['value'] . '"';
608 if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
609 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
610 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
615 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
617 // Maybe the admin has to setup some maximum values?
618 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
622 SQL_FREERESULT($result);
624 if ($return === true) {
625 // Return generated HTML code
628 // Output directly (default)
633 // Checks wether the given email address is used.
634 function isEmailTaken ($email) {
635 // Query the database
636 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '%%%s%%' OR `email` LIKE '%%%s%%' LIMIT 1",
637 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
639 // Is the email there?
640 $ret = (SQL_NUMROWS($result) == 1);
643 SQL_FREERESULT($result);
649 // Validate the given menu action
650 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
651 // Is the cache entry there and we shall not update?
652 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
654 incrementStatsEntry('cache_hits');
656 // Then use this cache
657 return $GLOBALS['action_valid'][$mode][$action][$what];
660 // By default nothing is valid
663 // Look in all menus or only unlocked
665 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
667 //* DEBUG: */ debugOutput(__LINE__.':'.$mode.'/'.$action.'/'.$what.'*');
668 if (($mode != 'admin') && ($updateEntry === true)) {
669 // Update guest or member menu
670 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
675 ), __FUNCTION__, __LINE__, false);
676 } elseif (($what != 'overview') && (!empty($what))) {
678 $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",
683 ), __FUNCTION__, __LINE__, false);
685 // Admin login overview
686 $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",
690 ), __FUNCTION__, __LINE__, false);
694 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
696 // Should we look for affected rows (only update) or found rows?
697 if ($updateEntry === true) {
698 // Check updated/affected rows
699 $ret = (SQL_AFFECTEDROWS() == 1);
702 $ret = (SQL_NUMROWS($result) == 1);
706 SQL_FREERESULT($result);
709 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
715 // Get action value from mode (admin/guest/member) and what-value
716 function getActionFromModuleWhat ($module, $what) {
718 $data['action'] = '';
720 //* DEBUG: */ debugOutput(__LINE__.'='.$module.'/'.$what.'/'.getAction().'=');
721 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
722 // sql_patches is missing so choose depending on mode
726 } elseif ($module == 'admin') {
733 } elseif ((empty($what)) && ($module != 'admin')) {
734 // Use configured 'home'
735 $what = getConfig('index_home');
738 if ($module == 'admin') {
739 // Action value for admin area
740 if (isGetRequestParameterSet('action')) {
742 return getRequestParameter('action');
743 } elseif (isActionSet()) {
744 // Get it directly from URL
746 } elseif (($what == 'overview') || (!isWhatSet())) {
747 // Default value for admin area
748 $data['action'] = 'login';
750 } elseif (isActionSet()) {
751 // Get it directly from URL
754 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ret=' . $data['action']);
756 // Does the module have a menu?
757 if (ifModuleHasMenu($module)) {
758 // Rewriting modules to menu
759 $module = mapModuleToTable($module);
761 // Guest and member menu is 'main' as the default
762 if (empty($data['action'])) $data['action'] = 'main';
764 // Load from database
765 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
766 array($module, $what), __FUNCTION__, __LINE__);
767 if (SQL_NUMROWS($result) == 1) {
768 // Load action value and pray that this one is the right you want... ;-)
769 $data = SQL_FETCHARRAY($result);
773 SQL_FREERESULT($result);
774 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
775 // No sql_patches installed, but maybe we need to register an admin?
776 if (isAdminRegistered()) {
777 // Redirect to admin area
778 redirectToUrl('admin.php');
782 // Return action value
783 return $data['action'];
786 // Get category name back
787 function getCategory ($cid) {
788 // Default is not found
789 $data['cat'] = '{--_CATEGORY_404--}';
791 // Is the category id set?
794 $data['cat'] = '{--_CATEGORY_NONE--}';
795 } elseif ($cid > 0) {
796 // Lookup the category in database
797 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
798 array(bigintval($cid)), __FUNCTION__, __LINE__);
799 if (SQL_NUMROWS($result) == 1) {
800 // Category found... :-)
801 $data = SQL_FETCHARRAY($result);
805 SQL_FREERESULT($result);
812 // Get a string of "mail title" and price back
813 function getPaymentTitlePrice ($pid, $full=false) {
814 // Default is not found
815 $ret = '{--_PAYMENT_404--}';
818 $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
819 array(bigintval($pid)), __FUNCTION__, __LINE__);
820 if (SQL_NUMROWS($result) == 1) {
821 // Payment type found... :-)
822 $data = SQL_FETCHARRAY($result);
824 // Only title or also including price?
825 if ($full === false) {
826 $ret = $data['mail_title'];
828 $ret = $data['mail_title'] . ' / ' . translateComma($data['price']) . ' {?POINTS?}';
833 SQL_FREERESULT($result);
839 // Get (basicly) the price of given payment id
840 function getPaymentPoints ($pid, $lookFor = 'price') {
842 $data[$lookFor] = '-1';
844 // Search for it in database
845 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
846 array($lookFor, $pid), __FUNCTION__, __LINE__);
848 // Is the entry there?
849 if (SQL_NUMROWS($result) == 1) {
850 // Payment type found... :-)
851 $data = SQL_FETCHARRAY($result);
855 SQL_FREERESULT($result);
858 return $data[$lookFor];
861 // Remove a receiver's id from $receivers and add a link for him to confirm
862 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
863 // Default is not removed
866 // Is the userid valid?
868 // Remove entry from array
869 unset($receivers[$key]);
871 // Is there already a line for this user available?
873 // Only when we got a real stats id continue searching for the entry
874 $type = 'NORMAL'; $rowName = 'stats_id';
875 if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
877 // Try to look the entry up
878 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
879 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
881 // Was it *not* found?
882 if (SQL_HASZERONUMS($result)) {
884 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
885 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
893 SQL_FREERESULT($result);
897 // Return status for sending routine
901 // Calculate sum (default) or count records of given criteria
902 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
906 //* DEBUG: */ debugOutput($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add);
907 if ((empty($search)) && ($search != '0')) {
908 // Count or sum whole table?
909 if ($countRows === true) {
911 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
912 array($lookFor, $tableName), __FUNCTION__, __LINE__);
915 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
916 array($lookFor, $tableName), __FUNCTION__, __LINE__);
918 } elseif (($countRows === true) || ($lookFor == 'userid')) {
920 //* DEBUG: */ debugOutput('COUNT!');
921 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
922 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
925 //* DEBUG: */ debugOutput('SUM!');
926 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
927 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
931 $data = SQL_FETCHARRAY($result);
934 SQL_FREERESULT($result);
937 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
939 $data['res'] = '0.00000';
940 } elseif (''.$data['res'].'' == '') {
946 //* DEBUG: */ debugOutput('ret=' . $data['res']);
949 // Getter fro ref level percents
950 function getReferalLevelPercents ($level) {
952 $data['percents'] = '0';
955 if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
956 // First look for level
957 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
958 if ($key !== false) {
960 $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
963 incrementStatsEntry('cache_hits');
965 } elseif (!isExtensionActive('cache')) {
967 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
968 array(bigintval($level)), __FUNCTION__, __LINE__);
971 if (SQL_NUMROWS($result_level) == 1) {
973 $data = SQL_FETCHARRAY($result_level);
977 SQL_FREERESULT($result_level);
981 return $data['percents'];
986 * Dynamic referal system, can also send mails!
988 * subject = Subject line, write in lower-case letters and underscore is allowed
989 * userid = Referal id wich should receive...
990 * points = ... xxx points
991 * sendNotify = shall I send the referal an email or not?
992 * rid = inc/modules/guest/what-confirm.php need this
993 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
994 * add_mode = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
995 * for default value will cause no referal will get points ever!!!)
997 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
998 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">' . __FUNCTION__ . ' - ENTRY</font> ------------------------<ul><li>');
999 // Convert mode to lower-case
1000 $add_mode = strtolower($add_mode);
1002 // When $userid = '0' add points to jackpot
1003 if (($userid == '0') && (isExtensionActive('jackpot'))) {
1004 // Add points to jackpot
1005 addPointsToJackpot($points);
1009 // Prepare data for the filter
1010 $filterData = array(
1011 'subject' => $subject,
1012 'userid' => $userid,
1013 'points' => $points,
1014 'notify' => $sendNotify,
1016 'locked' => $locked,
1018 'sub_mode' => $add_mode,
1022 runFilterChain('add_points', $filterData);
1024 // Count up referal depth
1025 if (!isset($GLOBALS['ref_level'])) {
1026 // Initialialize referal system
1027 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal system initialized!');
1028 $GLOBALS['ref_level'] = '0';
1030 // Increase referal level
1031 $GLOBALS['ref_level']++;
1032 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal level increased. DEPTH='.$GLOBALS['ref_level']);
1035 // Default is 'normal' points
1038 // Which points, locked or normal?
1039 if ($locked === true) $data = 'locked_points';
1041 // Check user account
1042 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points);
1043 if (fetchUserData($userid)) {
1044 // This is the user and his ref
1045 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1048 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1049 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points.',depth='.$GLOBALS['ref_level'].',per='.$per.',mode='.$add_mode);
1051 // Some percents found?
1053 // Calculate new points
1054 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points.',per='.$per.',depth='.$GLOBALS['ref_level']);
1055 $ref_points = $points * $per / 100;
1057 // Pay refback here if level > 0 and in ref-mode
1058 if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == 'ref') && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1059 //* 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!');
1060 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1061 //* 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!');
1065 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
1066 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1067 //* 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().')');
1069 // No entry updated?
1070 if (SQL_AFFECTEDROWS() < 1) {
1071 // First ref in this level! :-)
1072 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,%s,%s)",
1073 array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1074 //* 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().')');
1077 // Points updated, maybe I shall send him an email?
1078 if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
1082 'level' => bigintval($GLOBALS['ref_level']),
1083 'points' => $ref_points,
1086 // Load email template
1087 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1090 sendEmail($userid, '{--THANX_REFERAL_ONE_SUBJECT--}', $message);
1091 } elseif (($sendNotify === true) && (getUserData('refid') == '0') && ($locked === false) && ($add_mode == 'direct')) {
1094 'text' => '{--REASON_DIRECT_PAYMENT--}',
1095 'points' => $ref_points
1099 $message = loadEmailTemplate('add-points', $content, $userid);
1102 sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
1103 if (!isGetRequestParameterSet('mid')) loadTemplate('admin_settings_saved', false, '{--ADMIN_POINTS_ADDED--}');
1106 // Maybe there's another ref?
1107 if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1108 // Then let's credit him here...
1109 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.getUserData('refid').',points='.$points.' - ADVANCE!');
1110 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
1115 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
1118 // Updates the referal counter
1119 function updateReferalCounter ($userid) {
1120 // Make it sure referal level zero (member him-/herself) is at least selected
1121 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1122 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',level='.$GLOBALS['cache_array']['ref_level'][$userid]);
1125 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1126 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1128 // When no entry was updated then we have to create it here
1129 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):updated=' . SQL_AFFECTEDROWS());
1130 if (SQL_AFFECTEDROWS() < 1) {
1132 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1133 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1134 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid);
1140 // Check for his referal
1141 if (fetchUserData($userid)) {
1143 $ref = getUserData('refid');
1146 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.$ref);
1148 // When he has a referal...
1149 if (($ref > 0) && ($ref != $userid)) {
1150 // Move to next referal level and count his counter one up!
1151 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):ref='.$ref.' - ADVANCE!');
1152 $GLOBALS['cache_array']['ref_level'][$userid]++;
1153 updateReferalCounter($ref);
1154 } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1155 // Remove cache here
1156 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):ref='.$ref.' - CACHE!');
1157 rebuildCache('refsystem', 'refsystem');
1161 $GLOBALS['cache_array']['ref_level'][$userid]--;
1163 // Handle refback here if extension is installed
1164 if (isExtensionActive('refback')) {
1165 updateRefbackTable($userid);
1169 // Sends out mail to all administrators. This function is no longer obsolete
1170 // because we need it when there is no ext-admins installed
1171 function sendAdminEmails ($subj, $message) {
1172 // Load all admin email addresses
1173 $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1174 while ($content = SQL_FETCHARRAY($result)) {
1175 // Send the email out
1176 sendEmail($content['email'], $subj, $message);
1180 SQL_FREERESULT($result);
1182 // Really simple... ;-)
1185 // Get id number from administrator's login name
1186 function getAdminId ($adminLogin) {
1187 // By default no admin is found
1191 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1192 // Use it if found to save SQL queries
1193 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1195 // Update cache hits
1196 incrementStatsEntry('cache_hits');
1197 } elseif (!isExtensionActive('cache')) {
1198 // Load from database
1199 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1200 array($adminLogin), __FUNCTION__, __LINE__);
1202 // Do we have an entry?
1203 if (SQL_NUMROWS($result) == 1) {
1205 $data = SQL_FETCHARRAY($result);
1209 SQL_FREERESULT($result);
1216 // "Getter" for current admin id
1217 function getCurrentAdminId () {
1218 // Do we have cache?
1219 if (!isset($GLOBALS['current_admin_id'])) {
1220 // Get the admin login from session
1221 $adminId = getSession('admin_id');
1223 // Remember in cache securely
1224 setCurrentAdminId(bigintval($adminId));
1228 return $GLOBALS['current_admin_id'];
1231 // Setter for current admin id
1232 function setCurrentAdminId ($currentAdminId) {
1234 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1237 // Get password hash from administrator's login name
1238 function getAdminHash ($adminId) {
1239 // By default an invalid hash is returned
1240 $data['password'] = '-1';
1242 if (isAdminHashSet($adminId)) {
1244 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1246 // Update cache hits
1247 incrementStatsEntry('cache_hits');
1248 } elseif (!isExtensionActive('cache')) {
1249 // Load from database
1250 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1251 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1253 // Do we have an entry?
1254 if (SQL_NUMROWS($result) == 1) {
1256 $data = SQL_FETCHARRAY($result);
1259 setAdminHash($adminId, $data['password']);
1263 SQL_FREERESULT($result);
1266 // Return password hash
1267 return $data['password'];
1270 // "Getter" for admin login
1271 function getAdminLogin ($adminId) {
1272 // By default a non-existent login is returned (other functions react on this!)
1273 $data['login'] = '***';
1275 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1277 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1279 // Update cache hits
1280 incrementStatsEntry('cache_hits');
1281 } elseif (!isExtensionActive('cache')) {
1282 // Load from database
1283 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1284 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1287 if (SQL_NUMROWS($result) == 1) {
1289 $data = SQL_FETCHARRAY($result);
1292 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1296 SQL_FREERESULT($result);
1299 // Return the result
1300 return $data['login'];
1303 // Get email address of admin id
1304 function getAdminEmail ($adminId) {
1305 // By default an invalid emails is returned
1306 $data['email'] = '***';
1308 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1310 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1312 // Update cache hits
1313 incrementStatsEntry('cache_hits');
1314 } elseif (!isExtensionActive('cache')) {
1315 // Load from database
1316 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1317 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1320 if (SQL_NUMROWS($result_admin_id) == 1) {
1322 $data = SQL_FETCHARRAY($result_admin_id);
1325 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1329 SQL_FREERESULT($result_admin_id);
1333 return $data['email'];
1336 // Get default ACL of admin id
1337 function getAdminDefaultAcl ($adminId) {
1338 // By default an invalid ACL value is returned
1339 $data['default_acl'] = '***';
1341 // Is sql_patches there and was it found in cache?
1342 if (!isExtensionActive('sql_patches')) {
1343 // Not found, which is bad, so we need to allow all
1344 $data['default_acl'] = 'allow';
1345 } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1347 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1349 // Update cache hits
1350 incrementStatsEntry('cache_hits');
1351 } elseif (!isExtensionActive('cache')) {
1352 // Load from database
1353 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1354 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1355 if (SQL_NUMROWS($result_admin_id) == 1) {
1357 $data = SQL_FETCHARRAY($result_admin_id);
1360 $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1364 SQL_FREERESULT($result_admin_id);
1367 // Return default ACL
1368 return $data['default_acl'];
1371 // Generates an option list from various parameters
1372 function generateOptionList ($table, $id, $name, $default='', $special='', $where='', $disabled=array()) {
1374 if ($table == '/ARRAY/') {
1375 // Selection from array
1376 if ((is_array($id)) && (is_array($name)) && (count($id)) == (count($name))) {
1378 foreach ($id as $idx => $value) {
1379 $ret .= '<option value="' . $value . '"';
1380 if ($default == $value) {
1381 // Selected by default
1382 $ret .= ' selected="selected"';
1383 } elseif (isset($disabled[$value])) {
1385 $ret .= ' disabled="disabled"';
1387 $ret .= '>' . $name[$idx] . '</option>';
1390 // Problem in request
1391 debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name));
1394 // Data from database
1395 $SPEC = ', `' . $id . '`';
1396 if (!empty($special)) $SPEC = ', `' . $special . '`';
1398 // Query the database
1399 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1405 ), __FUNCTION__, __LINE__);
1408 if (!SQL_HASZERONUMS($result)) {
1409 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1410 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1411 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1412 if (empty($special)) $add = '';
1413 $ret .= '<option value="' . $value . '"';
1414 if ($default == $value) {
1415 // Selected by default
1416 $ret .= ' selected="selected"';
1417 } elseif (isset($disabled[$value])) {
1419 $ret .= ' disabled="disabled"';
1421 if (!empty($add)) $add = ' ('.$add.')';
1422 $ret .= '>' . $title . $add . '</option>';
1426 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1430 SQL_FREERESULT($result);
1433 // Return - hopefully - the requested data
1436 // Activate exchange
1437 function FILTER_ACTIVATE_EXCHANGE () {
1438 // Is the extension 'user' there?
1439 if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) {
1440 // Silently abort here
1444 // Check total amount of users
1445 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1447 if ($totalUsers >= getConfig('activate_xchange')) {
1450 "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1451 "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1455 runFilterChain('run_sqls');
1457 // Update configuration
1458 updateConfiguration('activate_xchange' ,0);
1461 rebuildCache('modules', 'modules');
1465 // Deletes a user account with given reason
1466 function deleteUserAccount ($userid, $reason) {
1468 $data['points'] = '0';
1470 $result = SQL_QUERY_ESC("SELECT
1471 (SUM(p.points) - d.used_points) AS points
1473 `{?_MYSQL_PREFIX?}_user_points` AS p
1475 `{?_MYSQL_PREFIX?}_user_data` AS d
1481 array(bigintval($userid)), __FUNCTION__, __LINE__);
1483 // Do we have an entry?
1484 if (SQL_NUMROWS($result) == 1) {
1485 // Save his points to add them to the jackpot
1486 $data = SQL_FETCHARRAY($result);
1488 // Delete points entries as well
1489 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1490 array(bigintval($userid)), __FUNCTION__, __LINE__);
1492 // Update mediadata as well
1493 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1495 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1498 // Now, when we have all his points adds them do the jackpot!
1499 if (isExtensionActive('jackpot')) addPointsToJackpot($data['points']);
1503 SQL_FREERESULT($result);
1505 // Delete category selections as well...
1506 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1507 array(bigintval($userid)), __FUNCTION__, __LINE__);
1509 // Remove from rallye if found
1510 // @TODO Rewrite this to a filter
1511 if (isExtensionActive('rallye')) {
1512 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1513 array(bigintval($userid)), __FUNCTION__, __LINE__);
1516 // Add reason and translate points
1517 $data['text'] = $reason;
1518 $data['points'] = translateComma($data['points']);
1520 // Now a mail to the user and that's all...
1521 $message = loadEmailTemplate('del-user', $data, $userid);
1522 sendEmail($userid, '{--ADMIN_DEL_ACCOUNT--}', $message);
1524 // Ok, delete the account!
1525 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1528 // Gets the matching what name from module
1529 function getWhatFromModule ($modCheck) {
1530 // Is the request element set?
1531 if (isGetRequestParameterSet('what')) {
1532 // Then return this!
1533 return getRequestParameter('what');
1539 //* DEBUG: */ debugOutput(__LINE__.'!'.$modCheck.'!');
1540 switch ($modCheck) {
1547 // Is ext-sql_patches installed and newer than 0.0.5?
1548 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1549 // Use it from config
1550 $what = getConfig('index_home');
1552 // Use default 'welcome'
1562 // Return what value
1566 // Subtract points from database and mediadata cache
1567 function subtractPoints ($subject, $userid, $points) {
1568 // Add points to used points
1569 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1570 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1572 // Prepare filter data
1573 $filterData = array(
1574 'subject' => $subject,
1575 'userid' => $userid,
1576 'points' => $points,
1580 // Insert booking record
1581 runFilterChain('sub_points', $filterData);
1584 // "Getter" for total available receivers
1585 function getTotalReceivers ($mode='normal') {
1587 $result_all = SQL_QUERY("SELECT
1590 `{?_MYSQL_PREFIX?}_user_data`
1592 `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1593 __FUNCTION__, __LINE__);
1596 $numRows = SQL_NUMROWS($result_all);
1599 SQL_FREERESULT($result_all);
1605 // Returns HTML code with an option list of all categories
1606 function generateCategoryOptionsList ($mode) {
1607 // Prepare WHERE statement
1608 $whereStatement = " WHERE `visible`='Y'";
1609 if (isAdmin()) $whereStatement = '';
1611 // Initialize array...
1615 'userids' => array()
1619 $result = SQL_QUERY("SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort` ASC",
1620 __FUNCTION__, __LINE__);
1622 // Do we have entries?
1623 if (!SQL_HASZERONUMS($result)) {
1624 // ... and begin loading stuff
1625 while ($content = SQL_FETCHARRAY($result)) {
1626 // Transfer some data
1627 $CATS['id'][] = $content['id'];
1628 $CATS['name'][] = $content['cat'];
1630 // Check which users are in this category
1631 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1632 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1638 while ($data = SQL_FETCHARRAY($result_userids)) {
1640 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1644 SQL_FREERESULT($result_userids);
1647 $CATS['userids'][] = $userid_cnt;
1651 SQL_FREERESULT($result);
1655 foreach ($CATS['id'] as $key => $value) {
1656 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1657 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1660 // No cateogries are defined yet
1661 $OUT = '<option class="member_failed">{--MEMBER_NO_CATEGORIES--}</option>';
1668 // Add bonus mail to queue
1669 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1670 // Is admin or bonus extension there?
1674 } elseif (!isExtensionActive('bonus')) {
1679 // Calculcate target sent
1680 $target = countSelection(explode(';', $receiverList));
1682 // Receiver is zero?
1683 if ($receiver == '0') {
1685 $receiver = $target;
1688 // HTML extension active?
1689 if (isExtensionActive('html_mail')) {
1690 // No HTML by default
1694 if ($mode == 'html') $HTML = 'Y';
1697 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1698 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1699 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1709 bigintval($receiver),
1711 ), __FUNCTION__, __LINE__);
1714 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1715 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1716 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1726 bigintval($receiver),
1727 ), __FUNCTION__, __LINE__);
1731 // Generate a receiver list for given category and maximum receivers
1732 function generateReceiverList ($cat, $receiver, $mode = '') {
1740 $cat = bigintval($cat);
1741 $receiver = bigintval($receiver);
1743 // Is the receiver zero and mode set?
1744 if (($receiver == '0') && (!empty($mode))) {
1745 // Auto-fix receiver maximum
1746 $receiver = getTotalReceivers($mode);
1752 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
1753 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
1756 // Exclude users in holiday?
1757 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1758 // Add something for the holiday extension
1759 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1762 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1763 // Only include HTML receivers
1764 $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",
1767 ), __FUNCTION__, __LINE__);
1770 $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",
1773 ), __FUNCTION__, __LINE__);
1777 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1779 while ($content = SQL_FETCHARRAY($result)) {
1780 // Add receiver when not empty
1781 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1785 SQL_FREERESULT($result);
1787 // Remove trailing semicolon
1788 $receiverList = substr($receiverList, 0, -1);
1792 return $receiverList;
1795 // "Getter" for array for user refs and points in given level
1796 function getUserReferalPoints ($userid, $level) {
1797 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">'.__FUNCTION__.' - ENTRY</font> ------------------------<ul><li>');
1798 // Default is no refs and no nickname
1802 // Do we have nickname extension installed?
1803 if (isExtensionActive('nickname')) {
1804 $add = ', ud.nickname';
1807 // Get refs from database
1808 $result = SQL_QUERY_ESC("SELECT
1809 ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
1811 `{?_MYSQL_PREFIX?}_user_refs` AS ur
1813 `{?_MYSQL_PREFIX?}_user_points` AS up
1815 ur.refid=up.userid AND ur.level=0
1817 `{?_MYSQL_PREFIX?}_user_data` AS ud
1821 ur.userid=%s AND ur.level=%s
1827 ), __FUNCTION__, __LINE__);
1829 // Are there some entries?
1830 if (!SQL_HASZERONUMS($result)) {
1831 // Fetch all entries
1832 while ($row = SQL_FETCHARRAY($result)) {
1833 // Get total points of this user
1834 $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
1836 // Get unconfirmed mails
1837 $row['unconfirmed'] = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
1839 // Init clickrate with zero
1840 $row['clickrate'] = '0';
1842 // Is at least one mail received?
1843 if ($row['emails_received'] > 0) {
1844 // Calculate clickrate
1845 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
1848 // Activity is 'active' by default because if autopurge is not installed
1849 $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
1851 // Is autopurge installed and the user inactive?
1852 if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online'])) {
1854 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
1857 // Remove some entries
1858 unset($row['mails_confirmed']);
1859 unset($row['emails_received']);
1860 unset($row['last_online']);
1863 $refs[$row['id']] = $row;
1868 SQL_FREERESULT($result);
1871 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
1875 // Recuce the amount of received emails for the receipients for given email
1876 function reduceRecipientReceivedMails ($column, $id, $count) {
1877 // Search for mail in database
1878 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1879 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1881 // Are there entries?
1882 if (!SQL_HASZERONUMS($result)) {
1883 // Now load all userids for one big query!
1885 while ($data = SQL_FETCHARRAY($result)) {
1886 // By default we want to reduce and have no mails found
1889 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1890 // @TODO Rewrite this to a filter
1891 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1893 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1894 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1896 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1899 // Reduce this users total received emails?
1900 if ($num === 0) $userids[$data['userid']] = $data['userid'];
1903 if (count($userids) > 0) {
1904 // Now update all user accounts
1905 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1906 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1909 loadTemplate('admin_settings_saved', false, getMaskedMessage('ADMIN_MAIL_NOTHING_DELETED', $id));
1914 SQL_FREERESULT($result);
1917 // Creates a new task
1918 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
1919 // Insert the task data into the database
1920 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())",
1927 ), __FUNCTION__, __LINE__, true, $strip);
1929 // Return insert id which is the task id
1930 return SQL_INSERTID();
1933 // Updates last module / online time
1934 // @TODO Fix inconsistency between last_module and getWhat()
1935 function updateLastActivity($userid) {
1936 // Run the update query
1937 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
1942 ), __FUNCTION__, __LINE__);