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 * 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 ($module) {
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($module, $GLOBALS['cache_array']['modules']['module']))) {
55 $data['title'] = $GLOBALS['cache_array']['modules']['title'][$module];
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($module), __FUNCTION__, __LINE__);
64 // Is the entry there?
65 if (SQL_NUMROWS($result)) {
66 // Get the title from database
67 $data = SQL_FETCHARRAY($result);
71 SQL_FREERESULT($result);
76 $data['title'] = trim($data['title']);
78 // Still no luck or empty title?
79 if (empty($data['title'])) {
81 $data['title'] = sprintf("%s (%s)", getMessage('LANG_UNKNOWN_MODULE'), $module);
82 if (SQL_NUMROWS($result) == '0') {
83 // Add module to database
84 $dummy = checkModulePermissions($module);
89 return $data['title'];
92 // "Getter" for module description
93 // @TODO Can we cache this?
94 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
97 $what = getConfig('index_home');
100 // Default is not found
101 $data['title'] = '??? (' . $what . ')';
104 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
109 ), __FUNCTION__, __LINE__);
111 // Is there an entry?
112 if (SQL_NUMROWS($result) == 1) {
114 $data = SQL_FETCHARRAY($result);
118 SQL_FREERESULT($result);
121 return $data['title'];
124 // Check validity of a given module name (no file extension)
125 function checkModulePermissions ($module = '') {
126 // Is it empty (default), then take the current one
127 if (empty($module)) $module = getModule();
130 if (isset($GLOBALS['module_status'][$module])) {
132 return $GLOBALS['module_status'][$module];
135 // Filter module name (names with low chars and underlines are fine!)
136 $module = preg_replace('/[^a-z_]/', '', $module);
138 // Check for prefix is a extension...
139 $modSplit = explode('_', $module);
140 $extension = ''; $module_chk = $module;
141 //* DEBUG: */ print(__LINE__."*".count($modSplit)."*/".$module."*<br />");
142 if (count($modSplit) == 2) {
143 // Okay, there is a seperator (_) in the name so is the first part a module?
144 //* DEBUG: */ print(__LINE__."*".$modSplit[0]."*<br />");
145 if (isExtensionActive($modSplit[0])) {
146 // The prefix is an extension's name, so let's set it
147 $extension = $modSplit[0]; $module = $modSplit[1];
151 // Major error in module registry is the default
154 // Check if script is installed if not return a 'done' to prevent some errors
155 if ((isInstallationPhase()) || (!isAdminRegistered())) {
156 // Not installed or no admin registered or in installation phase
168 // By default nothing is found
171 // Check if cache is latest version
172 if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
173 // Is the cache there?
174 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
175 if (isset($GLOBALS['cache_array']['modules']['locked'][$module_chk])) {
177 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache found.');
178 $data['locked'] = $GLOBALS['cache_array']['modules']['locked'][$module_chk];
179 $data['hidden'] = $GLOBALS['cache_array']['modules']['hidden'][$module_chk];
180 $data['admin_only'] = $GLOBALS['cache_array']['modules']['admin_only'][$module_chk];
181 $data['mem_only'] = $GLOBALS['cache_array']['modules']['mem_only'][$module_chk];
184 incrementStatsEntry('cache_hits');
187 // No, then we have to update it!
190 } elseif (!isExtensionActive('cache')) {
191 // Check for module in database
192 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
193 $result = SQL_QUERY_ESC("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
194 array($module_chk), __FUNCTION__, __LINE__);
195 if (SQL_NUMROWS($result) == 1) {
197 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Entry found.');
198 $data = SQL_FETCHARRAY($result);
200 } elseif (isDebugModeEnabled()) {
201 // Debug message only in debug-mode...
202 logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $module_chk . ' not found!');
206 SQL_FREERESULT($result);
208 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
210 // Is the module found?
211 if ($found === true) {
212 // Check returned values against current access permissions
214 // Admin access ----- Guest access ----- --- Guest or member? ---
215 if ((isAdmin()) || (($data['locked'] != 'Y') && ($data['admin_only'] != 'Y') && (($data['mem_only'] != 'Y') || (isMember())))) {
216 // If you are admin you are welcome for everything!
218 } elseif ($data['locked'] == 'Y') {
221 } elseif (($data['mem_only'] == 'Y') && (!isMember())) {
222 // You have to login first!
224 } elseif (($data['admin_only'] == 'Y') && (!isAdmin())) {
225 // Only the Admin is allowed to enter this module!
228 // @TODO Nothing helped???
229 logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
238 // Still no luck or not found?
239 if (($found === false) && (!isExtensionActive('cache')) && ($ret != 'done')) {
240 // ----- Legacy module ----- ---- Module in base folder ---- --- Module with extension's name ---
241 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $module))) || (isIncludeReadable(sprintf("%s.php", $module))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $module)))) {
242 // Data is missing so we add it
243 if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
244 // Since 0.3.6 we have a has_menu column, this took me a half hour
245 // to find a loop here... *sigh*
246 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
247 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`) VALUES
248 ('%s','Y','N','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
250 // Wrong/missing sql_patches!
251 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
252 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`) VALUES
253 ('%s','Y','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
256 // Everthing is fine?
257 if (SQL_AFFECTEDROWS() < 1) {
258 // Something bad happend!
262 // Destroy cache here
263 // @TODO Rewrite this to a filter
264 if ((getOutputMode() == '0') || (getOutputMode() == -1)) rebuildCacheFile('modules', 'modules');
267 unset($GLOBALS['module_status'][$module]);
268 $ret = checkModulePermissions($module_chk);
270 // Module not found we don't add it to the database
273 } elseif (($ret == 'cache_miss') && (getOutputMode() == '0')) {
274 // Rebuild the cache files
275 rebuildCacheFile('modules', 'modules');
276 } elseif ($found === false) {
277 // Problem with module detected
278 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s, output_mode=%s",
290 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
291 $GLOBALS['module_status'][$module] = $ret;
295 // Add menu description pending on given file name (without path!)
296 function addMenuDescription ($accessLevel, $FQFN, $return = false) {
297 // Use only filename of the FQFN...
298 $file = basename($FQFN);
305 // First we have to do some analysis...
306 if (substr($file, 0, 7) == 'action-') {
307 // This is an action file!
309 $search = substr($file, 7);
311 // Get access level from it
312 $modCheck = getModuleFromFileName($file, $accessLevel);
315 $ADD = " AND (`what`='' OR `what` IS NULL)";
316 } elseif (substr($file, 0, 5) == 'what-') {
317 // This is a 'what file'!
319 $search = substr($file, 5);
320 $ADD = " AND `visible`='Y' AND `locked`='N'";
322 // Get access level from it
323 $modCheck = getModuleFromFileName($file, $accessLevel);
325 // Do we have admin? Then display all
326 if (isAdmin()) $ADD = '';
328 $dummy = substr($search, 0, -4);
329 $ADD .= " AND `action`='".getModeAction($accessLevel, $dummy)."'";
330 } elseif (($accessLevel == 'sponsor') || ($accessLevel == 'engine')) {
331 // Sponsor / engine menu
334 $modCheck = getModule();
340 $modCheck = getModule();
344 // Begin the navigation line
345 if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) {
346 $GLOBALS['nav_depth'] = '0';
347 $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>';
349 if ($return === false) $GLOBALS['nav_depth']++;
353 $prefix .= ' -> ';
355 // We need to remove .php and the end
356 if (substr($search, -4, 4) == '.php') {
358 $search = substr($search, 0, -4);
361 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
363 $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>';
365 // Can we close the you-are-here navigation?
366 //* DEBUG: */ print(__LINE__."*".$type.'/'.getWhat()."*<br />");
367 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
368 //* DEBUG: */ print(__LINE__.'+'.$type."+<br />");
369 // Add closing div and br-tag
370 $OUT .= '</div><br />';
371 $GLOBALS['nav_depth'] = '0';
373 // Run the filter chain
374 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
376 // Add additional content
377 $OUT .= $ret['content'];
381 // Return or output HTML code?
382 if ($return === true) {
386 // Output HTML code here
391 // Adds a menu (mode = guest/member/admin/sponsor) to output
392 function addMenu ($mode, $action, $what) {
393 // Init some variables
397 // is the menu action valid?
398 if (!isMenuActionValid($mode, $action, $what, true)) {
399 return getCode('MENU_NOT_VALID');
402 // Non-admin shall not see all menus
404 $ADD = " AND `visible`='Y' AND `locked`='N'";
407 // Load SQL data and add the menu to the output stream...
408 $result_main = SQL_QUERY_ESC("SELECT `title`, `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$ADD." ORDER BY `sort` ASC",
409 array($mode), __FUNCTION__, __LINE__);
411 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
412 if (SQL_NUMROWS($result_main) > 0) {
413 // There are menus available, so we simply display them... :)
414 $GLOBALS['rows'] = '';
415 while ($content = SQL_FETCHARRAY($result_main)) {
416 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].':'.getWhat()."*<br />");
418 enableBlockMode(false);
419 $action = $content['action'];
421 // Load menu header template
422 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
425 $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 ".$ADD." ORDER BY `sort`",
426 array($mode, $content['action']), __FUNCTION__, __LINE__);
428 // Get number of rows
429 $totalWhats = SQL_NUMROWS($result_sub);
431 // Do we have some entries?
432 if ($totalWhats > 0) {
436 // Load all sub menus
437 while ($content2 = SQL_FETCHARRAY($result_sub)) {
438 // Merge both arrays in one
439 $content = merge_array($content, $content2);
444 // Full file name for checking menu
445 //* DEBUG: */ print(__LINE__.":!!!!".$content['sub_what']."!!!<br />");
446 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
447 if (isIncludeReadable($inc)) {
448 // Mark currently selected menu - open
449 if ((!empty($what)) && (($what == $content['sub_what']))) {
454 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
457 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
461 $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
463 if (isIncludeReadable($inc)) {
466 // Mark currently selected menu - close
467 if ((!empty($what)) && (($what == $content['sub_what']))) {
471 // Not found! - close
481 'what' => $content['sub_what']
484 // Add regular menu row or bottom row?
485 if ($cnt < $totalWhats) {
486 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
488 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
492 // This is a menu block... ;-)
496 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
497 if (isFileReadable($INC)) {
499 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
500 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
502 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
503 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
505 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
510 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
511 if (SQL_NUMROWS($result_main) > $main_cnt) {
513 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
515 // Should we display adverts in this menu?
516 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
517 // Display advert template
518 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
520 // Add seperator again
521 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
527 SQL_FREERESULT($result_main);
529 // Should we display adverts in this menu?
530 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
531 // Add seperator again
532 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
534 // Display advert template
535 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
540 'rows' => $GLOBALS['rows'],
544 // Load main template
545 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
546 loadTemplate('menu_table', false, $content);
550 // Checks wether the current user is a member
551 function isMember () {
552 // By default no member
555 // Fix missing 'last_online' array, damn stupid code :(((
556 // @TODO Try to rewrite this to one or more functions
557 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
559 // is the cache entry there?
560 if (isset($GLOBALS['is_member'])) {
562 return $GLOBALS['is_member'];
563 } elseif (getMemberId() == '0') {
567 // Transfer userid=>current
568 setCurrentUserid(getMemberId());
571 // Init global user data array
574 // Fix "deleted" cookies first
575 fixDeletedCookies(array('userid', 'u_hash'));
578 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) {
579 // Cookies are set with values, but are they valid?
580 if (fetchUserData(getMemberId()) === true) {
581 // Validate password by created the difference of it and the secret key
582 $valPass = generatePassString(getUserData('password'));
584 // Transfer last module and online time
585 $GLOBALS['last_online']['module'] = getUserData('last_module');
586 $GLOBALS['last_online']['online'] = getUserData('last_online');
588 // So did we now have valid data and an unlocked user?
589 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
590 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
593 // Maybe got locked etc.
594 logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status'));
595 destroyMemberSession();
598 // Cookie data is invalid!
599 destroyMemberSession();
602 // Cookie data is invalid!
603 destroyMemberSession();
607 $GLOBALS['is_member'] = $ret;
613 // Fetch user data for given user id
614 function fetchUserData ($userid, $column = 'userid') {
615 // If we should look for userid secure&set it here
616 if (substr($column, -2, 2) == 'id') {
618 $userid = bigintval($userid);
621 setCurrentUserId($userid);
623 // Don't look for invalid userids...
625 // Invalid, so abort here
626 debug_report_bug('User id ' . $userid . ' is invalid.');
627 } elseif (isUserDataValid()) {
628 // Use cache, so it is fine
631 } elseif (isUserDataValid()) {
632 // Use cache, so it is fine
637 // By default none was found
642 if (isExtensionInstalledAndNewer('user', '0.3.5')) $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
644 // Query for the user
645 $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
646 array($column, $userid), __FUNCTION__, __LINE__);
648 // Do we have a record?
649 if (SQL_NUMROWS($result) == 1) {
650 // Load data from cookies
651 $data = SQL_FETCHARRAY($result);
653 // Set the userid for later use
654 setCurrentUserId($data['userid']);
655 $GLOBALS['user_data'][getCurrentUserId()] = $data;
657 // Rewrite 'last_failure' if found
658 if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
659 // Backup the raw one and zero it
660 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
661 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = '0';
664 if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
665 // Seperate data/time
666 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
668 // Seperate data and time again
669 $array['date'] = explode('-', $array[0]);
670 $array['time'] = explode(':', $array[1]);
672 // Now pass it to mktime()
673 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
685 $found = isUserDataValid();
689 SQL_FREERESULT($result);
695 // This patched function will reduce many SELECT queries for the specified or current admin login
696 function isAdmin ($admin = '') {
698 $ret = false; $passCookie = ''; $valPass = '';
699 //* DEBUG: */ print(__FUNCTION__.':'.$admin.'<br />');
701 // If admin login is not given take current from cookies...
702 if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
703 // Get admin login and password from session/cookies
704 $admin = getSession('admin_login');
705 $passCookie = getSession('admin_md5');
707 //* DEBUG: */ print(__FUNCTION__.':'.$admin.'/'.$passCookie.'<br />');
710 if (!isset($GLOBALS['is_admin'][$admin])) {
711 // Init it with failed
712 $GLOBALS['is_admin'][$admin] = false;
714 // Search in array for entry
715 if (isset($GLOBALS['admin_hash'])) {
717 $valPass = $GLOBALS['admin_hash'];
718 } elseif ((!empty($passCookie)) && (isAdminHashSet($admin) === true) && (!empty($admin))) {
719 // Login data is valid or not?
720 $valPass = generatePassString(getAdminHash($admin));
723 $GLOBALS['admin_hash'] = $valPass;
726 incrementStatsEntry('cache_hits');
727 } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (isAdminHashSet($admin) === false)) {
728 // Get admin hash and hash it
729 $valPass = generatePassString(getAdminHash($admin));
732 if (!empty($valPass)) {
733 // Check if password is valid
734 //* DEBUG: */ print(__FUNCTION__ . ':(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie).'<br />');
735 $GLOBALS['is_admin'][$admin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
739 // Return result of comparision
740 return $GLOBALS['is_admin'][$admin];
743 // Generates a list of "max receiveable emails per day"
744 function addMaxReceiveList ($mode, $default = '', $return = false) {
750 // Guests (in the registration form) are not allowed to select 0 mails per day.
751 $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC",
752 __FUNCTION__, __LINE__);
756 // Members are allowed to set to zero mails per day (we will change this soon!)
757 $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC",
758 __FUNCTION__, __LINE__);
762 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
766 // Some entries are found?
767 if (SQL_NUMROWS($result) > 0) {
769 while ($content = SQL_FETCHARRAY($result)) {
770 $OUT .= ' <option value="' . $content['value'] . '"';
771 if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
772 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
773 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
778 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
780 // Maybe the admin has to setup some maximum values?
781 debug_report_bug('Nothing is being done here?');
785 SQL_FREERESULT($result);
787 if ($return === true) {
788 // Return generated HTML code
791 // Output directly (default)
796 // Checks wether the given email address is used.
797 function isEmailTaken ($email) {
798 // Query the database
799 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '{PER}%s{PER}' OR `email` LIKE '{PER}%s{PER}' LIMIT 1",
800 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
802 // Is the email there?
803 $ret = (SQL_NUMROWS($result) == 1);
806 SQL_FREERESULT($result);
812 // Validate the given menu action
813 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
814 // Is the cache entry there and we shall not update?
815 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
817 incrementStatsEntry('cache_hits');
819 // Then use this cache
820 return $GLOBALS['action_valid'][$mode][$action][$what];
823 // By default nothing is valid
826 // Look in all menus or only unlocked
828 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
830 //* DEBUG: */ print(__LINE__.':'.$mode.'/'.$action.'/'.$what."*<br />");
831 if (($mode != 'admin') && ($updateEntry === true)) {
832 // Update guest or member menu
833 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
834 array($mode, $action, $what), __FUNCTION__, __LINE__, false);
835 } elseif (($what != 'overview') && (!empty($what))) {
837 $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",
838 array($mode, $action, $what), __FUNCTION__, __LINE__, false);
840 // Admin login overview
841 $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",
842 array($mode, $action), __FUNCTION__, __LINE__, false);
846 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
848 // Should we look for affected rows (only update) or found rows?
849 if ($updateEntry === true) {
850 // Check updated/affected rows
851 $ret = (SQL_AFFECTEDROWS() == 1);
854 $ret = (SQL_NUMROWS($result) == 1);
858 SQL_FREERESULT($result);
861 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
867 // Get action value from mode (admin/guest/member) and what-value
868 function getModeAction ($mode, $what) {
870 $data['action'] = '';
872 //* DEBUG: */ print(__LINE__.'='.$mode.'/'.$what.'/'.getAction()."=<br />");
873 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
874 // sql_patches is missing so choose depending on mode
878 } elseif ($mode == 'admin') {
885 } elseif ((empty($what)) && ($mode != 'admin')) {
886 // Use configured 'home'
887 $what = getConfig('index_home');
890 if ($mode == 'admin') {
891 // Action value for admin area
892 if (isGetRequestParameterSet('action')) {
894 return getRequestParameter('action');
895 } elseif (isActionSet()) {
896 // Get it directly from URL
898 } elseif (($what == 'overview') || (!isWhatSet())) {
899 // Default value for admin area
900 $data['action'] = 'login';
902 } elseif (isActionSet()) {
903 // Get it directly from URL
906 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$data['action'].'<br />');
908 // Does the module have a menu?
909 if (ifModuleHasMenu($mode)) {
910 // Rewriting modules to menu
911 $mode = mapModuleToTable($mode);
913 // Guest and member menu is 'main' as the default
914 if (empty($data['action'])) $data['action'] = 'main';
916 // Load from database
917 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
918 array($mode, $what), __FUNCTION__, __LINE__);
919 if (SQL_NUMROWS($result) == 1) {
920 // Load action value and pray that this one is the right you want... ;-)
921 $data = SQL_FETCHARRAY($result);
925 SQL_FREERESULT($result);
926 } elseif ((!isExtensionInstalled('sql_patches')) && (($mode != 'admin') && ($mode != 'unknown'))) {
927 // No sql_patches installed, but maybe we need to register an admin?
928 if (isAdminRegistered()) {
929 // Redirect to admin area
930 redirectToUrl('admin.php');
934 // Return action value
935 return $data['action'];
938 // Get category name back
939 function getCategory ($cid) {
940 // Default is not found
941 $data['cat'] = getMessage('_CATEGORY_404');
943 // Is the category id set?
946 $data['cat'] = getMessage('_CATEGORY_NONE');
947 } elseif ($cid > 0) {
948 // Lookup the category in database
949 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
950 array(bigintval($cid)), __FUNCTION__, __LINE__);
951 if (SQL_NUMROWS($result) == 1) {
952 // Category found... :-)
953 $data = SQL_FETCHARRAY($result);
957 SQL_FREERESULT($result);
964 // Get a string of "mail title" and price back
965 function getPaymentTitlePrice ($pid, $full=false) {
966 // Default is not found
967 $ret = getMessage('_PAYMENT_404');
970 $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
971 array(bigintval($pid)), __FUNCTION__, __LINE__);
972 if (SQL_NUMROWS($result) == 1) {
973 // Payment type found... :-)
974 $data = SQL_FETCHARRAY($result);
976 // Only title or also including price?
977 if ($full === false) {
978 $ret = $data['mail_title'];
980 $ret = $data['mail_title'] . ' / ' . translateComma($data['price']) . ' {?POINTS?}';
985 SQL_FREERESULT($result);
991 // Get (basicly) the price of given payment id
992 function getPaymentPoints ($pid, $lookFor = 'price') {
994 $data[$lookFor] = '-1';
996 // Search for it in database
997 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
998 array($lookFor, $pid), __FUNCTION__, __LINE__);
1000 // Is the entry there?
1001 if (SQL_NUMROWS($result) == 1) {
1002 // Payment type found... :-)
1003 $data = SQL_FETCHARRAY($result);
1007 SQL_FREERESULT($result);
1010 return $data[$lookFor];
1013 // Remove a receiver's id from $receivers and add a link for him to confirm
1014 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
1015 // Default is not removed
1018 // Is the userid valid?
1020 // Remove entry from array
1021 unset($receivers[$key]);
1023 // Is there already a line for this user available?
1024 if ($stats_id > 0) {
1025 // Only when we got a real stats id continue searching for the entry
1026 $type = 'NORMAL'; $rowName = 'stats_id';
1027 if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1029 // Try to look the entry up
1030 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1031 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1033 // Was it *not* found?
1034 if (SQL_NUMROWS($result) == '0') {
1036 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
1037 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1045 SQL_FREERESULT($result);
1049 // Return status for sending routine
1053 // Calculate sum (default) or count records of given criteria
1054 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1058 //* DEBUG: */ print($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />');
1059 if ((empty($search)) && ($search != '0')) {
1060 // Count or sum whole table?
1061 if ($countRows === true) {
1062 // Count whole table
1063 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1064 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1067 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1068 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1070 } elseif (($countRows === true) || ($lookFor == 'userid')) {
1072 //* DEBUG: */ print("COUNT!<br />");
1073 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1074 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1077 //* DEBUG: */ print("SUM!<br />");
1078 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1079 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1083 $data = SQL_FETCHARRAY($result);
1086 SQL_FREERESULT($result);
1089 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1091 $data['res'] = '0.00000';
1092 } elseif (''.$data['res'].'' == '') {
1098 //* DEBUG: */ print 'ret=' . $data['res'] . '<br />';
1099 return $data['res'];
1101 // Getter fro ref level percents
1102 function getReferalLevelPercents ($level) {
1104 $data['percents'] = '0';
1106 // Do we have cache?
1107 if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
1108 // First look for level
1109 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1110 if ($key !== false) {
1112 $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1115 incrementStatsEntry('cache_hits');
1117 } elseif (!isExtensionActive('cache')) {
1119 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
1120 array(bigintval($level)), __FUNCTION__, __LINE__);
1123 if (SQL_NUMROWS($result_level) == 1) {
1125 $data = SQL_FETCHARRAY($result_level);
1129 SQL_FREERESULT($result_level);
1133 return $data['percents'];
1138 * Dynamic referal system, can also send mails!
1140 * subject = Subject line, write in lower-case letters and underscore is allowed
1141 * userid = Referal id wich should receive...
1142 * points = ... xxx points
1143 * sendNotify = shall I send the referal an email or not?
1144 * rid = inc/modules/guest/what-confirm.php need this
1145 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
1146 * add_mode = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
1147 * for default value will cause no referal will get points ever!!!)
1149 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
1150 //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
1151 // Convert mode to lower-case
1152 $add_mode = strtolower($add_mode);
1154 // When $userid = '0' add points to jackpot
1155 if (($userid == '0') && (isExtensionActive('jackpot'))) {
1156 // Add points to jackpot
1157 addPointsToJackpot($points);
1161 // Prepare data for the filter
1162 $filterData = array(
1163 'subject' => $subject,
1164 'userid' => $userid,
1165 'points' => $points,
1166 'notify' => $sendNotify,
1168 'locked' => $locked,
1170 'sub_mode' => $add_mode,
1174 runFilterChain('add_points', $filterData);
1176 // Count up referal depth
1177 if (!isset($GLOBALS['ref_level'])) {
1178 // Initialialize referal system
1179 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal system initialized!<br />");
1180 $GLOBALS['ref_level'] = '0';
1182 // Increase referal level
1183 $GLOBALS['ref_level']++;
1184 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />");
1187 // Default is 'normal' points
1190 // Which points, locked or normal?
1191 if ($locked === true) $data = 'locked_points';
1193 // Check user account
1194 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points}<br />");
1195 if (fetchUserData($userid)) {
1196 // This is the user and his ref
1197 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1200 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1201 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />");
1203 // Some percents found?
1205 // Calculate new points
1206 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />");
1207 $ref_points = $points * $per / 100;
1209 // Pay refback here if level > 0 and in ref-mode
1210 if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1211 //* 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 />");
1212 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1213 //* 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 />");
1217 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`='%s' LIMIT 1",
1218 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1219 //* 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 />");
1221 // No entry updated?
1222 if (SQL_AFFECTEDROWS() < 1) {
1223 // First ref in this level! :-)
1224 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,'%s',%s)",
1225 array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1226 //* 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 />");
1229 // Points updated, maybe I shall send him an email?
1230 if (($sendNotify === true) && (getUserData('refid') > 0) && ($locked === false)) {
1234 'level' => bigintval($GLOBALS['ref_level']),
1235 'points' => $ref_points,
1236 'refid' => getUserData('refid')
1239 // Load email template
1240 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1243 sendEmail($userid, getMessage('THANX_REFERAL_ONE_SUBJECT'), $message);
1244 } elseif (($sendNotify) && (getUserData('refid') == '0') && ($locked === false) && ($add_mode == 'direct')) {
1247 'text' => getMessage('REASON_DIRECT_PAYMENT'),
1248 'points' => translateComma($ref_points)
1252 $message = loadEmailTemplate('add-points', $content, $userid);
1255 sendEmail($userid, getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
1256 if (!isGetRequestParameterSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1259 // Maybe there's another ref?
1260 if ((getUserData('refid') > 0) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1261 // Then let's credit him here...
1262 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref=".getUserData('refid').",points={$points} - ADVANCE!<br />");
1263 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
1268 //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
1271 // Updates the referal counter
1272 function updateReferalCounter ($userid) {
1273 // Make it sure referal level zero (member him-/herself) is at least selected
1274 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1275 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}<br />");
1278 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1279 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1281 // When no entry was updated then we have to create it here
1282 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS().'<br />');
1283 if (SQL_AFFECTEDROWS() < 1) {
1285 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1286 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1287 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid}<br />");
1293 // Check for his referal
1294 if (fetchUserData($userid)) {
1296 $ref = getUserData('refid');
1299 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref}<br />");
1301 // When he has a referal...
1302 if (($ref > 0) && ($ref != $userid)) {
1303 // Move to next referal level and count his counter one up!
1304 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />");
1305 $GLOBALS['cache_array']['ref_level'][$userid]++;
1306 updateReferalCounter($ref);
1307 } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1308 // Remove cache here
1309 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />");
1310 rebuildCacheFile('refsystem', 'refsystem');
1314 $GLOBALS['cache_array']['ref_level'][$userid]--;
1316 // Handle refback here if extension is installed
1317 if (isExtensionActive('refback')) {
1318 updateRefbackTable($userid);
1322 // Sends out mail to all administrators. This function is no longer obsolete
1323 // because we need it when there is no ext-admins installed
1324 function sendAdminEmails ($subj, $message) {
1325 // Load all admin email addresses
1326 $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1327 while ($content = SQL_FETCHARRAY($result)) {
1328 // Send the email out
1329 sendEmail($content['email'], $subj, $message);
1333 SQL_FREERESULT($result);
1335 // Really simple... ;-)
1338 // Get id number from administrator's login name
1339 function getAdminId ($login) {
1340 // By default no admin is found
1344 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$login])) {
1345 // Use it if found to save SQL queries
1346 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$login];
1348 // Update cache hits
1349 incrementStatsEntry('cache_hits');
1350 } elseif (!isExtensionActive('cache')) {
1351 // Load from database
1352 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1353 array($login), __FUNCTION__, __LINE__);
1355 // Do we have an entry?
1356 if (SQL_NUMROWS($result) == 1) {
1358 $data = SQL_FETCHARRAY($result);
1362 SQL_FREERESULT($result);
1369 // "Getter" for current admin id
1370 function getCurrentAdminId () {
1371 // Do we have cache?
1372 if (!isset($GLOBALS['current_admin_id'])) {
1373 // Get the admin login from session
1374 $adminLogin = getSession('admin_login');
1376 // "Solve" it into an id
1377 $adminId = getAdminId($adminLogin);
1379 // Remember in cache securely
1380 $GLOBALS['current_admin_id'] = bigintval($adminId);
1384 return $GLOBALS['current_admin_id'];
1387 // Get password hash from administrator's login name
1388 function getAdminHash ($admin) {
1389 // By default an invalid hash is returned
1390 $data['password'] = '-1';
1392 if (isAdminHashSet($admin)) {
1394 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$admin];
1396 // Update cache hits
1397 incrementStatsEntry('cache_hits');
1398 } elseif (!isExtensionActive('cache')) {
1399 // Load from database
1400 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1401 array($admin), __FUNCTION__, __LINE__);
1403 // Do we have an entry?
1404 if (SQL_NUMROWS($result) == 1) {
1406 $data = SQL_FETCHARRAY($result);
1409 setAdminHash($admin, $data['password']);
1413 SQL_FREERESULT($result);
1416 // Return password hash
1417 return $data['password'];
1420 // "Getter" for admin login
1421 function getAdminLogin ($adminId) {
1422 // By default a non-existent login is returned (other functions react on this!)
1423 $data['login'] = '***';
1425 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1427 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1429 // Update cache hits
1430 incrementStatsEntry('cache_hits');
1431 } elseif (!isExtensionActive('cache')) {
1432 // Load from database
1433 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1434 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1437 if (SQL_NUMROWS($result) == 1) {
1439 $data = SQL_FETCHARRAY($result);
1442 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1446 SQL_FREERESULT($result);
1449 // Return the result
1450 return $data['login'];
1453 // Get email address of admin id
1454 function getAdminEmail ($adminId) {
1455 // By default an invalid emails is returned
1456 $data['email'] = '***';
1458 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1460 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1462 // Update cache hits
1463 incrementStatsEntry('cache_hits');
1464 } elseif (!isExtensionActive('cache')) {
1465 // Load from database
1466 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1467 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1470 if (SQL_NUMROWS($result_admin_id) == 1) {
1472 $data = SQL_FETCHARRAY($result_admin_id);
1475 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1479 SQL_FREERESULT($result_admin_id);
1483 return $data['email'];
1486 // Get default ACL of admin id
1487 function getAdminDefaultAcl ($adminId) {
1488 // By default an invalid ACL value is returned
1489 $data['default_acl'] = '***';
1491 // Is sql_patches there and was it found in cache?
1492 if (!isExtensionActive('sql_patches')) {
1493 // Not found, which is bad, so we need to allow all
1494 $data['default_acl'] = 'allow';
1495 } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1497 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1499 // Update cache hits
1500 incrementStatsEntry('cache_hits');
1501 } elseif (!isExtensionActive('cache')) {
1502 // Load from database
1503 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1504 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1505 if (SQL_NUMROWS($result_admin_id) == 1) {
1507 $data = SQL_FETCHARRAY($result_admin_id);
1510 $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1514 SQL_FREERESULT($result_admin_id);
1517 // Return default ACL
1518 return $data['default_acl'];
1521 // Generates an option list from various parameters
1522 function generateOptionList ($table, $id, $name, $default='', $special='', $where='', $disabled=array()) {
1524 if ($table == '/ARRAY/') {
1525 // Selection from array
1526 if ((is_array($id)) && (is_array($name)) && (count($id)) == (count($name))) {
1528 foreach ($id as $idx => $value) {
1529 $ret .= '<option value="' . $value . '"';
1530 if ($default == $value) {
1531 // Selected by default
1532 $ret .= ' selected="selected"';
1533 } elseif (isset($disabled[$value])) {
1535 $ret .= ' disabled="disabled"';
1537 $ret .= '>' . $name[$idx] . '</option>';
1540 // Problem in request
1541 debug_report_bug('Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name));
1544 // Data from database
1545 $SPEC = ', `' . $id . '`';
1546 if (!empty($special)) $SPEC = ', `' . $special . '`';
1548 // Query the database
1549 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1555 ), __FUNCTION__, __LINE__);
1558 if (SQL_NUMROWS($result) > 0) {
1559 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1560 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1561 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1562 if (empty($special)) $add = '';
1563 $ret .= '<option value="' . $value . '"';
1564 if ($default == $value) {
1565 // Selected by default
1566 $ret .= ' selected="selected"';
1567 } elseif (isset($disabled[$value])) {
1569 $ret .= ' disabled="disabled"';
1571 if (!empty($add)) $add = ' ('.$add.')';
1572 $ret .= '>' . $title . $add . '</option>';
1576 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1580 SQL_FREERESULT($result);
1583 // Return - hopefully - the requested data
1586 // Activate exchange
1587 function FILTER_ACTIVATE_EXCHANGE () {
1588 // Is the extension 'user' there?
1589 if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) {
1590 // Silently abort here
1594 // Check total amount of users
1595 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1597 if ($totalUsers >= getConfig('activate_xchange')) {
1600 "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1601 "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1605 runFilterChain('run_sqls');
1607 // Update configuration
1608 updateConfiguration('activate_xchange' ,0);
1611 rebuildCacheFile('modules', 'modules');
1615 // Deletes a user account with given reason
1616 function deleteUserAccount ($userid, $reason) {
1618 $data['points'] = '0';
1620 $result = SQL_QUERY_ESC("SELECT
1621 (SUM(p.points) - d.used_points) AS points
1623 `{?_MYSQL_PREFIX?}_user_points` AS p
1625 `{?_MYSQL_PREFIX?}_user_data` AS d
1630 array(bigintval($userid)), __FUNCTION__, __LINE__);
1632 // Do we have an entry?
1633 if (SQL_NUMROWS($result) == 1) {
1634 // Save his points to add them to the jackpot
1635 $data = SQL_FETCHARRAY($result);
1637 // Delete points entries as well
1638 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s", array(bigintval($userid)), __FUNCTION__, __LINE__);
1640 // Update mediadata as well
1641 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1643 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1646 // Now, when we have all his points adds them do the jackpot!
1647 if (isExtensionActive('jackpot')) addPointsToJackpot($data['points']);
1651 SQL_FREERESULT($result);
1653 // Delete category selections as well...
1654 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1655 array(bigintval($userid)), __FUNCTION__, __LINE__);
1657 // Remove from rallye if found
1658 // @TODO Rewrite this to a filter
1659 if (isExtensionActive('rallye')) {
1660 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1661 array(bigintval($userid)), __FUNCTION__, __LINE__);
1664 // Add reason and translate points
1665 $data['text'] = $reason;
1666 $data['points'] = translateComma($data['points']);
1668 // Now a mail to the user and that's all...
1669 $message = loadEmailTemplate('del-user', $data, $userid);
1670 sendEmail($userid, getMessage('ADMIN_DEL_ACCOUNT'), $message);
1672 // Ok, delete the account!
1673 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1676 // Generates meta description for given module and 'what' value
1677 function generateMetaDescriptionCode ($module, $what) {
1678 // Only include from guest area
1679 if ($module == 'index') {
1680 // Construct dynamic description
1681 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', $what);
1683 // Output it directly
1684 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1688 unset($GLOBALS['ref_level']);
1691 // Gets the matching what name from module
1692 function getWhatFromModule ($modCheck) {
1693 // Is the request element set?
1694 if (isGetRequestParameterSet('what')) {
1695 // Then return this!
1696 return getRequestParameter('what');
1702 //* DEBUG: */ print(__LINE__.'!'.$modCheck."!<br />");
1703 switch ($modCheck) {
1710 // Is ext-sql_patches installed and newer than 0.0.5?
1711 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1712 // Use it from config
1713 $what = getConfig('index_home');
1715 // Use default 'welcome'
1725 // Return what value
1729 // Subtract points from database and mediadata cache
1730 function subtractPoints ($subject, $userid, $points) {
1731 // Add points to used points
1732 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1733 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1735 // Prepare filter data
1736 $filterData = array(
1737 'subject' => $subject,
1738 'userid' => $userid,
1739 'points' => $points,
1743 // Insert booking record
1744 runFilterChain('sub_points', $filterData);
1747 // "Getter" for total available receivers
1748 function getTotalReceivers ($mode='normal') {
1750 $result_all = SQL_QUERY("SELECT
1753 `{?_MYSQL_PREFIX?}_user_data`
1755 `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1756 __FUNCTION__, __LINE__);
1759 $numRows = SQL_NUMROWS($result_all);
1762 SQL_FREERESULT($result_all);
1768 // Returns HTML code with an option list of all categories
1769 function generateCategoryOptionsList ($mode) {
1770 // Prepare WHERE statement
1771 $whereStatement = " WHERE `visible`='Y'";
1772 if (isAdmin()) $whereStatement = '';
1774 // Initialize array...
1778 'userids' => array()
1782 $result = SQL_QUERY("SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort` ASC",
1783 __FUNCTION__, __LINE__);
1785 // Do we have entries?
1786 if (SQL_NUMROWS($result) > 0) {
1787 // ... and begin loading stuff
1788 while ($content = SQL_FETCHARRAY($result)) {
1789 // Transfer some data
1790 $CATS['id'][] = $content['id'];
1791 $CATS['name'][] = $content['cat'];
1793 // Check which users are in this category
1794 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1795 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1801 while ($data = SQL_FETCHARRAY($result_userids)) {
1803 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1807 SQL_FREERESULT($result_userids);
1810 $CATS['userids'][] = $userid_cnt;
1814 SQL_FREERESULT($result);
1818 foreach ($CATS['id'] as $key => $value) {
1819 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1820 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1823 // No cateogries are defined yet
1824 $OUT = '<option class="member_failed">{--MEMBER_NO_CATS--}</option>';
1831 // Add bonus mail to queue
1832 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1833 // Is admin or bonus extension there?
1837 } elseif (!isExtensionActive('bonus')) {
1842 // Calculcate target sent
1843 $target = countSelection(explode(';', $receiverList));
1845 // Receiver is zero?
1846 if ($receiver == '0') {
1848 $receiver = $target;
1851 // HTML extension active?
1852 if (isExtensionActive('html_mail')) {
1853 // No HTML by default
1857 if ($mode == 'html') $HTML = 'Y';
1860 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1861 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1862 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1872 bigintval($receiver),
1874 ), __FUNCTION__, __LINE__);
1877 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1878 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1879 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1889 bigintval($receiver),
1890 ), __FUNCTION__, __LINE__);
1894 // Generate a receiver list for given category and maximum receivers
1895 function generateReceiverList ($cat, $receiver, $mode = '') {
1903 $cat = bigintval($cat);
1904 $receiver = bigintval($receiver);
1906 // Is the receiver zero and mode set?
1907 if (($receiver == '0') && (!empty($mode))) {
1908 // Auto-fix receiver maximum
1909 $receiver = getTotalReceivers($mode);
1915 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
1916 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
1919 // Exclude users in holiday?
1920 if (getExtensionVersion('holiday') >= '0.1.3') {
1921 // Add something for the holiday extension
1922 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1925 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1926 // Only include HTML receivers
1927 $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",
1930 ), __FUNCTION__, __LINE__);
1933 $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",
1936 ), __FUNCTION__, __LINE__);
1940 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1942 while ($content = SQL_FETCHARRAY($result)) {
1943 // Add receiver when not empty
1944 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1948 SQL_FREERESULT($result);
1950 // Remove trailing semicolon
1951 $receiverList = substr($receiverList, 0, -1);
1955 return $receiverList;
1958 // Get timestamp for given stats type and data
1959 function getTimestampFromUserStats ($statsType, $statsData, $userid = '0') {
1960 // Default timestamp is zero
1961 $data['inserted'] = '0';
1964 if ((isMemberIdSet()) && ($userid == '0')) {
1965 $userid = getMemberId();
1968 // Is the extension installed and updated?
1969 if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
1971 return $data['inserted'];
1974 // Try to find the entry
1975 $result = SQL_QUERY_ESC("SELECT
1976 UNIX_TIMESTAMP(`inserted`) AS inserted
1978 `{?_MYSQL_PREFIX?}_user_stats_data`
1981 `stats_type`='%s' AND
1988 ), __FUNCTION__, __LINE__);
1990 // Is the entry there?
1991 if (SQL_NUMROWS($result) == 1) {
1993 $data = SQL_FETCHARRAY($result);
1997 SQL_FREERESULT($result);
2000 return $data['inserted'];
2003 // Inserts user stats
2004 function insertUserStatsRecord ($userid, $statsType, $statsData) {
2005 // Is the extension installed and updated?
2006 if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
2012 if ((!getTimestampFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
2014 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
2015 array(bigintval($userid), $statsType, $statsData), __FUNCTION__, __LINE__);
2016 } elseif (is_array($statsData)) {
2018 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$statsType},data={".gettype($statsData).": Invalid statistics data type!");
2022 // "Getter" for array for user refs and points in given level
2023 function getUserReferalPoints ($userid, $level) {
2024 //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
2025 // Default is no refs and no nickname
2029 // Do we have nickname extension installed?
2030 if (isExtensionActive('nickname')) {
2031 $add = ', ud.nickname';
2034 // Get refs from database
2035 $result = SQL_QUERY_ESC("SELECT
2036 ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2038 `{?_MYSQL_PREFIX?}_user_refs` AS ur
2040 `{?_MYSQL_PREFIX?}_user_points` AS up
2042 ur.refid=up.userid AND ur.level=0
2044 `{?_MYSQL_PREFIX?}_user_data` AS ud
2048 ur.userid=%s AND ur.level=%s
2054 ), __FUNCTION__, __LINE__);
2056 // Are there some entries?
2057 if (SQL_NUMROWS($result) > 0) {
2058 // Fetch all entries
2059 while ($row = SQL_FETCHARRAY($result)) {
2060 // Get total points of this user
2061 $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
2063 // Get unconfirmed mails
2064 $row['unconfirmed'] = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
2066 // Init clickrate with zero
2067 $row['clickrate'] = '0';
2069 // Is at least one mail received?
2070 if ($row['emails_received'] > 0) {
2071 // Calculate clickrate
2072 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2075 // Activity is 'active' by default because if autopurge is not installed
2076 $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2078 // Is autopurge installed and the user inactive?
2079 if ((isExtensionActive('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online'])) {
2081 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2084 // Remove some entries
2085 unset($row['mails_confirmed']);
2086 unset($row['emails_received']);
2087 unset($row['last_online']);
2090 $refs[$row['id']] = $row;
2095 SQL_FREERESULT($result);
2098 //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
2102 // Recuce the amount of received emails for the receipients for given email
2103 function reduceRecipientReceivedMails ($column, $id, $count) {
2104 // Search for mail in database
2105 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2106 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2108 // Are there entries?
2109 if (SQL_NUMROWS($result) > 0) {
2110 // Now load all userids for one big query!
2112 while ($data = SQL_FETCHARRAY($result)) {
2113 // By default we want to reduce and have no mails found
2116 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
2117 // @TODO Rewrite this to a filter
2118 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
2120 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
2121 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
2123 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
2126 // Reduce this users total received emails?
2127 if ($num === 0) $userids[$data['userid']] = $data['userid'];
2130 if (count($userids) > 0) {
2131 // Now update all user accounts
2132 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2133 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
2136 loadTemplate('admin_settings_saved', false, getMaskedMessage('ADMIN_MAIL_NOTHING_DELETED', $id));
2141 SQL_FREERESULT($result);
2144 // Creates a new task
2145 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
2146 // Insert the task data into the database
2147 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())",
2154 ), __FUNCTION__, __LINE__, true, $strip);
2157 // Updates last module / online time
2158 // @TODO Fix inconsistency between last_module and getWhat()
2159 function updateLastActivity($userid) {
2160 // Run the update query
2161 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
2166 ), __FUNCTION__, __LINE__);