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 - 2008 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')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
45 // "Getter" for module title
46 function getModuleTitle ($mod) {
51 // Is the script installed?
53 // Check if cache is valid
54 if ((GET_EXT_VERSION('cache') >= '0.1.2') && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($mod, $GLOBALS['cache_array']['modules']['module']))) {
56 $name = $GLOBALS['cache_array']['modules']['title'][$mod];
59 incrementConfigEntry('cache_hits');
60 } elseif (!EXT_IS_ACTIVE('cache')) {
62 $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE `module`='%s' LIMIT 1",
63 array($mod), __FUNCTION__, __LINE__);
64 list($name) = SQL_FETCHROW($result);
65 SQL_FREERESULT($result);
72 // Still no luck or empty title?
75 $name = sprintf("%s (%s)", getMessage('LANG_UNKNOWN_MODULE'), $mod);
76 if (SQL_NUMROWS($result) == 0) {
77 // Add module to database
78 $dummy = checkModulePermissions($mod);
86 // "Getter" for module description
87 function getModuleDescription ($mode, $wht, $column = 'what') {
91 if (getConfig('index_home') != '') $wht = getConfig('index_home');
94 // Default is not found
95 $ret = "??? (".$wht.')';
98 $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE %s='%s' LIMIT 1",
99 array($mode, $column, $wht), __FUNCTION__, __LINE__);
101 // Is there an entry?
102 if (SQL_NUMROWS($result) == 1) {
104 list($ret) = SQL_FETCHROW($result);
108 SQL_FREERESULT($result);
112 // Check validity of a given module name (no file extension)
113 function checkModulePermissions ($mod) {
114 // Filter module name (names with low chars and underlines are fine!)
115 $mod = preg_replace("/[^a-z_]/", '', $mod);
117 // Check for prefix is a extension...
118 $modSplit = explode("_", $mod);
119 $extension = ''; $mod_chk = $mod;
120 //* DEBUG: */ echo __LINE__."*".count($modSplit)."*/".$mod."*<br />";
121 if (count($modSplit) == 2) {
122 // Okay, there is a seperator (_) in the name so is the first part a module?
123 //* DEBUG: */ echo __LINE__."*".$modSplit[0]."*<br />";
124 if (EXT_IS_ACTIVE($modSplit[0])) {
125 // The prefix is an extension's name, so let's set it
126 $extension = $modSplit[0]; $mod = $modSplit[1];
130 // Major error in module registry is the default
133 // Check if script is installed if not return a 'done' to prevent some errors
134 if ((!isInstalled()) || (isInstalling()) || (!isAdminRegistered())) {
135 // Not installed or no admin registered or in installation phase
146 // Check if cache is latest version
147 if (GET_EXT_VERSION('cache') >= '0.1.2') {
148 // Is the cache there?
149 if (!isset($GLOBALS['cache_array']['modules'])) {
150 // This should normally not happen...
151 debug_report_bug("Cache 'modules' is gone.");
154 // Is the module cached?
155 if (isset($GLOBALS['cache_array']['modules']['locked'][$mod_chk])) {
157 $locked = $GLOBALS['cache_array']['modules']['locked'][$mod_chk];
158 $hidden = $GLOBALS['cache_array']['modules']['hidden'][$mod_chk];
159 $admin = $GLOBALS['cache_array']['modules']['admin_only'][$mod_chk];
160 $mem = $GLOBALS['cache_array']['modules']['mem_only'][$mod_chk];
163 incrementConfigEntry('cache_hits');
166 // No, then we have to update it!
169 } elseif (!EXT_IS_ACTIVE('cache')) {
170 // Check for module in database
171 $result = SQL_QUERY_ESC("SELECT locked, hidden, admin_only, mem_only FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE `module`='%s' LIMIT 1",
172 array($mod_chk), __FUNCTION__, __LINE__);
173 if (SQL_NUMROWS($result) == 1) {
175 list($locked, $hidden, $admin, $mem) = SQL_FETCHROW($result);
176 SQL_FREERESULT($result);
181 // Is the module found?
182 if ($found === true) {
183 // Check returned values against current access permissions
185 // Admin access ----- Guest access ----- --- Guest or member? ---
186 if ((IS_ADMIN()) || (($locked == 'N') && ($admin == 'N') && (($mem == 'N') || (IS_MEMBER())))) {
187 // If you are admin you are welcome for everything!
189 } elseif ($locked == 'Y') {
192 } elseif (($mem == 'Y') && (!IS_MEMBER())) {
193 // You have to login first!
195 } elseif (($admin == 'Y') && (!IS_ADMIN())) {
196 // Only the Admin is allowed to enter this module!
199 // @TODO Nothing helped???
200 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
209 // Still no luck or not found?
210 if (($ret == "cache_miss") || (!$found)) {
211 // ----- Legacy module ----- ---- Module in base folder ---- --- Module with extension's name ---
212 if ((isFileReadable(sprintf("%sinc/modules/%s.php", constant('PATH'), $mod))) || (isFileReadable(sprintf("%s%s.php", constant('PATH'), $mod))) || (isFileReadable(sprintf("%s%s/%s.php", constant('PATH'), $extension, $mod)))) {
213 // Data is missing so we add it
214 if (GET_EXT_VERSION('sql_patches') >= '0.3.6') {
215 // Since 0.3.6 we have a has_menu column, this took me a half hour
216 // to find a loop here... *sigh*
217 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_mod_reg`
218 (module, locked, hidden, mem_only, admin_only, has_menu) VALUES
219 ('%s','Y','N','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
221 // Wrong/missing sql_patches!
222 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_mod_reg`
223 (module, locked, hidden, mem_only, admin_only) VALUES
224 ('%s','Y','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
227 // Everthing is fine?
228 if (SQL_AFFECTEDROWS() < 1) {
229 // Something bad happend!
233 // Destroy cache here
234 rebuildCacheFiles("modreg", "modreg");
237 $ret = checkModulePermissions($mod_chk);
239 // Module not found we don't add it to the database
243 // Problem with module detected
244 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s",
258 // Add menu description pending on given file name (without path!)
259 function ADD_DESCR ($ACC_LVL, $FQFN, $return = false, $output = true) {
260 // Use only filename of the FQFN...
261 $file = basename($FQFN);
268 // First we have to do some analysis...
269 if (substr($file, 0, 7) == "action-") {
270 // This is an action file!
272 $search = substr($file, 7);
281 $modCheck = $GLOBALS['module'];
284 $AND = " AND (`what`='' OR `what` IS NULL)";
285 } elseif (substr($file, 0, 5) == "what-") {
286 // This is an admin what file!
288 $search = substr($file, 5);
297 $modCheck = $GLOBALS['module'];
299 $AND = " AND `visible`='Y' AND `locked`='N'";
303 $dummy = substr($search, 0, -4);
304 $AND .= " AND `action`='".getModeAction($ACC_LVL, $dummy)."'";
305 } elseif (($ACC_LVL == 'sponsor') || ($ACC_LVL == "engine")) {
306 // Sponsor / engine menu
309 $modCheck = $GLOBALS['module'];
315 $modCheck = $GLOBALS['module'];
319 // Begin the navigation line
320 if ((!isset($GLOBALS['nav_depth'])) && (!$return)) {
321 $GLOBALS['nav_depth'] = 0;
322 $prefix = "<div class=\"you_are_here\">{--YOU_ARE_HERE--} <strong><a class=\"you_are_here\" href=\"{!URL!}/modules.php?module=".$GLOBALS['module'].$LINK_ADD."\">Home</a></strong>";
324 if (!$return) $GLOBALS['nav_depth']++;
328 $prefix .= " -> ";
330 // We need to remove .php and the end
331 if (substr($search, -4, 4) == '.php') {
333 $search = substr($search, 0, -4);
336 // Get the title from menu
337 $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE %s='%s' ".$AND." LIMIT 1",
338 array($ACC_LVL, $type, $search), __FUNCTION__, __LINE__);
341 if (SQL_NUMROWS($result) == 1) {
343 list($ret) = SQL_FETCHROW($result);
345 // Shall we return it?
346 if ($return === true) {
349 } elseif (((GET_EXT_VERSION('sql_patches') >= '0.2.3') && (getConfig('youre_here') == 'Y')) || ((IS_ADMIN()) && ($modCheck == 'admin'))) {
351 $OUT = $prefix."<strong><a class=\"you_are_here\" href=\"{!URL!}/modules.php?module=".$modCheck.'&'.$type.'='.$search.$LINK_ADD."\">".$ret."</a></strong>\n";
353 // Can we close the you-are-here navigation?
354 //* DEBUG: */ echo __LINE__."*".$type.'/'.$GLOBALS['what']."*<br />\n";
355 if (($type == 'what') || (($type == 'action') && ((!isset($GLOBALS['what'])) || ($GLOBALS['what'] == "overview")))) {
356 //* DEBUG: */ echo __LINE__.'+'.$type."+<br />\n";
357 // Add closing div and br-tag
358 $OUT .= "</div><br />\n";
359 $GLOBALS['nav_depth'] = '0';
361 // Run the filter chain
362 $ret = runFilterChain('post_youhere_line', array('access_level' => $ACC_LVL, 'type' => $type, 'content' => ""));
363 $OUT .= $ret['content'];
369 SQL_FREERESULT($result);
371 // Return or output HTML code?
373 // Output HTML code here
382 function ADD_MENU ($mode, $act, $wht) {
383 // Init some variables
389 // is the menu action valid?
390 if (!isMenuActionValid($mode, $act, $wht, true)) {
391 return getCode('MENU_NOT_VALID');
394 // Non-admin shall not see all menus
396 $AND = " AND `visible`='Y' AND `locked`='N'";
399 // Load SQL data and add the menu to the output stream...
400 $result_main = SQL_QUERY_ESC("SELECT title, action FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$AND." ORDER BY `sort`",
401 array($mode), __FUNCTION__, __LINE__);
402 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$main_action.'/'.$sub_what.':'.$GLOBALS['what']."*<br />\n";
403 if (SQL_NUMROWS($result_main) > 0) {
404 OUTPUT_HTML("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"".$mode."_menu\">");
405 // There are menus available, so we simply display them... :)
406 while ($content = SQL_FETCHARRAY($result_main)) {
407 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$sub_what.':'.$GLOBALS['what']."*<br />\n";
409 $GLOBALS['block_mode'] = false;
410 $act = $content['action'];
412 // Load menu header template
413 LOAD_TEMPLATE($mode."_menu_title", false, $content);
416 $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`",
417 array($mode, $content['action']), __FUNCTION__, __LINE__);
419 // Get number of rows
420 $ctl = SQL_NUMROWS($result_sub);
422 // Do we have some entries?
427 // Load all sub menus
428 while ($content2 = SQL_FETCHARRAY($result_sub)) {
429 // Merge both arrays in one
430 $content = merge_array($content, $content2);
435 // Full file name for checking menu
436 //* DEBUG: */ echo __LINE__.":!!!!".$content['sub_what']."!!!<br />\n";
437 $INC = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
438 if (isIncludeReadable($INC)) {
439 if ((!empty($wht)) && (($wht == $content['sub_what']))) {
444 $OUT .= "<a name=\"menu\" class=\"menu_blur\" href=\"{!URL!}/modules.php?module=".$GLOBALS['module']."&what=".$content['sub_what']."\" target=\"_self\">";
450 $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
452 if (isIncludeReadable($INC)) {
458 if ((!empty($wht)) && (($wht == $content['sub_what']))) {
462 // Remember 'what' for next round and count it up
463 $wht = $content['sub_what']; $cnt++;
468 'what' => $content['sub_what']
471 // Add regular menu row or bottom row?
473 LOAD_TEMPLATE($mode."_menu_row", false, $content);
475 LOAD_TEMPLATE($mode."_menu_bottom", false, $content);
479 // This is a menu block... ;-)
480 $GLOBALS['block_mode'] = true;
481 $INC_BLOCK = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
482 if (isFileReadable($INC_BLOCK)) {
484 if ((!EXT_IS_ACTIVE($content['action'])) || ($content['action'] == 'online')) OUTPUT_HTML("<tr>
486 <td class=\"".$mode."_menu_whats\">");
487 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.$GLOBALS['what']."*<br />\n";
488 loadInclude($INC_BLOCK);
489 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.$GLOBALS['what']."*<br />\n";
490 if ((!EXT_IS_ACTIVE($content['action'])) || ($content['action'] == 'online')) OUTPUT_HTML(" </td>
493 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.$GLOBALS['what']."*<br />\n";
496 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.$GLOBALS['what']."*<br />\n";
497 if (SQL_NUMROWS($result_main) > $main_cnt) {
498 OUTPUT_HTML("<tr><td class=\"".$mode."_menu_seperator\"></td></tr>");
503 SQL_FREERESULT($result_main);
506 //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.$GLOBALS['what']."*<br />\n";
507 OUTPUT_HTML("</table>");
511 // Checks wether the current user is a member
512 function IS_MEMBER () {
513 // @TODO Why is this global??? #100
516 if (!is_array($GLOBALS['last'])) $GLOBALS['last'] = array();
519 // is the cache entry there?
520 if (isset($GLOBALS['cache_array']['is_member'])) {
522 return $GLOBALS['cache_array']['is_member'];
525 // Fix "deleted" cookies first
526 fixDeletedCookies(array('userid', 'u_hash'));
529 if ((isUserIdSet()) && (isSessionVariableSet('u_hash'))) {
530 // Cookies are set with values, but are they valid?
531 $result = SQL_QUERY_ESC("SELECT password, status, last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
532 array(getUserId()), __FUNCTION__, __LINE__);
533 if (SQL_NUMROWS($result) == 1) {
534 // Load data from cookies
535 list($password, $status, $mod, $onl) = SQL_FETCHROW($result);
537 // Validate password by created the difference of it and the secret key
538 $valPass = generatePassString($password);
540 // Transfer last module and online time
541 if ((!empty($mod)) && (empty($GLOBALS['last']['module']))) {
542 $GLOBALS['last']['module'] = $mod;
543 $GLOBALS['last']['online'] = $onl;
546 // So did we now have valid data and an unlocked user?
547 //* DEBUG: */ echo $valPass."<br />".getSession('u_hash')."<br />";
548 if (($status == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
549 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
552 // Maybe got locked etc.
553 //* DEBUG: */ echo __LINE__."!!!<br />";
554 destroyUserSession();
557 // Cookie data is invalid!
558 //* DEBUG: */ echo __LINE__."***<br />";
559 destroyUserSession();
563 SQL_FREERESULT($result);
565 // Cookie data is invalid!
566 //* DEBUG: */ echo __LINE__."///<br />";
567 destroyUserSession();
571 $GLOBALS['cache_array']['is_member'] = $ret;
577 // This patched function will reduce many SELECT queries for the specified or current admin login
578 function IS_ADMIN ($admin = '') {
580 $ret = false; $passCookie = ''; $valPass = '';
581 //* DEBUG: */ echo __LINE__."ADMIN:".$admin."<br />";
583 // If admin login is not given take current from cookies...
584 if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
585 // Get admin login and password from session/cookies
586 $admin = getSession('admin_login');
587 $passCookie = getSession('admin_md5');
589 //* DEBUG: */ echo __LINE__."ADMIN:".$admin.'/'.$passCookie."<br />";
591 // Search in array for entry
592 if (isset($GLOBALS['cache_array']['admin_hash'])) {
594 $valPass = $GLOBALS['cache_array']['admin_hash'];
595 } elseif ((!empty($passCookie)) && (isset($GLOBALS['cache_array']['admins']['password'][$admin])) && (!empty($admin))) {
596 // Login data is valid or not?
597 $valPass = generatePassString($GLOBALS['cache_array']['admins']['password'][$admin]);
600 $GLOBALS['cache_array']['admin_hash'] = $valPass;
603 incrementConfigEntry('cache_hits');
604 } elseif ((!empty($admin)) && ((!EXT_IS_ACTIVE('cache'))) || (!isset($GLOBALS['cache_array']['admins']['password'][$admin]))) {
606 $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY password FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
607 array($admin), __FUNCTION__, __LINE__);
611 if (SQL_NUMROWS($result) == 1) {
612 // Admin login was found so let's load password from DB
613 list($passDB) = SQL_FETCHROW($result);
615 // Temporary cache it
616 $GLOBALS['cache_array']['admins']['password'][$admin] = $passDB;
618 // Generate password hash
619 $valPass = generatePassString($passDB);
623 SQL_FREERESULT($result);
626 if (!empty($valPass)) {
627 // Check if password is valid
628 //* DEBUG: */ print __FUNCTION__."*".$valPass.'/'.$passCookie."*<br />\n";
629 $ret = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == "*FAILED*") && (!EXT_IS_ACTIVE('cache'))));
632 // Return result of comparision
633 //* DEBUG: */ if (!$ret) echo __LINE__."OK!<br />";
637 // Generates a list of "max receiveable emails per day"
638 function addMaxReceiveList ($mode, $default = '', $return = false) {
644 // Guests (in the registration form) are not allowed to select 0 mails per day.
645 $result = SQL_QUERY("SELECT value, comment FROM `{!_MYSQL_PREFIX!}_max_receive` WHERE value > 0 ORDER BY value",
646 __FUNCTION__, __LINE__);
650 // Members are allowed to set to zero mails per day (we will change this soon!)
651 $result = SQL_QUERY("SELECT value, comment FROM `{!_MYSQL_PREFIX!}_max_receive` ORDER BY value",
652 __FUNCTION__, __LINE__);
656 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
660 // Some entries are found?
661 if (SQL_NUMROWS($result) > 0) {
663 while ($content = SQL_FETCHARRAY($result)) {
664 $OUT .= " <option value=\"".$content['value']."\"";
665 if (REQUEST_POST('max_mails') == $content['value']) $OUT .= ' selected="selected"';
666 $OUT .= ">".$content['value']." {--PER_DAY--}";
667 if (!empty($content['comment'])) $OUT .= " (".$content['comment'].')';
668 $OUT .= "</option>\n";
670 define('__MAX_RECEIVE_OPTIONS', $OUT);
673 $OUT = LOAD_TEMPLATE($mode . '_receive_table', true);
675 // Maybe the admin has to setup some maximum values?
676 debug_report_bug('Nothing is being done here?');
680 SQL_FREERESULT($result);
682 if ($return === true) {
683 // Return generated HTML code
686 // Output directly (default)
691 // Checks wether the given email address is used.
692 function isEmailTaken ($email) {
693 // Query the database
694 $result = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE email LIKE '{PER}%s{PER}' LIMIT 1",
695 array($email), __FUNCTION__, __LINE__);
697 // Is the email there?
698 $ret = (SQL_NUMROWS($result) == 1);
701 SQL_FREERESULT($result);
707 // Validate the given menu action
708 function isMenuActionValid ($mode, $act, $wht, $UPDATE=false) {
709 // Is the cache entry there and we shall not update?
710 if ((isset($GLOBALS['cache_array']['action_valid'][$mode][$act][$wht])) && ($UPDATE === false)) {
712 incrementConfigEntry('cache_hits');
714 // Then use this cache
715 return $GLOBALS['cache_array']['action_valid'][$mode][$act][$wht];
718 // By default nothing is valid
721 // Look in all menus or only unlocked
723 if ((!IS_ADMIN()) && ($mode != 'admin')) $add = " AND `locked`='N'";
725 //* DEBUG: */ echo __LINE__.':'.$mode.'/'.$act.'/'.$wht."*<br />\n";
726 if (($mode != 'admin') && ($UPDATE === true)) {
727 // Update guest or member menu
728 $sql = SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
729 array($mode, $act, $wht), __FUNCTION__, __LINE__, false);
730 } elseif (($wht != "overview") && (!empty($wht))) {
732 $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",
733 array($mode, $act, $wht), __FUNCTION__, __LINE__, false);
735 // Admin login overview
736 $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",
737 array($mode, $act), __FUNCTION__, __LINE__, false);
741 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
742 if ($UPDATE === true) {
743 // Check updated/affected rows
744 $ret = (SQL_AFFECTEDROWS() == 1);
747 $ret = (SQL_NUMROWS($result) == 1);
751 SQL_FREERESULT($result);
754 $GLOBALS['cache_array']['action_valid'][$mode][$act][$wht] = $ret;
761 function sendModeMails ($mod, $modes) {
765 $result_main = SQL_QUERY_ESC("SELECT password FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s AND `status`='CONFIRMED' LIMIT 1",
766 array(getUserId()), __FUNCTION__, __LINE__);
767 if (SQL_NUMROWS($result_main) == 1) {
768 // Load hash from database
769 list($hashDB) = SQL_FETCHROW($result_main);
771 // Extract salt from cookie
772 $salt = substr(getSession('u_hash'), 0, -40);
774 // Now let's compare passwords
775 $hash = generatePassString($hashDB);
776 if (($hash == getSession('u_hash')) || (REQUEST_POST('pass1') == REQUEST_POST('pass2'))) {
778 $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",
779 array(getUserId(), $hashDB), __FUNCTION__, __LINE__);
780 if (SQL_NUMROWS($result) == 1) {
782 $DATA = SQL_FETCHROW($result);
785 SQL_FREERESULT($result);
788 $DATA[0] = translateGender($DATA[0]);
790 // Clear/init the content variable
797 foreach ($modes as $mode) {
800 case 'normal': break; // Do not add any special lines
802 case 'email': // Email was changed!
803 $content = getMessage('MEMBER_CHANGED_EMAIL').": ".REQUEST_POST('old_addy')."\n";
806 case 'pass': // Password was changed
807 $content = getMessage('MEMBER_CHANGED_PASS')."\n";
811 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
812 $content = getMessage('MEMBER_UNKNOWN_MODE').": ".$mode."\n\n";
817 if (EXT_IS_ACTIVE('country')) {
818 // Replace code with description
819 $DATA[4] = COUNTRY_GENERATE_INFO(REQUEST_POST('country_code'));
822 // Merge content with data from POST
823 $content = merge_array($content, REQUEST_POST_ARRAY());
826 $msg = LOAD_EMAIL_TEMPLATE('member_mydata_notify', $content, getUserId());
828 if (getConfig('admin_notify') == 'Y') {
829 // The admin needs to be notified about a profile change
830 $msg_admin = 'admin_mydata_notify';
831 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
839 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
841 // Output success message
842 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
845 default: // Unsupported module!
846 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
847 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
851 // Could not load profile data
852 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
855 // Passwords mismatch
856 $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
859 // Could not load profile
860 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
863 // Send email to user if required
864 if ((!empty($sub_mem)) && (!empty($msg))) {
866 sendEmail($DATA[7], $sub_mem, $msg);
869 // Send only if no other error has occured
870 if (empty($content)) {
871 if ((!empty($sub_adm)) && (!empty($msg_admin))) {
873 sendAdminNotification($sub_adm, $msg_admin, $content, getUserId());
874 } elseif (getConfig('admin_notify') == 'Y') {
875 // Cannot send mails to admin!
876 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
879 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
884 LOAD_TEMPLATE('admin_settings_saved', false, $content);
887 // Update module counter
888 function countModuleHit($mod) {
890 // Do count all other modules but not accesses on CSS file css.php!
891 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET clicks=clicks+1 WHERE `module`='%s' LIMIT 1",
892 array($mod), __FUNCTION__, __LINE__);
896 // Get action value from mode (admin/guest/member) and what-value
897 function getModeAction ($mode, &$wht) {
901 //* DEBUG: */ echo __LINE__.'='.$mode.'/'.$wht.'/'.$GLOBALS['action']."=<br />";
902 if ((empty($wht)) && ($mode != 'admin')) {
904 if (getConfig('index_home') != '') $wht = getConfig('index_home');
907 if ($mode == 'admin') {
908 // Action value for admin area
909 if (REQUEST_ISSET_GET('action')) {
911 return REQUEST_GET('action');
912 } elseif (!empty($GLOBALS['action'])) {
913 // Get it directly from URL
914 return $GLOBALS['action'];
915 } elseif (($wht == "overview") || (empty($GLOBALS['what']))) {
916 // Default value for admin area
919 } elseif (!empty($GLOBALS['action'])) {
920 // Get it directly from URL
921 return $GLOBALS['action'];
923 //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret."<br />\n";
925 // Does the module have a menu?
926 if (MODULE_HAS_MENU($mode)) {
927 // Rewriting modules to menu
929 case 'index': $mode = 'guest'; break;
930 case "login": $mode = 'member'; break;
933 // Guest and member menu is "main" as the default
934 if (empty($ret)) $ret = "main";
936 // Load from database
937 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `what`='%s' LIMIT 1",
938 array($mode, $wht), __FUNCTION__, __LINE__);
939 if (SQL_NUMROWS($result) == 1) {
940 // Load action value and pray that this one is the right you want... ;-)
941 list($ret) = SQL_FETCHROW($result);
945 SQL_FREERESULT($result);
946 } elseif ((GET_EXT_VERSION('sql_patches') == '') && ($mode != 'admin')) {
947 // No sql_patches installed, but maybe we need to register an admin?
948 if (isAdminRegistered()) {
950 // @TODO Why does this lead into an endless loop but we still need it???
951 // @TODO Commented out redirectToUrl('admin.php');
955 // Return action value
959 // Get category name back
960 function getCategory ($cid) {
961 // Default is not found
962 $ret = getMessage('_CATEGORY_404');
964 // Is the category id set?
967 $ret = getMessage('_CATEGORY_NONE');
968 } elseif ($cid > 0) {
969 // Lookup the category in database
970 $result = SQL_QUERY_ESC("SELECT cat FROM `{!_MYSQL_PREFIX!}_cats` WHERE `id`=%s LIMIT 1",
971 array(bigintval($cid)), __FUNCTION__, __LINE__);
972 if (SQL_NUMROWS($result) == 1) {
973 // Category found... :-)
974 list($ret) = SQL_FETCHROW($result);
978 SQL_FREERESULT($result);
985 // Get a string of "mail title" and price back
986 function getPaymentTitlePrice ($pid, $full=false) {
987 // Default is not found
988 $ret = getMessage('_PAYMENT_404');
991 $result = SQL_QUERY_ESC("SELECT mail_title, price FROM `{!_MYSQL_PREFIX!}_payments` WHERE `id`=%s LIMIT 1",
992 array(bigintval($pid)), __FUNCTION__, __LINE__);
993 if (SQL_NUMROWS($result) == 1) {
994 // Payment type found... :-)
997 list($ret) = SQL_FETCHROW($result);
999 // Return title and price
1000 list($t, $p) = SQL_FETCHROW($result);
1001 $ret = $t.' / '.translateComma($p).' {!POINTS!}';
1006 SQL_FREERESULT($result);
1012 // Get (basicly) the price of given payment id
1013 function getPaymentPoints ($pid, $lookFor = 'price') {
1017 // Search for it in database
1018 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_payments` WHERE `id`=%s LIMIT 1",
1019 array($lookFor, $pid), __FUNCTION__, __LINE__);
1021 // Is the entry there?
1022 if (SQL_NUMROWS($result) == 1) {
1023 // Payment type found... :-)
1024 list($ret) = SQL_FETCHROW($result);
1028 SQL_FREERESULT($result);
1034 // Remove a receiver's ID from $receivers and add a link for him to confirm
1035 function removeReceiver (&$receivers, $key, $uid, $pool_id, $stats_id='', $bonus=false) {
1036 // Default is not removed
1039 // Is the userid valid?
1041 // Remove entry from array
1042 unset($receivers[$key]);
1044 // Is there already a line for this user available?
1045 if ($stats_id > 0) {
1046 // Only when we got a real stats ID continue searching for the entry
1047 $type = 'NORMAL'; $rowName = 'stats_id';
1048 if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1050 // Try to look the entry up
1051 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1052 array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
1054 // Was it *not* found?
1055 if (SQL_NUMROWS($result) == 0) {
1057 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_links` (%s, userid, link_type) VALUES ('%s','%s','%s')",
1058 array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
1066 SQL_FREERESULT($result);
1070 // Return status for sending routine
1074 // Calculate sum (default) or count records of given criteria
1075 function GET_TOTAL_DATA ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1077 //* DEBUG: */ echo $search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />\n';
1078 if ((empty($search)) && ($search != '0')) {
1079 // Count or sum whole table?
1080 if ($countRows === true) {
1081 // Count whole table
1082 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s`".$add,
1083 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1086 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{!_MYSQL_PREFIX!}_%s`".$add,
1087 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1089 } elseif (($countRows === true) || ($lookFor == 'userid')) {
1091 //* DEBUG: */ echo "COUNT!<br />\n";
1092 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
1093 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1096 //* DEBUG: */ echo "SUM!<br />\n";
1097 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
1098 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1102 list($ret) = SQL_FETCHROW($result);
1105 SQL_FREERESULT($result);
1108 if ((empty($ret)) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1111 } elseif (''.$ret.'' == '') {
1119 // Getter fro ref level percents
1120 function getReferalLevelPercents ($level) {
1124 // Do we have cache?
1125 if ((isset($GLOBALS['cache_array']['ref_depths']['level'])) && (EXT_IS_ACTIVE('cache'))) {
1126 // First look for level
1127 $key = array_search($level, $GLOBALS['cache_array']['ref_depths']['level']);
1128 if ($key !== false) {
1130 $per = $GLOBALS['cache_array']['ref_depths']['percents'][$key];
1133 incrementConfigEntry('cache_hits');
1135 } elseif (!EXT_IS_ACTIVE('cache')) {
1137 $result_lvl = SQL_QUERY_ESC("SELECT percents FROM `{!_MYSQL_PREFIX!}_refdepths` WHERE level='%s' LIMIT 1",
1138 array(bigintval($level)), __FUNCTION__, __LINE__);
1141 if (SQL_NUMROWS($result_lvl) == 1) {
1143 list($per) = SQL_FETCHROW($result_lvl);
1147 SQL_FREERESULT($result_lvl);
1156 * Dynamic referal system, can also send mails!
1158 * subject = Subject line, write in lower-case letters and underscore is allowed
1159 * uid = Referal ID wich should receive...
1160 * points = ... xxx points
1161 * send_notify = shall I send the referal an email or not?
1162 * rid = inc/modules/guest/what-confirm.php need this (DEPRECATED???)
1163 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
1164 * add_mode = Add points only to $uid or also refs? (WARNING! Changing 'ref' to 'direct'
1165 * for default value will cause no referal will get points ever!!!)
1167 function ADD_POINTS_REFSYSTEM ($subject, $uid, $points, $send_notify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
1168 //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
1171 // Convert mode to lower-case
1172 $add_mode = strtolower($add_mode);
1174 // When $uid = 0 add points to jackpot
1176 // Add points to jackpot
1177 ADD_JACKPOT($points);
1181 // Add booking record if extension is installed
1182 if (EXT_IS_ACTIVE('booking')) {
1184 ADD_BOOKING_RECORD($subject, $uid, $points, 'add');
1187 // Count up referal depth
1188 if (!isset($GLOBALS['ref_level'])) {
1189 // Initialialize referal system
1190 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal system initialized!<br />\n";
1191 $GLOBALS['ref_level'] = 0;
1193 // Increase referal level
1194 $GLOBALS['ref_level']++;
1195 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />\n";
1198 // Default is 'normal' points
1201 // Which points, locked or normal?
1202 if ($locked) $data = 'locked_points';
1204 // Check user account
1205 $result_user = SQL_QUERY_ESC("SELECT refid, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s AND `status`='CONFIRMED' LIMIT 1",
1206 array(bigintval($uid)), __FUNCTION__, __LINE__);
1208 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},numRows=".SQL_NUMROWS($result_user).",points={$points}<br />\n";
1209 if (SQL_NUMROWS($result_user) == 1) {
1210 // This is the user and his ref
1211 list($ref, $email) = SQL_FETCHROW($result_user);
1212 $GLOBALS['cache_array']['add_uid'][$ref] = $uid;
1215 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1216 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />\n";
1218 // Some percents found?
1220 // Calculate new points
1221 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />\n";
1222 $ref_points = $points * $per / 100;
1224 // Pay refback here if level > 0 and in ref-mode
1225 if ((EXT_IS_ACTIVE('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_uid'][$uid]))) {
1226 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},data={$GLOBALS['cache_array']['add_uid'][$uid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - BEFORE!<br />\n";
1227 $ref_points = ADD_REFBACK_POINTS($GLOBALS['cache_array']['add_uid'][$uid], $uid, $points, $ref_points);
1228 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},data={$GLOBALS['cache_array']['add_uid'][$uid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - AFTER!<br />\n";
1232 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_points` SET %s=%s+%s WHERE userid=%s AND ref_depth='%s' LIMIT 1",
1233 array($data, $data, $ref_points, bigintval($uid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1234 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},uid={$uid},depth={$GLOBALS['ref_level']},mode={$add_mode} - UPDATE! (".SQL_AFFECTEDROWS().")<br />\n";
1236 // No entry updated?
1237 if (SQL_AFFECTEDROWS() < 1) {
1238 // First ref in this level! :-)
1239 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_points` (userid,ref_depth,%s) VALUES (%s,'%s',%s)",
1240 array($data, bigintval($uid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1241 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},uid={$uid},depth={$GLOBALS['ref_level']},mode={$add_mode} - INSERTED! (".SQL_AFFECTEDROWS().")<br />\n";
1244 // Update mediadata as well
1245 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
1247 MEDIA_UPDATE_ENTRY(array('total_points'), 'add', $ref_points);
1250 // Points updated, maybe I shall send him an email?
1251 if (($send_notify) && ($ref > 0) && (!$locked)) {
1255 'level' => bigintval($GLOBALS['ref_level']),
1256 'points' => $ref_points,
1257 'refid' => bigintval($ref)
1260 // Load email template
1261 $msg = LOAD_EMAIL_TEMPLATE('confirm-referal', $content, bigintval($uid));
1263 sendEmail($email, THANX_REFERRAL_ONE, $msg);
1264 } elseif (($send_notify) && ($ref == 0) && (!$locked) && ($add_mode == 'direct') && (!defined('__POINTS_VALUE'))) {
1265 // Direct payment shall be notified about
1266 define('__POINTS_VALUE', $ref_points);
1270 'text' => getMessage('REASON_DIRECT_PAYMENT'),
1271 'points' => translateComma($ref_points)
1275 $msg = LOAD_EMAIL_TEMPLATE('add-points', $content, $uid);
1278 sendEmail($email, getMessage('SUBJECT_DIRECT_PAYMENT'), $msg);
1279 if (!REQUEST_ISSET_GET(('mid'))) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1282 // Maybe there's another ref?
1283 if (($ref > 0) && ($points > 0) && ($ref != $uid) && ($add_mode == 'ref')) {
1284 // Then let's credit him here...
1285 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref},points={$points} - ADVANCE!<br />\n";
1286 ADD_POINTS_REFSYSTEM(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), $ref, $points, $send_notify, $ref, $locked);
1292 SQL_FREERESULT($result_user);
1293 //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
1296 // Wrapper function for ADD_POINTS_REFSYSTEM()
1297 function ADD_POINTS_REFSYSTEM_DIRECT ($subject, $uid, $points) {
1298 return ADD_POINTS_REFSYSTEM($subject, $uid, $points, false, 0, false, 'direct');
1301 // Updates the referal counter
1302 function updateReferalCounter ($uid) {
1303 // Make it sure referal level zero (member him-/herself) is at least selected
1304 if (empty($GLOBALS['cache_array']['ref_level'][$uid])) $GLOBALS['cache_array']['ref_level'][$uid] = 1;
1305 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['ref_level'][$uid]}<br />\n";
1308 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_refsystem` SET counter=counter+1 WHERE userid=%s AND level='%s' LIMIT 1",
1309 array(bigintval($uid), $GLOBALS['cache_array']['ref_level'][$uid]), __FUNCTION__, __LINE__);
1311 // When no entry was updated then we have to create it here
1312 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS()."<br />\n";
1313 if (SQL_AFFECTEDROWS() < 1) {
1315 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_refsystem` (userid, level, counter) VALUES (%s,%s,1)",
1316 array(bigintval($uid), $GLOBALS['cache_array']['ref_level'][$uid]), __FUNCTION__, __LINE__);
1317 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid}<br />\n";
1320 // Check for his referal
1321 $result = SQL_QUERY_ESC("SELECT refid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
1322 array(bigintval($uid)), __FUNCTION__, __LINE__);
1325 list($ref) = SQL_FETCHROW($result);
1328 SQL_FREERESULT($result);
1329 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref}<br />\n";
1331 // When he has a referal...
1332 if (($ref > 0) && ($ref != $uid)) {
1333 // Move to next referal level and count his counter one up!
1334 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />\n";
1335 $GLOBALS['cache_array']['ref_level'][$uid]++; updateReferalCounter($ref);
1336 } elseif ((($ref == $uid) || ($ref == 0)) && (GET_EXT_VERSION('cache') >= '0.1.2')) {
1337 // Remove cache here
1338 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />\n";
1339 rebuildCacheFiles('refsystem', 'refsystem');
1343 $GLOBALS['cache_array']['ref_level'][$uid]--;
1345 // Handle refback here if extension is installed
1346 if (EXT_IS_ACTIVE('refback')) {
1347 updateRefbackTable($uid);
1351 // Sends out mail to all administrators. This function is no longer obsolete
1352 // because we need it when there is no ext-admins installed
1353 function SEND_ADMIN_EMAILS ($subj, $msg) {
1354 // Load all admin email addresses
1355 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1356 while ($content = SQL_FETCHARRAY($result)) {
1357 // Send the email out
1358 sendEmail($content['email'], $subj, $msg);
1362 SQL_FREERESULT($result);
1364 // Really simple... ;-)
1367 // Get ID number from administrator's login name
1368 function GET_ADMIN_ID ($login) {
1369 // By default no admin is found
1373 if (isset($GLOBALS['cache_array']['admins']['aid'][$login])) {
1374 // Use it if found to save SQL queries
1375 $ret = $GLOBALS['cache_array']['admins']['aid'][$login];
1377 // Update cache hits
1378 incrementConfigEntry('cache_hits');
1379 } elseif (!EXT_IS_ACTIVE('cache')) {
1380 // Load from database
1381 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1382 array($login), __FUNCTION__, __LINE__);
1383 if (SQL_NUMROWS($result) == 1) {
1384 list($ret) = SQL_FETCHROW($result);
1388 SQL_FREERESULT($result);
1393 // "Getter" for current admin id
1394 function getCurrentAdminId () {
1395 // Get the admin login from session
1396 $adminLogin = getSession('admin_login');
1398 // "Solve" it into an id
1399 $adminId = GET_ADMIN_ID($adminLogin);
1401 // Secure and return it
1402 return bigintval($adminId);
1405 // Get password hash from administrator's login name
1406 function GET_ADMIN_HASH ($aid) {
1407 // By default an invalid hash is returned
1410 if (isset($GLOBALS['cache_array']['admins']['password'][$aid])) {
1412 $ret = $GLOBALS['cache_array']['admins']['password'][$aid];
1414 // Update cache hits
1415 incrementConfigEntry('cache_hits');
1416 } elseif (!EXT_IS_ACTIVE('cache')) {
1417 // Load from database
1418 $result = SQL_QUERY_ESC("SELECT password FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1419 array($aid), __FUNCTION__, __LINE__);
1420 if (SQL_NUMROWS($result) == 1) {
1422 list($ret) = SQL_FETCHROW($result);
1425 $GLOBALS['cache_array']['admins']['password'][$aid] = $ret;
1429 SQL_FREERESULT($result);
1434 // "Getter" for admin login
1435 function getAdminLogin ($aid) {
1436 // By default a non-existent login is returned (other functions react on this!)
1439 if (isset($GLOBALS['cache_array']['admins']['login'][$aid])) {
1441 $ret = $GLOBALS['cache_array']['admins']['login'][$aid];
1443 // Update cache hits
1444 incrementConfigEntry('cache_hits');
1445 } elseif (!EXT_IS_ACTIVE('cache')) {
1446 // Load from database
1447 $result = SQL_QUERY_ESC("SELECT login FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1448 array(bigintval($aid)), __FUNCTION__, __LINE__);
1449 if (SQL_NUMROWS($result) == 1) {
1451 list($ret) = SQL_FETCHROW($result);
1454 $GLOBALS['cache_array']['admins']['login'][$aid] = $ret;
1458 SQL_FREERESULT($result);
1463 // Get email address of admin id
1464 function getAdminEmail ($aid) {
1465 // By default an invalid emails is returned
1468 if (isset($GLOBALS['cache_array']['admins']['email'][$aid])) {
1470 $ret = $GLOBALS['cache_array']['admins']['email'][$aid];
1472 // Update cache hits
1473 incrementConfigEntry('cache_hits');
1474 } elseif (!EXT_IS_ACTIVE('cache')) {
1475 // Load from database
1476 $result_aid = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1477 array(bigintval($aid)), __FUNCTION__, __LINE__);
1478 if (SQL_NUMROWS($result_aid) == 1) {
1480 list($ret) = SQL_FETCHROW($result_aid);
1483 $GLOBALS['cache_array']['admins']['email'][$aid] = $ret;
1487 SQL_FREERESULT($result_aid);
1494 // Get default ACL of admin id
1495 function getAdminDefaultAcl ($aid) {
1496 // By default an invalid ACL value is returned
1499 // Is sql_patches there and was it found in cache?
1500 if (!EXT_IS_ACTIVE('sql_patches')) {
1501 // Not found, which is bad, so we need to allow all
1503 } elseif (isset($GLOBALS['cache_array']['admins']['def_acl'][$aid])) {
1505 $ret = $GLOBALS['cache_array']['admins']['def_acl'][$aid];
1507 // Update cache hits
1508 incrementConfigEntry('cache_hits');
1509 } elseif (!EXT_IS_ACTIVE('cache')) {
1510 // Load from database
1511 $result_aid = SQL_QUERY_ESC("SELECT default_acl FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1512 array(bigintval($aid)), __FUNCTION__, __LINE__);
1513 if (SQL_NUMROWS($result_aid) == 1) {
1515 list($ret) = SQL_FETCHROW($result_aid);
1518 $GLOBALS['cache_array']['admins']['def_acl'][$aid] = $ret;
1522 SQL_FREERESULT($result_aid);
1529 // Generates an option list from various parameters
1530 function generateOptionList ($table, $id, $name, $default='', $special='', $where='') {
1532 if ($table == '/ARRAY/') {
1533 // Selection from array
1534 if (is_array($id) && is_array($name) && count($id) == count($name)) {
1536 foreach ($id as $idx => $value) {
1537 $ret .= '<option value="' . $value . '"';
1538 if ($default == $value) $ret .= ' selected="selected"';
1539 $ret .= '>' . $name[$idx] . '</option>';
1543 // Data from database
1545 if (!empty($special)) $SPEC = ', ' . $special;
1546 $ORDER = $name.$SPEC;
1547 if ($table == 'country') $ORDER = $special;
1548 $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM `{!_MYSQL_PREFIX!}_%s` ".$where." ORDER BY %s",
1549 array($id, $ORDER, $table, $name), __FUNCTION__, __LINE__);
1550 if (SQL_NUMROWS($result) > 0) {
1551 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1552 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1553 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1554 if (empty($special)) $add = '';
1555 $ret .= '<option value="' . $value . '"';
1556 if ($default == $value) $ret .= ' selected="selected"';
1557 if (!empty($add)) $add = ' ('.$add.')';
1558 $ret .= '>' . $title . $add . '</option>';
1562 SQL_FREERESULT($result);
1565 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1569 // Return - hopefully - the requested data
1572 // Activate exchange
1573 function activateExchange () {
1574 // Is the extension 'user' there?
1575 if (!EXT_IS_ACTIVE('user')) {
1576 // Silently abort here
1580 // Check total amount of users
1581 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1583 if ($totalUsers >= getConfig('activate_xchange')) {
1586 "UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1587 "UPDATE `{!_MYSQL_PREFIX!}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1588 "UPDATE `{!_MYSQL_PREFIX!}_config` SET `activate_xchange`=0 WHERE `config`=0 LIMIT 1"
1592 runFilterChain('run_sqls');
1595 // @TODO Rewrite this to a filter
1596 rebuildCacheFiles('config', 'config');
1597 rebuildCacheFiles('modreg', 'modreg');
1601 // Deletes a user account with given reason
1602 function deleteUserAccount ($uid, $reason) {
1604 $result = SQL_QUERY_ESC("SELECT (SUM(p.points) - d.used_points) AS points
1605 FROM `{!_MYSQL_PREFIX!}_user_points` AS p
1606 LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1607 ON p.userid=d.userid
1608 WHERE p.userid=%s", array(bigintval($uid)), __FUNCTION__, __LINE__);
1609 if (SQL_NUMROWS($result) == 1) {
1610 // Save his points to add them to the jackpot
1611 list($points) = SQL_FETCHROW($result);
1613 // Delete points entries as well
1614 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_points` WHERE userid=%s", array(bigintval($uid)), __FUNCTION__, __LINE__);
1616 // Update mediadata as well
1617 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
1619 MEDIA_UPDATE_ENTRY(array('total_points'), 'sub', $points);
1622 // Now, when we have all his points adds them do the jackpot!
1623 ADD_JACKPOT($points);
1627 SQL_FREERESULT($result);
1629 // Delete category selections as well...
1630 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_cats` WHERE userid=%s",
1631 array(bigintval($uid)), __FUNCTION__, __LINE__);
1633 // Remove from rallye if found
1634 if (EXT_IS_ACTIVE('rallye')) {
1635 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_rallye_users` WHERE userid=%s",
1636 array(bigintval($uid)), __FUNCTION__, __LINE__);
1639 // Now a mail to the user and that's all...
1640 $msg = LOAD_EMAIL_TEMPLATE('del-user', array('text' => $reason), $uid);
1641 sendEmail($uid, getMessage('ADMIN_DEL_ACCOUNT'), $msg);
1643 // Ok, delete the account!
1644 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($uid)), __FUNCTION__, __LINE__);
1647 // Generates meta description for given module and 'what' value
1648 function generateMetaDescriptionCode ($mod, $wht) {
1649 // Exclude admin and member's area
1650 if (($mod != 'admin') && ($mod != 'login')) {
1651 // Construct dynamic description
1652 $DESCR = '{!MAIN_TITLE!} '.trim(getConfig('title_middle')) . ' ' . ADD_DESCR('guest', 'what-'.$wht, true);
1654 // Output it directly
1655 OUTPUT_HTML('<meta name="description" content="' . $DESCR . '" />');
1659 unset($GLOBALS['ref_level']);
1662 // Adds points to the jackpot
1663 function ADD_JACKPOT ($points) {
1664 $result = SQL_QUERY("SELECT points FROM `{!_MYSQL_PREFIX!}_jackpot` WHERE ok='ok' LIMIT 1", __FUNCTION__, __LINE__);
1665 if (SQL_NUMROWS($result) == 0) {
1667 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_jackpot` (ok, points) VALUES ('ok','%s')", array($points), __FUNCTION__, __LINE__);
1670 SQL_FREERESULT($result);
1673 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_jackpot` SET points=points+%s WHERE ok='ok' LIMIT 1",
1674 array($points), __FUNCTION__, __LINE__);
1678 // Subtracts points from the jackpot
1679 function SUB_JACKPOT ($points) {
1683 // Get current points
1684 $result = SQL_QUERY("SELECT points FROM `{!_MYSQL_PREFIX!}_jackpot` WHERE ok='ok' LIMIT 1", __FUNCTION__, __LINE__);
1685 if (SQL_NUMROWS($result) == 0) {
1687 SQL_QUERY("INSERT INTO `{!_MYSQL_PREFIX!}_jackpot` (ok, points) VALUES ('ok', 0.00000)", __FUNCTION__, __LINE__);
1690 list($jackpot) = SQL_FETCHROW($result);
1691 if ($jackpot >= $points) {
1692 // Update points when there are enougth points in jackpot
1693 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_jackpot` SET points=points-%s WHERE ok='ok' LIMIT 1",
1694 array($points), __FUNCTION__, __LINE__);
1695 $ret = $jackpot - $points;
1700 SQL_FREERESULT($result);
1703 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
1704 function IS_DEMO () {
1705 return ((EXT_IS_ACTIVE('demo')) && (getSession('admin_login') == 'demo'));
1708 // Gets the matching what name from module
1709 function getWhatFromModule ($modCheck) {
1710 // Is the request element set?
1711 if (REQUEST_ISSET_GET('what')) {
1712 // Then return this!
1713 return REQUEST_GET('what');
1717 //* DEBUG: */ echo __LINE__.'!'.$modCheck."!<br />\n";
1727 if (($modCheck == 'index') && (getConfig('index_home') != '')) $wht = getConfig('index_home');
1735 // Return what value
1739 // Subtract points from database and mediadata cache
1740 function SUB_POINTS ($subject, $uid, $points) {
1741 // Add points to used points
1742 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `used_points`=`used_points`+%s WHERE userid=%s LIMIT 1",
1743 array($points, bigintval($uid)), __FUNCTION__, __LINE__);
1745 // Insert booking record
1746 if (EXT_IS_ACTIVE('booking')) {
1748 ADD_BOOKING_RECORD($subject, $uid, $points, 'sub');
1751 // Update mediadata as well
1752 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
1754 MEDIA_UPDATE_ENTRY(array('total_points'), 'sub', $points);
1758 // Update config entries
1759 function updateConfiguration ($entries, $values, $updateMode='') {
1760 // Do not update config in CSS mode
1761 if (($GLOBALS['output_mode'] == '1') || ($GLOBALS['output_mode'] == -1)) {
1765 // Do we have multiple entries?
1766 if (is_array($entries)) {
1769 foreach ($entries as $idx => $entry) {
1771 if (!empty($updateMode)) {
1773 // @TODO Find a way for updating $_CONFIG here
1774 $all .= sprintf("%s=%s%s%s,", $entry, $entry, $updateMode, (float)$values[$idx]);
1776 // Check if string or number
1777 if (($values[$idx] + 0) === $values[$idx]) {
1779 $all .= sprintf("%s=%s,", $entry, (float)$values[$idx]);
1780 } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
1781 // Function UNIX_TIMESTAMP() detected
1782 $all .= sprintf("%s=%s,", $entry, $values[$idx]);
1785 $all .= sprintf("%s='%s',", $entry, SQL_ESCAPE($values[$idx]));
1789 // Set it in config as well
1790 setConfigEntry($entry, $values[$idx]);
1793 // Remove last comma
1794 $entries = substr($all, 0, -1);
1795 } elseif (!empty($updateMode)) {
1797 // @TODO Find a way for updating $_CONFIG here
1798 $entries .= sprintf("=%s%s%s", $entries, $updateMode, (float)$values);
1800 // Set it in config first
1801 setConfigEntry($entries, $values);
1803 // Regular entry to update
1804 $entries .= sprintf("='%s'", SQL_ESCAPE($values));
1807 // Run database update
1808 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "entries={$entries}");
1809 SQL_QUERY("UPDATE `{!_MYSQL_PREFIX!}_config` SET ".$entries." WHERE config=0 LIMIT 1", __FUNCTION__, __LINE__);
1811 // Get affected rows
1812 $affectedRows = SQL_AFFECTEDROWS();
1813 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):entries={$entries},affectedRows={$affectedRows}<br />\n";
1816 rebuildCacheFiles('config', 'config');
1819 // Prepares an SQL statement part for HTML mail and/or holiday depency
1820 // @TODO Can this be rewritten to a filter?
1821 function PREPARE_SQL_HTML_HOLIDAY ($mode) {
1822 // Exclude no users by default
1826 if ($mode == 'html') $MORE = " AND `html`='Y'";
1827 if (GET_EXT_VERSION('holiday') >= '0.1.3') {
1828 // Add something for the holiday extension
1829 $MORE .= " AND `holiday_active`='N'";
1836 // "Getter" for total available receivers
1837 function getTotalReceivers ($mode='normal') {
1839 $result_all = SQL_QUERY("SELECT userid
1840 FROM `{!_MYSQL_PREFIX!}_user_data`
1841 WHERE `status`='CONFIRMED' AND receive_mails > 0 ".PREPARE_SQL_HTML_HOLIDAY($mode),
1842 __FUNCTION__, __LINE__);
1845 $numRows = SQL_NUMROWS($result_all);
1848 SQL_FREERESULT($result_all);
1854 // Returns HTML code with an "<option> list" of all categories
1855 function generateCategoryOptionsList ($mode) {
1856 // Prepare WHERE statement
1857 $whereStatement = " WHERE `visible`='Y'";
1858 if (IS_ADMIN()) $whereStatement = '';
1860 // Initialize array...
1868 $result = SQL_QUERY("SELECT id, cat FROM `{!_MYSQL_PREFIX!}_cats`".$whereStatement." ORDER BY `sort`", __FUNCTION__, __LINE__);
1869 if (SQL_NUMROWS($result) > 0) {
1870 // ... and begin loading stuff
1871 while ($content = SQL_FETCHARRAY($result)) {
1872 // Transfer some data
1873 $CATS['id'][] = $content['id'];
1874 $CATS['name'][] = $content['cat'];
1876 // Check which users are in this category
1877 $result_uids = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_cats` WHERE cat_id=%s",
1878 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1882 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
1883 while (list($ucat) = SQL_FETCHROW($result_uids)) {
1884 $result_ver = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data`
1885 WHERE userid=%s AND `status`='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML_HOLIDAY($mode)." LIMIT 1",
1886 array(bigintval($ucat)), __FUNCTION__, __LINE__);
1889 $uid_cnt += SQL_NUMROWS($result_ver);
1892 SQL_FREERESULT($result_ver);
1896 SQL_FREERESULT($result_uids);
1899 $CATS['uids'][] = $uid_cnt;
1903 SQL_FREERESULT($result);
1907 foreach ($CATS['id'] as $key => $value) {
1908 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1909 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['uids'][$key] . ' {--USER_IN_CAT--})</option>';
1912 // No cateogries are defined yet
1913 $OUT = '<option class="member_failed">{!MEMBER_NO_CATS!}</option>';
1920 // Add bonus mail to queue
1921 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1922 // Is admin or bonus extension there?
1926 } elseif (!EXT_IS_ACTIVE('bonus')) {
1931 // Calculcate target sent
1932 $target = countSelection(explode(';', $receiverList));
1934 // Receiver is zero?
1935 if ($receiver == 0) {
1937 $receiver = $target;
1940 // HTML extension active?
1941 if (EXT_IS_ACTIVE('html_mail')) {
1942 // No HTML by default
1946 if ($mode == 'html') $HTML = 'Y';
1949 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_bonus`
1950 (subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent, html_msg)
1951 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1961 bigintval($receiver),
1963 ), __FUNCTION__, __LINE__);
1966 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_bonus`
1967 (subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent)
1968 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1978 bigintval($receiver),
1979 ), __FUNCTION__, __LINE__);
1983 // Generate a receiver list for given category and maximum receivers
1984 function generateReceiverList ($cat, $receiver, $mode = '') {
1992 $cat = bigintval($cat);
1993 $receiver = bigintval($receiver);
1995 // Is the receiver zero and mode set?
1996 if (($receiver == 0) && (!empty($mode))) {
1997 // Auto-fix receiver maximum
1998 $receiver = getTotalReceivers($mode);
2004 $CAT_TABS = "LEFT JOIN `{!_MYSQL_PREFIX!}_user_cats` AS c ON d.userid=c.userid";
2005 $CAT_WHERE = " AND c.cat_id=%s";
2008 // Exclude users in holiday?
2009 if (GET_EXT_VERSION('holiday') >= '0.1.3') {
2010 // Add something for the holiday extension
2011 $CAT_WHERE .= " AND d.`holiday_active`='N'";
2014 if ((EXT_IS_ACTIVE('html_mail')) && ($mode == 'html')) {
2015 // Only include HTML receivers
2016 $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.%s %s LIMIT %s",
2017 array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
2020 $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.%s %s LIMIT %s",
2021 array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
2025 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
2027 while ($content = SQL_FETCHARRAY($result)) {
2028 // Add receiver when not empty
2029 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
2033 SQL_FREERESULT($result);
2035 // Remove trailing semicolon
2036 $receiverList = substr($receiverList, 0, -1);
2040 return $receiverList;
2043 // Get timestamp for given stats type and data
2044 function getTimestampFromUserStats ($type, $data, $uid = 0) {
2045 // Default timestamp is zero
2049 if ((isUserIdSet()) && ($uid == 0)) {
2053 // Is the extension installed and updated?
2054 if ((!EXT_IS_ACTIVE('sql_patches')) || (EXT_VERSION_IS_OLDER('sql_patches', '0.5.6'))) {
2059 // Try to find the entry
2060 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`inserted`) AS `stamp`
2061 FROM `{!_MYSQL_PREFIX!}_user_stats_data`
2062 WHERE userid=%s AND stats_type='%s' AND stats_data='%s'
2064 array(bigintval($uid), $type, $data), __FUNCTION__, __LINE__);
2066 // Is the entry there?
2067 if (SQL_NUMROWS($result) == 1) {
2069 list($stamp) = SQL_FETCHROW($result);
2073 SQL_FREERESULT($result);
2079 // Inserts user stats
2080 function insertUserStatsRecord ($uid, $type, $data) {
2081 // Is the extension installed and updated?
2082 if ((!EXT_IS_ACTIVE('sql_patches')) || (EXT_VERSION_IS_OLDER('sql_patches', '0.5.6'))) {
2088 if ((!getTimestampFromUserStats($type, $data, $uid)) && (!is_array($data))) {
2090 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
2091 array(bigintval($uid), $type, $data), __FUNCTION__, __LINE__);
2092 } elseif (is_array($data)) {
2094 DEBUG_LOG(__FUNCTION__, __LINE__, " uid={$uid},type={$type},data={".gettype($data).": Invalid statistics data type!");
2098 // "Getter" for array for user refs and points in given level
2099 function getUserReferalPoints ($uid, $level) {
2100 //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
2101 // Default is no refs and no nickname
2105 // Do we have nickname extension installed?
2106 if (EXT_IS_ACTIVE('nickname')) {
2107 $add = ', ud.nickname';
2110 // Get refs from database
2111 $result = SQL_QUERY_ESC("SELECT ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2112 FROM `{!_MYSQL_PREFIX!}_user_refs` AS ur
2113 LEFT JOIN `{!_MYSQL_PREFIX!}_user_points` AS up
2114 ON ur.refid=up.userid AND ur.level=0
2115 LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS ud
2116 ON ur.refid=ud.userid
2117 WHERE ur.userid=%s AND ur.level=%s
2118 ORDER BY ur.refid ASC",
2119 array(bigintval($uid), bigintval($level)), __FUNCTION__, __LINE__);
2121 // Are there some entries?
2122 if (SQL_NUMROWS($result) > 0) {
2123 // Fetch all entries
2124 while ($row = SQL_FETCHARRAY($result)) {
2125 // Get total points of this user
2126 $row['points'] = GET_TOTAL_DATA($row['refid'], 'user_points', 'points') - GET_TOTAL_DATA($row['refid'], 'user_data', 'used_points');
2128 // Get unconfirmed mails
2129 $row['unconfirmed'] = GET_TOTAL_DATA($row['refid'], 'user_links', 'id', 'userid', true);
2131 // Init clickrate with zero
2132 $row['clickrate'] = 0;
2134 // Is at least one mail received?
2135 if ($row['emails_received'] > 0) {
2136 // Calculate clickrate
2137 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2140 // Activity is 'active' by default because if autopurge is not installed
2141 $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2143 // Is autopurge installed and the user inactive?
2144 if ((EXT_IS_ACTIVE('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online'])) {
2146 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2149 // Remove some entries
2150 unset($row['mails_confirmed']);
2151 unset($row['emails_received']);
2152 unset($row['last_online']);
2155 $refs[$row['id']] = $row;
2160 SQL_FREERESULT($result);
2163 //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
2167 // Recuce the amount of received emails for the receipients for given email
2168 function reduceRecipientReceivedMails ($column, $id, $count) {
2169 // Search for mail in database
2170 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{!_MYSQL_PREFIX!}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2171 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2173 // Are there entries?
2174 if (SQL_NUMROWS($result) > 0) {
2175 // Now load all userids for one big query!
2176 // @TODO This can be somehow rewritten
2178 while (list($uid) = SQL_FETCHROW($result)) {
2182 // Now update all user accounts
2183 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2184 array(implode(',', $UIDs), count($UIDs)), __FUNCTION__, __LINE__);
2188 SQL_FREERESULT($result);
2192 function INIT_SQLS () {
2196 // Checks wether the sqls array is initialized
2197 function IS_SQLS_INITIALIZED () {
2198 return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
2201 // Setter for SQLs array
2202 function SET_SQLS ($SQLs) {
2203 $GLOBALS['sqls'] = (array) $SQLs;
2206 // Remover for SQLs array
2207 function UNSET_SQLS () {
2208 unset($GLOBALS['sqls']);
2211 // Getter for SQLs array
2212 function GET_SQLS () {
2213 return $GLOBALS['sqls'];
2216 // Add an SQL to the list
2217 function ADD_SQL ($sql) {
2218 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("sql=%s, count=%d", $sql, COUNT_SQLS()));
2219 $GLOBALS['sqls'][] = (string) $sql;
2222 // Setter for SQLs key
2223 function SET_SQL_KEY ($key, $value) {
2224 $GLOBALS['sqls'][$key] = (string) $value;
2227 // Merge SQLs together
2228 function MERGE_SQLS ($SQLs) {
2229 SET_SQLS(merge_array(GET_SQLS(), $SQLs));
2232 // Counter for SQLs array
2233 function COUNT_SQLS () {
2237 // Is the array there?
2238 if (IS_SQLS_INITIALIZED()) {
2240 $count = count($GLOBALS['sqls']);
2241 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
2248 // Checks wether the SQLs array is filled
2249 function IS_SQLS_VALID () {
2251 (IS_SQLS_INITIALIZED()) &&