2 /************************************************************************
3 * MXChange v0.2.1 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 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // "Getter" for module title
45 function getModuleTitle ($mod) {
50 // Is the script installed?
52 // Check if cache is valid
53 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($mod, $GLOBALS['cache_array']['modules']['module']))) {
55 $title = $GLOBALS['cache_array']['modules']['title'][$mod];
58 incrementStatsEntry('cache_hits');
59 } elseif (!isExtensionActive('cache')) {
61 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
62 array($mod), __FUNCTION__, __LINE__);
64 // Is the entry there?
65 if (SQL_NUMROWS($result)) {
66 // Get the title from database
67 list($title) = SQL_FETCHROW($result);
71 SQL_FREERESULT($result);
76 $title = trim($title);
78 // Still no luck or empty title?
81 $title = sprintf("%s (%s)", getMessage('LANG_UNKNOWN_MODULE'), $mod);
82 if (SQL_NUMROWS($result) == 0) {
83 // Add module to database
84 $dummy = checkModulePermissions($mod);
92 // "Getter" for module description
93 // @TODO Can we cache this?
94 function getModuleDescription ($mode, $what, $column = 'what') {
97 $what = getConfig('index_home');
100 // Default is not found
101 $ret = '??? (' . $what . ')';
104 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE %s='%s' LIMIT 1",
105 array($mode, $column, $what), __FUNCTION__, __LINE__);
107 // Is there an entry?
108 if (SQL_NUMROWS($result) == 1) {
110 list($ret) = SQL_FETCHROW($result);
114 SQL_FREERESULT($result);
120 // Check validity of a given module name (no file extension)
121 function checkModulePermissions ($mod = '') {
122 // Is it empty (default), then take the current one
123 if (empty($mod)) $mod = getModule();
126 if (isset($GLOBALS['module_status'][$mod])) {
128 return $GLOBALS['module_status'][$mod];
131 // Filter module name (names with low chars and underlines are fine!)
132 $mod = preg_replace('/[^a-z_]/', '', $mod);
134 // Check for prefix is a extension...
135 $modSplit = explode('_', $mod);
136 $extension = ''; $mod_chk = $mod;
137 //* DEBUG: */ print(__LINE__."*".count($modSplit)."*/".$mod."*<br />");
138 if (count($modSplit) == 2) {
139 // Okay, there is a seperator (_) in the name so is the first part a module?
140 //* DEBUG: */ print(__LINE__."*".$modSplit[0]."*<br />");
141 if (isExtensionActive($modSplit[0])) {
142 // The prefix is an extension's name, so let's set it
143 $extension = $modSplit[0]; $mod = $modSplit[1];
147 // Major error in module registry is the default
150 // Check if script is installed if not return a 'done' to prevent some errors
151 if ((isInstallationPhase()) || (!isAdminRegistered())) {
152 // Not installed or no admin registered or in installation phase
163 // Check if cache is latest version
164 if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
165 // Is the cache there?
166 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
167 if (isset($GLOBALS['cache_array']['modules']['locked'][$mod_chk])) {
169 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache found.');
170 $locked = $GLOBALS['cache_array']['modules']['locked'][$mod_chk];
171 $hidden = $GLOBALS['cache_array']['modules']['hidden'][$mod_chk];
172 $admin = $GLOBALS['cache_array']['modules']['admin_only'][$mod_chk];
173 $mem = $GLOBALS['cache_array']['modules']['mem_only'][$mod_chk];
176 incrementStatsEntry('cache_hits');
179 // No, then we have to update it!
182 } elseif (!isExtensionActive('cache')) {
183 // Check for module in database
184 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
185 $result = SQL_QUERY_ESC("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
186 array($mod_chk), __FUNCTION__, __LINE__);
187 if (SQL_NUMROWS($result) == 1) {
189 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Entry found.');
190 list($locked, $hidden, $admin, $mem) = SQL_FETCHROW($result);
192 } elseif (isDebugModeEnabled()) {
193 // Debug message only in debug-mode...
194 logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $mod_chk . ' not found!');
198 SQL_FREERESULT($result);
200 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
202 // Is the module found?
203 if ($found === true) {
204 // Check returned values against current access permissions
206 // Admin access ----- Guest access ----- --- Guest or member? ---
207 if ((isAdmin()) || (($locked != 'Y') && ($admin != 'Y') && (($mem != 'Y') || (isMember())))) {
208 // If you are admin you are welcome for everything!
210 } elseif ($locked == 'Y') {
213 } elseif (($mem == 'Y') && (!isMember())) {
214 // You have to login first!
216 } elseif (($admin == 'Y') && (!isAdmin())) {
217 // Only the Admin is allowed to enter this module!
220 // @TODO Nothing helped???
221 logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
230 // Still no luck or not found?
231 if (($found === false) && (!isExtensionActive('cache')) && ($ret != 'done')) {
232 // ----- Legacy module ----- ---- Module in base folder ---- --- Module with extension's name ---
233 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $mod))) || (isIncludeReadable(sprintf("%s.php", $mod))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $mod)))) {
234 // Data is missing so we add it
235 if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
236 // Since 0.3.6 we have a has_menu column, this took me a half hour
237 // to find a loop here... *sigh*
238 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
239 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`) VALUES
240 ('%s','Y','N','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
242 // Wrong/missing sql_patches!
243 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
244 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`) VALUES
245 ('%s','Y','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
248 // Everthing is fine?
249 if (SQL_AFFECTEDROWS() < 1) {
250 // Something bad happend!
254 // Destroy cache here
255 // @TODO Rewrite this to a filter
256 if ((getOutputMode() == 0) || (getOutputMode() == -1)) rebuildCacheFile('modules', 'modules');
259 unset($GLOBALS['module_status'][$mod]);
260 $ret = checkModulePermissions($mod_chk);
262 // Module not found we don't add it to the database
265 } elseif (($ret == 'cache_miss') && (getOutputMode() == 0)) {
266 // Rebuild the cache files
267 rebuildCacheFile('modules', 'modules');
268 } elseif ($found === false) {
269 // Problem with module detected
270 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s, output_mode=%s",
282 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
283 $GLOBALS['module_status'][$mod] = $ret;
287 // Add menu description pending on given file name (without path!)
288 function addMenuDescription ($accessLevel, $FQFN, $return = false, $output = true) {
289 // Use only filename of the FQFN...
290 $file = basename($FQFN);
297 // First we have to do some analysis...
298 if (substr($file, 0, 7) == 'action-') {
299 // This is an action file!
301 $search = substr($file, 7);
302 switch ($accessLevel) {
310 $modCheck = getModule();
313 $AND = " AND (`what`='' OR `what` IS NULL)";
314 } elseif (substr($file, 0, 5) == 'what-') {
315 // This is an admin what file!
317 $search = substr($file, 5);
319 switch ($accessLevel) {
326 $modCheck = getModule();
328 $AND = " AND `visible`='Y' AND `locked`='N'";
333 $dummy = substr($search, 0, -4);
334 $AND .= " AND `action`='".getModeAction($accessLevel, $dummy)."'";
335 } elseif (($accessLevel == 'sponsor') || ($accessLevel == "engine")) {
336 // Sponsor / engine menu
339 $modCheck = getModule();
345 $modCheck = getModule();
349 // Begin the navigation line
350 if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) {
351 $GLOBALS['nav_depth'] = 0;
352 $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>";
354 if ($return === false) $GLOBALS['nav_depth']++;
358 $prefix .= ' -> ';
360 // We need to remove .php and the end
361 if (substr($search, -4, 4) == '.php') {
363 $search = substr($search, 0, -4);
366 // Get the title from menu
367 $result = SQL_QUERY_ESC("SELECT title FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE %s='%s' ".$AND." LIMIT 1",
368 array($accessLevel, $type, $search), __FUNCTION__, __LINE__);
371 if (SQL_NUMROWS($result) == 1) {
373 list($ret) = SQL_FETCHROW($result);
375 // Shall we return it?
376 if ($return === true) {
379 } elseif (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
381 $OUT = $prefix . "<strong><a class=\"you_are_here\" href=\"{?URL?}/modules.php?module=" . $modCheck . '&' . $type . '=' . $search.$LINK_ADD . "\">" . $ret . "</a></strong>\n";
383 // Can we close the you-are-here navigation?
384 //* DEBUG: */ print(__LINE__."*".$type.'/'.getWhat()."*<br />");
385 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
386 //* DEBUG: */ print(__LINE__.'+'.$type."+<br />");
387 // Add closing div and br-tag
388 $OUT .= "</div><br />\n";
389 $GLOBALS['nav_depth'] = 0;
391 // Run the filter chain
392 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ""));
393 $OUT .= $ret['content'];
399 SQL_FREERESULT($result);
401 // Return or output HTML code?
403 // Output HTML code here
411 // Adds a menu (mode = guest/member/admin/sponsor) to output
412 function addMenu ($mode, $action, $what) {
413 // Init some variables
417 // is the menu action valid?
418 if (!isMenuActionValid($mode, $action, $what, true)) {
419 return getCode('MENU_NOT_VALID');
422 // Non-admin shall not see all menus
424 $AND = " AND `visible`='Y' AND `locked`='N'";
427 // Load SQL data and add the menu to the output stream...
428 $result_main = SQL_QUERY_ESC("SELECT `title`, `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$AND." ORDER BY `sort` ASC",
429 array($mode), __FUNCTION__, __LINE__);
431 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
432 if (SQL_NUMROWS($result_main) > 0) {
433 // There are menus available, so we simply display them... :)
434 $GLOBALS['rows'] = '';
435 while ($content = SQL_FETCHARRAY($result_main)) {
436 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].':'.getWhat()."*<br />");
438 enableBlockMode(false);
439 $action = $content['action'];
441 // Load menu header template
442 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
445 $result_sub = SQL_QUERY_ESC("SELECT `title` AS sub_title, `what` AS sub_what FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$AND." ORDER BY `sort`",
446 array($mode, $content['action']), __FUNCTION__, __LINE__);
448 // Get number of rows
449 $totalWhats = SQL_NUMROWS($result_sub);
451 // Do we have some entries?
452 if ($totalWhats > 0) {
456 // Load all sub menus
457 while ($content2 = SQL_FETCHARRAY($result_sub)) {
458 // Merge both arrays in one
459 $content = merge_array($content, $content2);
464 // Full file name for checking menu
465 //* DEBUG: */ print(__LINE__.":!!!!".$content['sub_what']."!!!<br />");
466 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
467 if (isIncludeReadable($inc)) {
468 // Mark currently selected menu - open
469 if ((!empty($what)) && (($what == $content['sub_what']))) {
474 $OUT .= "<a name=\"menu\" class=\"menu_blur\" href=\"{?URL?}/modules.php?module=".getModule()."&what=".$content['sub_what']."\" target=\"_self\">";
477 $OUT .= "<em style=\"cursor:help\" class=\"admin_note\" title=\"{--MENU_WHAT_404--}\">";
481 $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
483 if (isIncludeReadable($inc)) {
486 // Mark currently selected menu - close
487 if ((!empty($what)) && (($what == $content['sub_what']))) {
491 // Not found! - close
501 'what' => $content['sub_what']
504 // Add regular menu row or bottom row?
505 if ($cnt < $totalWhats) {
506 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
508 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
512 // This is a menu block... ;-)
516 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
517 if (isFileReadable($INC)) {
519 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
520 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
522 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
523 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
525 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
530 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
531 if (SQL_NUMROWS($result_main) > $main_cnt) {
533 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
535 // Should we display adverts in this menu?
536 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
537 // Display advert template
538 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
540 // Add seperator again
541 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
547 SQL_FREERESULT($result_main);
549 // Should we display adverts in this menu?
550 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
551 // Add seperator again
552 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
554 // Display advert template
555 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
560 'rows' => $GLOBALS['rows'],
564 // Load main template
565 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
566 loadTemplate('menu_table', false, $content);
570 // Checks wether the current user is a member
571 function isMember () {
572 // By default no member
575 // Fix missing 'last_online' array, damn stupid code :(((
576 // @TODO Try to rewrite this to one or more functions
577 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
579 // is the cache entry there?
580 if (isset($GLOBALS['is_member'])) {
582 return $GLOBALS['is_member'];
583 } elseif (getUserId() == 0) {
588 // Init global user data array
591 // Fix "deleted" cookies first
592 fixDeletedCookies(array('userid', 'u_hash'));
595 if ((isUserIdSet()) && (isSessionVariableSet('u_hash'))) {
596 // Cookies are set with values, but are they valid?
597 if (fetchUserData(getUserId()) === true) {
598 // Validate password by created the difference of it and the secret key
599 $valPass = generatePassString(getUserData('password'));
601 // Transfer last module and online time
602 $GLOBALS['last_online']['module'] = getUserData('last_module');
603 $GLOBALS['last_online']['online'] = getUserData('last_online');
605 // So did we now have valid data and an unlocked user?
606 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
607 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
610 // Maybe got locked etc.
611 //* DEBUG: */ print(__LINE__."!!!<br />");
612 destroyUserSession();
615 // Cookie data is invalid!
616 //* DEBUG: */ print(__LINE__."***<br />");
617 destroyUserSession();
620 // Cookie data is invalid!
621 //* DEBUG: */ print(__LINE__."///<br />");
622 destroyUserSession();
626 $GLOBALS['is_member'] = $ret;
632 // Fetch user data for given user id
633 function fetchUserData ($userid, $column='userid') {
634 // Don't look for invalid userids...
636 // Invalid, so abort here
637 debug_report_bug('User id ' . $userid . ' is invalid.');
638 } elseif (isset($GLOBALS['user_data'][$userid])) {
639 // Use cache, so it is fine
643 // By default none was found
646 // Do we have userid/refid?
647 if (($column == 'userid') || ($column == 'refid')) {
648 // Then secure the id
649 $userid = bigintval($userid);
652 // Query for the user
653 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
654 array($column, $userid), __FUNCTION__, __LINE__);
656 // Do we have a record?
657 if (SQL_NUMROWS($result) == 1) {
658 // Load data from cookies
659 $data = SQL_FETCHARRAY($result);
661 // Set the userid for later use
662 setCurrentUserId($data['userid']);
663 $GLOBALS['user_data'][getCurrentUserId()] = $data;
665 // Rewrite 'last_failure' if found
666 if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
667 // Backup the raw one and zero it
668 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
669 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = 0;
672 if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
673 // Seperate data/time
674 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure']);
676 // Seperate data and time again
677 $array['date'] = explode('-', $array[0]);
678 $array['time'] = explode(':', $array[1]);
680 // Now pass it to mktime()
681 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
693 $found = isUserDataValid();
697 SQL_FREERESULT($result);
703 // This patched function will reduce many SELECT queries for the specified or current admin login
704 function isAdmin ($admin = '') {
706 $ret = false; $passCookie = ''; $valPass = '';
707 //* DEBUG: */ print(__FUNCTION__.':'.$admin.'<br />');
709 // If admin login is not given take current from cookies...
710 if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
711 // Get admin login and password from session/cookies
712 $admin = getSession('admin_login');
713 $passCookie = getSession('admin_md5');
715 //* DEBUG: */ print(__FUNCTION__.':'.$admin.'/'.$passCookie.'<br />');
718 if (!isset($GLOBALS['is_admin'][$admin])) {
719 // Init it with failed
720 $GLOBALS['is_admin'][$admin] = false;
722 // Search in array for entry
723 if (isset($GLOBALS['admin_hash'])) {
725 $valPass = $GLOBALS['admin_hash'];
726 } elseif ((!empty($passCookie)) && (isAdminHashSet($admin) === true) && (!empty($admin))) {
727 // Login data is valid or not?
728 $valPass = generatePassString(getAdminHash($admin));
731 $GLOBALS['admin_hash'] = $valPass;
734 incrementStatsEntry('cache_hits');
735 } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (isAdminHashSet($admin) === false)) {
737 $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
738 array($admin), __FUNCTION__, __LINE__);
742 if (SQL_NUMROWS($result) == 1) {
743 // Admin login was found so let's load password from DB
744 list($passDB) = SQL_FETCHROW($result);
746 // Temporary cache it
747 setAdminHash($admin, $passDB);
749 // Generate password hash
750 $valPass = generatePassString($passDB);
754 SQL_FREERESULT($result);
757 if (!empty($valPass)) {
758 // Check if password is valid
759 //* DEBUG: */ print(__FUNCTION__ . ':(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie).'<br />');
760 $GLOBALS['is_admin'][$admin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
764 // Return result of comparision
765 return $GLOBALS['is_admin'][$admin];
768 // Generates a list of "max receiveable emails per day"
769 function addMaxReceiveList ($mode, $default = '', $return = false) {
775 // Guests (in the registration form) are not allowed to select 0 mails per day.
776 $result = SQL_QUERY("SELECT value, comment FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE value > 0 ORDER BY value",
777 __FUNCTION__, __LINE__);
781 // Members are allowed to set to zero mails per day (we will change this soon!)
782 $result = SQL_QUERY("SELECT value, comment FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY value",
783 __FUNCTION__, __LINE__);
787 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
791 // Some entries are found?
792 if (SQL_NUMROWS($result) > 0) {
794 while ($content = SQL_FETCHARRAY($result)) {
795 $OUT .= " <option value=\"".$content['value']."\"";
796 if (postRequestElement('max_mails') == $content['value']) $OUT .= ' selected="selected"';
797 $OUT .= ">".$content['value']." {--PER_DAY--}";
798 if (!empty($content['comment'])) $OUT .= " (".$content['comment'].')';
799 $OUT .= "</option>\n";
803 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
805 // Maybe the admin has to setup some maximum values?
806 debug_report_bug('Nothing is being done here?');
810 SQL_FREERESULT($result);
812 if ($return === true) {
813 // Return generated HTML code
816 // Output directly (default)
821 // Checks wether the given email address is used.
822 function isEmailTaken ($email) {
823 // Query the database
824 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE email LIKE '{PER}%s{PER}' LIMIT 1",
825 array($email), __FUNCTION__, __LINE__);
827 // Is the email there?
828 $ret = (SQL_NUMROWS($result) == 1);
831 SQL_FREERESULT($result);
837 // Validate the given menu action
838 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
839 // Is the cache entry there and we shall not update?
840 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
842 incrementStatsEntry('cache_hits');
844 // Then use this cache
845 return $GLOBALS['action_valid'][$mode][$action][$what];
848 // By default nothing is valid
851 // Look in all menus or only unlocked
853 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
855 //* DEBUG: */ print(__LINE__.':'.$mode.'/'.$action.'/'.$what."*<br />");
856 if (($mode != 'admin') && ($updateEntry === true)) {
857 // Update guest or member menu
858 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
859 array($mode, $action, $what), __FUNCTION__, __LINE__, false);
860 } elseif (($what != 'overview') && (!empty($what))) {
862 $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",
863 array($mode, $action, $what), __FUNCTION__, __LINE__, false);
865 // Admin login overview
866 $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",
867 array($mode, $action), __FUNCTION__, __LINE__, false);
871 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
873 // Should we look for affected rows (only update) or found rows?
874 if ($updateEntry === true) {
875 // Check updated/affected rows
876 $ret = (SQL_AFFECTEDROWS() == 1);
879 $ret = (SQL_NUMROWS($result) == 1);
883 SQL_FREERESULT($result);
886 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
892 // Send out mails depending on the 'mod/modes' combination
893 // @TODO Lame description for this function
894 function sendModeMails ($mod, $modes) {
896 if (fetchUserData(getUserId())) {
897 // Extract salt from cookie
898 $salt = substr(getSession('u_hash'), 0, -40);
900 // Now let's compare passwords
901 $hash = generatePassString(getUserData('password'));
903 // Does the hash match or should we change it?
904 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
905 // Load user's data 0 1 2 3 4 5 6 7
906 $result = SQL_QUERY_ESC("SELECT gender, surname, family, street_nr, country, zip, city, email FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND password='%s' LIMIT 1",
907 array(getUserId(), getUserData('password')), __FUNCTION__, __LINE__);
908 if (SQL_NUMROWS($result) == 1) {
910 $content = SQL_FETCHARRAY($result, 0, false);
913 SQL_FREERESULT($result);
916 $content['gender'] = translateGender($content['gender']);
918 // Clear/init the content variable
919 $content['message'] = '';
923 foreach ($modes as $mode) {
925 case 'normal': break; // Do not add any special lines
926 case 'email': // Email was changed!
927 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
930 case 'pass': // Password was changed
931 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
935 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
936 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
941 if (isExtensionActive('country')) {
942 // Replace code with description
943 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
946 // Merge content with data from POST
947 $content = merge_array($content, postRequestArray());
950 $message = loadEmailTemplate('member_mydata_notify', $content, getUserId());
952 if (getConfig('admin_notify') == 'Y') {
953 // The admin needs to be notified about a profile change
954 $message_admin = 'admin_mydata_notify';
955 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
963 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
965 // Output success message
966 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
969 default: // Unsupported module!
970 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
971 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
975 // Could not load profile data
976 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
979 // Passwords mismatch
980 $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
983 // Could not load profile
984 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
987 // Send email to user if required
988 if ((!empty($sub_mem)) && (!empty($message))) {
990 sendEmail($content['email'], $sub_mem, $message);
993 // Send only if no other error has occured
994 if (empty($content)) {
995 if ((!empty($sub_adm)) && (!empty($message_admin))) {
997 sendAdminNotification($sub_adm, $message_admin, $content, getUserId());
998 } elseif (getConfig('admin_notify') == 'Y') {
999 // Cannot send mails to admin!
1000 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
1003 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
1008 loadTemplate('admin_settings_saved', false, $content);
1011 // Get action value from mode (admin/guest/member) and what-value
1012 function getModeAction ($mode, $what) {
1016 //* DEBUG: */ print(__LINE__.'='.$mode.'/'.$what.'/'.getAction()."=<br />");
1017 if ((empty($what)) && ($mode != 'admin')) {
1018 $what = getConfig('index_home');
1021 if ($mode == 'admin') {
1022 // Action value for admin area
1023 if (isGetRequestElementSet('action')) {
1024 // Use from request!
1025 return getRequestElement('action');
1026 } elseif (isActionSet()) {
1027 // Get it directly from URL
1029 } elseif (($what == 'overview') || (!isWhatSet())) {
1030 // Default value for admin area
1033 } elseif (isActionSet()) {
1034 // Get it directly from URL
1037 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret.'<br />');
1039 // Does the module have a menu?
1040 if (ifModuleHasMenu($mode)) {
1041 // Rewriting modules to menu
1042 $mode = mapModuleToTable($mode);
1044 // Guest and member menu is 'main' as the default
1045 if (empty($ret)) $ret = 'main';
1047 // Load from database
1048 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
1049 array($mode, $what), __FUNCTION__, __LINE__);
1050 if (SQL_NUMROWS($result) == 1) {
1051 // Load action value and pray that this one is the right you want... ;-)
1052 list($ret) = SQL_FETCHROW($result);
1056 SQL_FREERESULT($result);
1057 } elseif ((!isExtensionInstalled('sql_patches')) && ($mode != 'admin')) {
1058 // No sql_patches installed, but maybe we need to register an admin?
1059 if (isAdminRegistered()) {
1060 // Redirect to admin area
1061 redirectToUrl('admin.php');
1065 // Return action value
1069 // Get category name back
1070 function getCategory ($cid) {
1071 // Default is not found
1072 $ret = getMessage('_CATEGORY_404');
1074 // Is the category id set?
1077 $ret = getMessage('_CATEGORY_NONE');
1078 } elseif ($cid > 0) {
1079 // Lookup the category in database
1080 $result = SQL_QUERY_ESC("SELECT cat FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
1081 array(bigintval($cid)), __FUNCTION__, __LINE__);
1082 if (SQL_NUMROWS($result) == 1) {
1083 // Category found... :-)
1084 list($ret) = SQL_FETCHROW($result);
1088 SQL_FREERESULT($result);
1095 // Get a string of "mail title" and price back
1096 function getPaymentTitlePrice ($pid, $full=false) {
1097 // Default is not found
1098 $ret = getMessage('_PAYMENT_404');
1100 // Load payment data
1101 $result = SQL_QUERY_ESC("SELECT mail_title, price FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1102 array(bigintval($pid)), __FUNCTION__, __LINE__);
1103 if (SQL_NUMROWS($result) == 1) {
1104 // Payment type found... :-)
1105 if ($full === false) {
1106 // Return only title
1107 list($ret) = SQL_FETCHROW($result);
1109 // Return title and price
1110 list($t, $p) = SQL_FETCHROW($result);
1111 $ret = $t.' / '.translateComma($p).' {?POINTS?}';
1116 SQL_FREERESULT($result);
1122 // Get (basicly) the price of given payment id
1123 function getPaymentPoints ($pid, $lookFor = 'price') {
1127 // Search for it in database
1128 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1129 array($lookFor, $pid), __FUNCTION__, __LINE__);
1131 // Is the entry there?
1132 if (SQL_NUMROWS($result) == 1) {
1133 // Payment type found... :-)
1134 list($ret) = SQL_FETCHROW($result);
1138 SQL_FREERESULT($result);
1144 // Remove a receiver's id from $receivers and add a link for him to confirm
1145 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
1146 // Default is not removed
1149 // Is the userid valid?
1151 // Remove entry from array
1152 unset($receivers[$key]);
1154 // Is there already a line for this user available?
1155 if ($stats_id > 0) {
1156 // Only when we got a real stats id continue searching for the entry
1157 $type = 'NORMAL'; $rowName = 'stats_id';
1158 if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1160 // Try to look the entry up
1161 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1162 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1164 // Was it *not* found?
1165 if (SQL_NUMROWS($result) == 0) {
1167 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
1168 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1176 SQL_FREERESULT($result);
1180 // Return status for sending routine
1184 // Calculate sum (default) or count records of given criteria
1185 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1187 //* DEBUG: */ print($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />');
1188 if ((empty($search)) && ($search != '0')) {
1189 // Count or sum whole table?
1190 if ($countRows === true) {
1191 // Count whole table
1192 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1193 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1196 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1197 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1199 } elseif (($countRows === true) || ($lookFor == 'userid')) {
1201 //* DEBUG: */ print("COUNT!<br />");
1202 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1203 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1206 //* DEBUG: */ print("SUM!<br />");
1207 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1208 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1212 list($ret) = SQL_FETCHROW($result);
1215 SQL_FREERESULT($result);
1218 if ((empty($ret)) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1221 } elseif (''.$ret.'' == '') {
1227 //* DEBUG: */ print 'ret='.$ret.'<br />';
1230 // Getter fro ref level percents
1231 function getReferalLevelPercents ($level) {
1235 // Do we have cache?
1236 if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
1237 // First look for level
1238 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1239 if ($key !== false) {
1241 $per = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1244 incrementStatsEntry('cache_hits');
1246 } elseif (!isExtensionActive('cache')) {
1248 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
1249 array(bigintval($level)), __FUNCTION__, __LINE__);
1252 if (SQL_NUMROWS($result_level) == 1) {
1254 list($per) = SQL_FETCHROW($result_level);
1258 SQL_FREERESULT($result_level);
1267 * Dynamic referal system, can also send mails!
1269 * subject = Subject line, write in lower-case letters and underscore is allowed
1270 * userid = Referal id wich should receive...
1271 * points = ... xxx points
1272 * sendNotify = shall I send the referal an email or not?
1273 * rid = inc/modules/guest/what-confirm.php need this
1274 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
1275 * add_mode = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
1276 * for default value will cause no referal will get points ever!!!)
1278 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = 0, $locked = false, $add_mode = 'ref') {
1279 //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
1280 // Convert mode to lower-case
1281 $add_mode = strtolower($add_mode);
1283 // When $userid = 0 add points to jackpot
1284 if (($userid == 0) && (isExtensionActive('jackpot'))) {
1285 // Add points to jackpot
1286 addPointsToJackpot($points);
1290 // Prepare data for the filter
1291 $filterData = array(
1292 'subject' => $subject,
1293 'userid' => $userid,
1294 'points' => $points,
1295 'notify' => $sendNotify,
1297 'locked' => $locked,
1299 'sub_mode' => $add_mode,
1303 runFilterChain('add_points', $filterData);
1305 // Count up referal depth
1306 if (!isset($GLOBALS['ref_level'])) {
1307 // Initialialize referal system
1308 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal system initialized!<br />");
1309 $GLOBALS['ref_level'] = 0;
1311 // Increase referal level
1312 $GLOBALS['ref_level']++;
1313 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />");
1316 // Default is 'normal' points
1319 // Which points, locked or normal?
1320 if ($locked === true) $data = 'locked_points';
1322 // Check user account
1323 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points}<br />");
1324 if (fetchUserData($userid)) {
1325 // This is the user and his ref
1326 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1329 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1330 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />");
1332 // Some percents found?
1334 // Calculate new points
1335 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />");
1336 $ref_points = $points * $per / 100;
1338 // Pay refback here if level > 0 and in ref-mode
1339 if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1340 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},data={$GLOBALS['cache_array']['add_userid'][$userid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - BEFORE!<br />");
1341 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1342 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},data={$GLOBALS['cache_array']['add_userid'][$userid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - AFTER!<br />");
1346 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`='%s' LIMIT 1",
1347 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1348 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},userid={$userid},depth={$GLOBALS['ref_level']},mode={$add_mode} - UPDATE! (".SQL_AFFECTEDROWS().")<br />");
1350 // No entry updated?
1351 if (SQL_AFFECTEDROWS() < 1) {
1352 // First ref in this level! :-)
1353 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,'%s',%s)",
1354 array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1355 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},userid={$userid},depth={$GLOBALS['ref_level']},mode={$add_mode} - INSERTED! (".SQL_AFFECTEDROWS().")<br />");
1358 // Points updated, maybe I shall send him an email?
1359 if (($sendNotify === true) && (getUserData('refid') > 0) && ($locked === false)) {
1363 'level' => bigintval($GLOBALS['ref_level']),
1364 'points' => $ref_points,
1365 'refid' => getUserData('refid')
1368 // Load email template
1369 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1371 sendEmail(getUserData('email'), THANX_REFERAL_ONE, $message);
1372 } elseif (($sendNotify) && (getUserData('refid') == 0) && ($locked === false) && ($add_mode == 'direct')) {
1375 'text' => getMessage('REASON_DIRECT_PAYMENT'),
1376 'points' => translateComma($ref_points)
1380 $message = loadEmailTemplate('add-points', $content, $userid);
1383 sendEmail(getUserData('email'), getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
1384 if (!isGetRequestElementSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1387 // Maybe there's another ref?
1388 if ((getUserData('refid') > 0) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1389 // Then let's credit him here...
1390 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref=".getUserData('refid').",points={$points} - ADVANCE!<br />");
1391 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
1396 //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
1399 // Updates the referal counter
1400 function updateReferalCounter ($userid) {
1401 // Make it sure referal level zero (member him-/herself) is at least selected
1402 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1403 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}<br />");
1406 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1407 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1409 // When no entry was updated then we have to create it here
1410 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS().'<br />');
1411 if (SQL_AFFECTEDROWS() < 1) {
1413 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1414 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1415 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid}<br />");
1421 // Check for his referal
1422 if (fetchUserData($userid)) {
1424 $ref = getUserData('refid');
1427 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref}<br />");
1429 // When he has a referal...
1430 if (($ref > 0) && ($ref != $userid)) {
1431 // Move to next referal level and count his counter one up!
1432 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />");
1433 $GLOBALS['cache_array']['ref_level'][$userid]++;
1434 updateReferalCounter($ref);
1435 } elseif ((($ref == $userid) || ($ref == 0)) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1436 // Remove cache here
1437 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />");
1438 rebuildCacheFile('refsystem', 'refsystem');
1442 $GLOBALS['cache_array']['ref_level'][$userid]--;
1444 // Handle refback here if extension is installed
1445 if (isExtensionActive('refback')) {
1446 updateRefbackTable($userid);
1450 // Sends out mail to all administrators. This function is no longer obsolete
1451 // because we need it when there is no ext-admins installed
1452 function sendAdminEmails ($subj, $message) {
1453 // Load all admin email addresses
1454 $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1455 while ($content = SQL_FETCHARRAY($result)) {
1456 // Send the email out
1457 sendEmail($content['email'], $subj, $message);
1461 SQL_FREERESULT($result);
1463 // Really simple... ;-)
1466 // Get id number from administrator's login name
1467 function getAdminId ($login) {
1468 // By default no admin is found
1472 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$login])) {
1473 // Use it if found to save SQL queries
1474 $ret = $GLOBALS['cache_array']['admin']['admin_id'][$login];
1476 // Update cache hits
1477 incrementStatsEntry('cache_hits');
1478 } elseif (!isExtensionActive('cache')) {
1479 // Load from database
1480 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1481 array($login), __FUNCTION__, __LINE__);
1482 if (SQL_NUMROWS($result) == 1) {
1483 list($ret) = SQL_FETCHROW($result);
1487 SQL_FREERESULT($result);
1492 // "Getter" for current admin id
1493 function getCurrentAdminId () {
1494 // Do we have cache?
1495 if (!isset($GLOBALS['current_admin_id'])) {
1496 // Get the admin login from session
1497 $adminLogin = getSession('admin_login');
1499 // "Solve" it into an id
1500 $adminId = getAdminId($adminLogin);
1502 // Remember in cache securely
1503 $GLOBALS['current_admin_id'] = bigintval($adminId);
1507 return $GLOBALS['current_admin_id'];
1510 // Get password hash from administrator's login name
1511 function getAdminHash ($admin) {
1512 // By default an invalid hash is returned
1515 if (isAdminHashSet($admin)) {
1517 $ret = $GLOBALS['cache_array']['admin']['password'][$admin];
1519 // Update cache hits
1520 incrementStatsEntry('cache_hits');
1521 } elseif (!isExtensionActive('cache')) {
1522 // Load from database
1523 $result = SQL_QUERY_ESC("SELECT password FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1524 array($admin), __FUNCTION__, __LINE__);
1525 if (SQL_NUMROWS($result) == 1) {
1527 list($ret) = SQL_FETCHROW($result);
1530 setAdminHash($admin, $ret);
1534 SQL_FREERESULT($result);
1539 // "Getter" for admin login
1540 function getAdminLogin ($adminId) {
1541 // By default a non-existent login is returned (other functions react on this!)
1544 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1546 $ret = $GLOBALS['cache_array']['admin']['login'][$adminId];
1548 // Update cache hits
1549 incrementStatsEntry('cache_hits');
1550 } elseif (!isExtensionActive('cache')) {
1551 // Load from database
1552 $result = SQL_QUERY_ESC("SELECT login FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1553 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1554 if (SQL_NUMROWS($result) == 1) {
1556 list($ret) = SQL_FETCHROW($result);
1559 $GLOBALS['cache_array']['admin']['login'][$adminId] = $ret;
1563 SQL_FREERESULT($result);
1568 // Get email address of admin id
1569 function getAdminEmail ($adminId) {
1570 // By default an invalid emails is returned
1573 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1575 $ret = $GLOBALS['cache_array']['admin']['email'][$adminId];
1577 // Update cache hits
1578 incrementStatsEntry('cache_hits');
1579 } elseif (!isExtensionActive('cache')) {
1580 // Load from database
1581 $result_admin_id = SQL_QUERY_ESC("SELECT email FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1582 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1583 if (SQL_NUMROWS($result_admin_id) == 1) {
1585 list($ret) = SQL_FETCHROW($result_admin_id);
1588 $GLOBALS['cache_array']['admin']['email'][$adminId] = $ret;
1592 SQL_FREERESULT($result_admin_id);
1599 // Get default ACL of admin id
1600 function getAdminDefaultAcl ($adminId) {
1601 // By default an invalid ACL value is returned
1604 // Is sql_patches there and was it found in cache?
1605 if (!isExtensionActive('sql_patches')) {
1606 // Not found, which is bad, so we need to allow all
1608 } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1610 $ret = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1612 // Update cache hits
1613 incrementStatsEntry('cache_hits');
1614 } elseif (!isExtensionActive('cache')) {
1615 // Load from database
1616 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1617 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1618 if (SQL_NUMROWS($result_admin_id) == 1) {
1620 list($ret) = SQL_FETCHROW($result_admin_id);
1623 $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $ret;
1627 SQL_FREERESULT($result_admin_id);
1634 // Generates an option list from various parameters
1635 function generateOptionList ($table, $id, $name, $default='', $special='', $where='') {
1637 if ($table == '/ARRAY/') {
1638 // Selection from array
1639 if (is_array($id) && is_array($name) && count($id) == count($name)) {
1641 foreach ($id as $idx => $value) {
1642 $ret .= '<option value="' . $value . '"';
1643 if ($default == $value) $ret .= ' selected="selected"';
1644 $ret .= '>' . $name[$idx] . '</option>';
1648 // Data from database
1650 if (!empty($special)) $SPEC = ', ' . $special;
1651 $ORDER = $name.$SPEC;
1652 if ($table == 'country') $ORDER = $special;
1653 $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY %s",
1654 array($id, $ORDER, $table, $name), __FUNCTION__, __LINE__);
1655 if (SQL_NUMROWS($result) > 0) {
1656 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1657 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1658 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1659 if (empty($special)) $add = '';
1660 $ret .= '<option value="' . $value . '"';
1661 if ($default == $value) $ret .= ' selected="selected"';
1662 if (!empty($add)) $add = ' ('.$add.')';
1663 $ret .= '>' . $title . $add . '</option>';
1667 SQL_FREERESULT($result);
1670 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1674 // Return - hopefully - the requested data
1677 // Activate exchange
1678 function FILTER_ACTIVATE_EXCHANGE () {
1679 // Is the extension 'user' there?
1680 if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == 0)) {
1681 // Silently abort here
1685 // Check total amount of users
1686 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1688 if ($totalUsers >= getConfig('activate_xchange')) {
1691 "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1692 "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1696 runFilterChain('run_sqls');
1698 // Update configuration
1699 updateConfiguration('activate_xchange' ,0);
1702 rebuildCacheFile('modules', 'modules');
1706 // Deletes a user account with given reason
1707 function deleteUserAccount ($userid, $reason) {
1709 $result = SQL_QUERY_ESC("SELECT
1710 (SUM(p.points) - d.used_points) AS points
1712 `{?_MYSQL_PREFIX?}_user_points` AS p
1714 `{?_MYSQL_PREFIX?}_user_data` AS d
1719 array(bigintval($userid)), __FUNCTION__, __LINE__);
1720 if (SQL_NUMROWS($result) == 1) {
1721 // Save his points to add them to the jackpot
1722 list($points) = SQL_FETCHROW($result);
1724 // Delete points entries as well
1725 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s", array(bigintval($userid)), __FUNCTION__, __LINE__);
1727 // Update mediadata as well
1728 if (getExtensionVersion('mediadata') >= '0.0.4') {
1730 updateMediadataEntry(array('total_points'), 'sub', $points);
1733 // Now, when we have all his points adds them do the jackpot!
1734 if (isExtensionActive('jackpot')) addPointsToJackpot($points);
1738 SQL_FREERESULT($result);
1740 // Delete category selections as well...
1741 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1742 array(bigintval($userid)), __FUNCTION__, __LINE__);
1744 // Remove from rallye if found
1745 if (isExtensionActive('rallye')) {
1746 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1747 array(bigintval($userid)), __FUNCTION__, __LINE__);
1750 // Now a mail to the user and that's all...
1751 $message = loadEmailTemplate('del-user', array('text' => $reason), $userid);
1752 sendEmail($userid, getMessage('ADMIN_DEL_ACCOUNT'), $message);
1754 // Ok, delete the account!
1755 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1758 // Generates meta description for given module and 'what' value
1759 function generateMetaDescriptionCode ($mod, $what) {
1760 // Exclude admin and member's area
1761 if (($mod != 'admin') && ($mod != 'login')) {
1762 // Construct dynamic description
1763 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . addMenuDescription('guest', 'what-'.$what, true);
1765 // Output it directly
1766 outputHtml('<meta name="description" content="' . $DESCR . '" />');
1770 unset($GLOBALS['ref_level']);
1773 // Gets the matching what name from module
1774 function getWhatFromModule ($modCheck) {
1775 // Is the request element set?
1776 if (isGetRequestElementSet('what')) {
1777 // Then return this!
1778 return getRequestElement('what');
1784 //* DEBUG: */ print(__LINE__.'!'.$modCheck."!<br />");
1785 switch ($modCheck) {
1792 // Is ext-sql_patches installed and newer than 0.0.5?
1793 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1794 // Use it from config
1795 $what = getConfig('index_home');
1797 // Use default 'welcome'
1807 // Return what value
1811 // Subtract points from database and mediadata cache
1812 function subtractPoints ($subject, $userid, $points) {
1813 // Add points to used points
1814 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1815 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1817 // Prepare filter data
1818 $filterData = array(
1819 'subject' => $subject,
1820 'userid' => $userid,
1821 'points' => $points,
1825 // Insert booking record
1826 runFilterChain('sub_points', $filterData);
1829 // "Getter" for total available receivers
1830 function getTotalReceivers ($mode='normal') {
1832 $result_all = SQL_QUERY("SELECT
1835 `{?_MYSQL_PREFIX?}_user_data`
1837 `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1838 __FUNCTION__, __LINE__);
1841 $numRows = SQL_NUMROWS($result_all);
1844 SQL_FREERESULT($result_all);
1850 // Returns HTML code with an "<option> list" of all categories
1851 function generateCategoryOptionsList ($mode) {
1852 // Prepare WHERE statement
1853 $whereStatement = " WHERE `visible`='Y'";
1854 if (isAdmin()) $whereStatement = '';
1856 // Initialize array...
1860 'userids' => array()
1864 $result = SQL_QUERY("SELECT id, cat FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort`", __FUNCTION__, __LINE__);
1865 if (SQL_NUMROWS($result) > 0) {
1866 // ... and begin loading stuff
1867 while ($content = SQL_FETCHARRAY($result)) {
1868 // Transfer some data
1869 $CATS['id'][] = $content['id'];
1870 $CATS['name'][] = $content['cat'];
1872 // Check which users are in this category
1873 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s",
1874 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1878 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
1879 while (list($ucat) = SQL_FETCHROW($result_userids)) {
1880 $result_ver = SQL_QUERY_ESC("SELECT
1883 `{?_MYSQL_PREFIX?}_user_data`
1885 `userid`=%s AND `status`='CONFIRMED' AND `receive_mails` > 0".runFilterChain('exclude_users', $mode)."
1887 array(bigintval($ucat)), __FUNCTION__, __LINE__);
1890 $userid_cnt += SQL_NUMROWS($result_ver);
1893 SQL_FREERESULT($result_ver);
1897 SQL_FREERESULT($result_userids);
1900 $CATS['userids'][] = $userid_cnt;
1904 SQL_FREERESULT($result);
1908 foreach ($CATS['id'] as $key => $value) {
1909 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1910 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1913 // No cateogries are defined yet
1914 $OUT = '<option class="member_failed">{--MEMBER_NO_CATS--}</option>';
1921 // Add bonus mail to queue
1922 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1923 // Is admin or bonus extension there?
1927 } elseif (!isExtensionActive('bonus')) {
1932 // Calculcate target sent
1933 $target = countSelection(explode(';', $receiverList));
1935 // Receiver is zero?
1936 if ($receiver == 0) {
1938 $receiver = $target;
1941 // HTML extension active?
1942 if (isExtensionActive('html_mail')) {
1943 // No HTML by default
1947 if ($mode == 'html') $HTML = 'Y';
1950 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1951 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1952 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1962 bigintval($receiver),
1964 ), __FUNCTION__, __LINE__);
1967 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1968 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1969 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1979 bigintval($receiver),
1980 ), __FUNCTION__, __LINE__);
1984 // Generate a receiver list for given category and maximum receivers
1985 function generateReceiverList ($cat, $receiver, $mode = '') {
1993 $cat = bigintval($cat);
1994 $receiver = bigintval($receiver);
1996 // Is the receiver zero and mode set?
1997 if (($receiver == 0) && (!empty($mode))) {
1998 // Auto-fix receiver maximum
1999 $receiver = getTotalReceivers($mode);
2005 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
2006 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
2009 // Exclude users in holiday?
2010 if (getExtensionVersion('holiday') >= '0.1.3') {
2011 // Add something for the holiday extension
2012 $CAT_WHERE .= " AND d.`holiday_active`='N'";
2015 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
2016 // Only include HTML receivers
2017 $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",
2020 ), __FUNCTION__, __LINE__);
2023 $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",
2026 ), __FUNCTION__, __LINE__);
2030 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
2032 while ($content = SQL_FETCHARRAY($result)) {
2033 // Add receiver when not empty
2034 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
2038 SQL_FREERESULT($result);
2040 // Remove trailing semicolon
2041 $receiverList = substr($receiverList, 0, -1);
2045 return $receiverList;
2048 // Get timestamp for given stats type and data
2049 function getTimestampFromUserStats ($type, $data, $userid = 0) {
2050 // Default timestamp is zero
2054 if ((isUserIdSet()) && ($userid == 0)) {
2055 $userid = getUserId();
2058 // Is the extension installed and updated?
2059 if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
2064 // Try to find the entry
2065 $result = SQL_QUERY_ESC("SELECT
2066 UNIX_TIMESTAMP(`inserted`) AS stamp
2068 `{?_MYSQL_PREFIX?}_user_stats_data`
2070 `userid`=%s AND `stats_type`='%s' AND `stats_data`='%s'
2076 ), __FUNCTION__, __LINE__);
2078 // Is the entry there?
2079 if (SQL_NUMROWS($result) == 1) {
2081 list($stamp) = SQL_FETCHROW($result);
2085 SQL_FREERESULT($result);
2091 // Inserts user stats
2092 function insertUserStatsRecord ($userid, $type, $data) {
2093 // Is the extension installed and updated?
2094 if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
2100 if ((!getTimestampFromUserStats($type, $data, $userid)) && (!is_array($data))) {
2102 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
2103 array(bigintval($userid), $type, $data), __FUNCTION__, __LINE__);
2104 } elseif (is_array($data)) {
2106 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$type},data={".gettype($data).": Invalid statistics data type!");
2110 // "Getter" for array for user refs and points in given level
2111 function getUserReferalPoints ($userid, $level) {
2112 //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
2113 // Default is no refs and no nickname
2117 // Do we have nickname extension installed?
2118 if (isExtensionActive('nickname')) {
2119 $add = ', ud.nickname';
2122 // Get refs from database
2123 $result = SQL_QUERY_ESC("SELECT
2124 ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2126 `{?_MYSQL_PREFIX?}_user_refs` AS ur
2128 `{?_MYSQL_PREFIX?}_user_points` AS up
2130 ur.refid=up.userid AND ur.level=0
2132 `{?_MYSQL_PREFIX?}_user_data` AS ud
2136 ur.userid=%s AND ur.level=%s
2137 ORDER BY ur.refid ASC",
2141 ), __FUNCTION__, __LINE__);
2143 // Are there some entries?
2144 if (SQL_NUMROWS($result) > 0) {
2145 // Fetch all entries
2146 while ($row = SQL_FETCHARRAY($result)) {
2147 // Get total points of this user
2148 $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
2150 // Get unconfirmed mails
2151 $row['unconfirmed'] = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
2153 // Init clickrate with zero
2154 $row['clickrate'] = 0;
2156 // Is at least one mail received?
2157 if ($row['emails_received'] > 0) {
2158 // Calculate clickrate
2159 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2162 // Activity is 'active' by default because if autopurge is not installed
2163 $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2165 // Is autopurge installed and the user inactive?
2166 if ((isExtensionActive('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online'])) {
2168 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2171 // Remove some entries
2172 unset($row['mails_confirmed']);
2173 unset($row['emails_received']);
2174 unset($row['last_online']);
2177 $refs[$row['id']] = $row;
2182 SQL_FREERESULT($result);
2185 //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
2189 // Recuce the amount of received emails for the receipients for given email
2190 function reduceRecipientReceivedMails ($column, $id, $count) {
2191 // Search for mail in database
2192 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2193 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2195 // Are there entries?
2196 if (SQL_NUMROWS($result) > 0) {
2197 // Now load all userids for one big query!
2198 // @TODO This can be somehow rewritten
2200 while (list($userid) = SQL_FETCHROW($result)) {
2201 $UIDs[$userid] = $userid;
2204 // Now update all user accounts
2205 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2206 array(implode(',', $UIDs), count($UIDs)), __FUNCTION__, __LINE__);
2210 SQL_FREERESULT($result);
2213 // Creates a new task
2214 function createNewTask ($subject, $notes, $taskType, $userid = 0, $adminId = 0, $strip = true) {
2215 // Insert the task data into the database
2216 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())",
2217 array($adminId, $userid, $taskType, $subject, smartAddSlashes($notes)), __FUNCTION__, __LINE__, true, $strip);