2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/26/2003 *
4 * =================== Last change: 11/29/2004 *
6 * -------------------------------------------------------------------- *
7 * File : mysql-manager.php *
8 * -------------------------------------------------------------------- *
9 * Short description : All database-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle datenbank-relevanten Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // "Getter" for module description
44 // @TODO Can we cache this?
45 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
48 $what = getIndexHome();
51 // Default is not found
52 $data['title'] = '??? (' . $what . ')';
55 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
60 ), __FUNCTION__, __LINE__);
63 if (SQL_NUMROWS($result) == 1) {
65 $data = SQL_FETCHARRAY($result);
69 SQL_FREERESULT($result);
72 return $data['title'];
75 // Add link into output stream (or return it) for 'You Are Here' navigation
76 function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
77 // Use only filename of the FQFN...
78 $file = basename($FQFN);
86 // First we have to do some analysis...
87 if (substr($file, 0, 7) == 'action-') {
88 // This is an action file!
90 $search = substr($file, 7);
92 // Get access level from it
93 $modCheck = getModuleFromFileName($file, $accessLevel);
96 $ADD = " AND (`what`='' OR `what` IS NULL)";
97 } elseif (substr($file, 0, 5) == 'what-') {
98 // This is a 'what file'!
100 $search = substr($file, 5);
102 // Get access level from it
103 $modCheck = getModuleFromFileName($file, $accessLevel);
105 // Do we have admin? Then display all
106 $ADD = " AND `visible`='Y' AND `locked`='N'";
112 $dummy = substr($search, 0, -4);
113 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
114 } elseif ($accessLevel == 'sponsor') {
118 $modCheck = getModule();
124 $modCheck = getModule();
128 // Begin the navigation line
129 if (!isset($GLOBALS['nav_depth'])) {
131 $GLOBALS['nav_depth'] = '0';
133 // Run the pre-filter chain
134 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
137 $prefix = $ret['content'];
139 $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>';
140 } elseif ($return === false) {
142 $GLOBALS['nav_depth']++;
145 $prefix .= ' -> ';
147 // We need to remove .php and the end
148 if (substr($search, -4, 4) == '.php') {
150 $search = substr($search, 0, -4);
153 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
155 $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>';
157 // Can we close the you-are-here navigation?
158 //* DEBUG: */ debugOutput(__LINE__.'*'.$type.'/'.getWhat().'*');
159 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
160 //* DEBUG: */ debugOutput(__LINE__.'+'.$type.'+');
161 // Add closing div and br-tag
163 $GLOBALS['nav_depth'] = '0';
165 // Run the post-filter chain
166 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
168 // Add additional content
169 $OUT .= $ret['content'];
173 // Return or output HTML code?
174 if ($return === true) {
178 // Output HTML code here
183 // Adds a menu (mode = guest/member/admin/sponsor) to output
184 function addMenu ($mode, $action, $what) {
185 // Init some variables
189 // is the menu action valid?
190 if (!isMenuActionValid($mode, $action, $what, true)) {
191 return getCode('MENU_NOT_VALID');
194 // Non-admin shall not see all menus
196 $ADD = " AND `visible`='Y' AND `locked`='N'";
199 // Load SQL data and add the menu to the output stream...
200 $result_main = SQL_QUERY_ESC("SELECT
201 `title`, `what`, `action`, `visible`, `locked`
203 `{?_MYSQL_PREFIX?}_%s_menu`
205 (`what`='' OR `what` IS NULL)
209 array($mode), __FUNCTION__, __LINE__);
211 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . ':' . getWhat() . '*');
212 if (!SQL_HASZERONUMS($result_main)) {
213 // There are menus available, so we simply display them... :)
214 $GLOBALS['rows'] = '';
215 while ($content = SQL_FETCHARRAY($result_main)) {
216 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . ':' . getWhat() . '*');
217 // Disable the block-mode
218 enableBlockMode(false);
220 // Load menu header template
221 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
224 $result_sub = SQL_QUERY_ESC("SELECT
225 `title` AS `sub_title`,
226 `what` AS `sub_what`,
227 `visible` AS `sub_visible`,
228 `locked` AS `sub_locked`
230 `{?_MYSQL_PREFIX?}_%s_menu`
238 array($mode, $content['action']), __FUNCTION__, __LINE__);
240 // Do we have some entries?
241 if (!SQL_HASZERONUMS($result_sub)) {
245 // Load all sub menus
246 while ($content2 = SQL_FETCHARRAY($result_sub)) {
247 // Merge both arrays in one
248 $content = merge_array($content, $content2);
253 // Full file name for checking menu
254 //* DEBUG: */ debugOutput(__LINE__ . ':!!!!' . $content['sub_what'] . '!!!');
255 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
256 if (isIncludeReadable($inc)) {
257 // Mark currently selected menu - open
258 if ((!empty($what)) && (($what == $content['sub_what']))) {
263 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
266 $OUT .= '<em style="cursor:help" class="notice" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
270 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
272 if (isIncludeReadable($inc)) {
275 // Mark currently selected menu - close
276 if ((!empty($what)) && (($what == $content['sub_what']))) {
290 'what' => $content['sub_what'],
291 'visible' => $content['sub_visible'],
292 'locked' => $content['locked'],
295 // Add regular menu row or bottom row?
296 if ($count < SQL_NUMROWS($result_sub)) {
297 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
299 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
303 // This is a menu block... ;-)
307 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
308 if (isFileReadable($INC)) {
310 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
311 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . '/' . getWhat().'*');
313 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . '/' . getWhat() . '*');
314 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
316 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . '/' . $content['sub_what'] . ':' . getWhat() . '*');
320 SQL_FREERESULT($result_sub);
325 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . ':' . getWhat() . '*');
326 if (SQL_NUMROWS($result_main) > $main_cnt) {
328 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
330 // Should we display adverts in this menu?
331 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
332 // Display advert template
333 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
335 // Add seperator again
336 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
342 SQL_FREERESULT($result_main);
344 // Should we display adverts in this menu?
345 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
346 // Add seperator again
347 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
349 // Display advert template
350 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
355 'rows' => $GLOBALS['rows'],
359 // Load main template
360 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . '/' . $content['sub_what'] . ':' . getWhat() . '*');
361 loadTemplate('menu_table', false, $content);
365 // Checks wether the current user is a member
366 function isMember () {
367 // By default no member
370 // Fix missing 'last_online' array, damn stupid code :(((
371 // @TODO Try to rewrite this to one or more functions
372 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
373 $GLOBALS['last_online'] = array();
376 // Is the cache entry there?
377 if (isset($GLOBALS[__FUNCTION__])) {
379 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
380 return $GLOBALS[__FUNCTION__];
381 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
382 // Destroy any existing user session data
383 destroyMemberSession();
384 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
386 // Abort further processing
390 // Get userid secured from session
391 setMemberId(getSession('userid'));
393 // ... and set it as currently handled user id
394 setCurrentUserId(getMemberId());
396 // Init user data array
399 // Fix "deleted" cookies first
400 fixDeletedCookies(array('userid', 'u_hash'));
402 // Are cookies set and can the member data be loaded?
403 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
404 // Validate password by created the difference of it and the secret key
405 $valPass = encodeHashForCookie(getUserData('password'));
407 // So did we now have valid data and an unlocked user?
408 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
409 // Transfer last module and online time
410 $GLOBALS['last_online']['module'] = getUserData('last_module');
411 $GLOBALS['last_online']['online'] = getUserData('last_online');
413 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
418 // Is $ret still false?
419 if ($ret === false) {
420 // Yes, so destroy the session
421 destroyMemberSession();
425 $GLOBALS[__FUNCTION__] = $ret;
428 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
432 // Fetch user data for given user id
433 function fetchUserData ($value, $column = 'userid') {
434 // Extension ext-user must be there at any case
435 if (!isExtensionActive('user')) {
436 // Absent ext-user is really not good
440 // If we should look for userid secure&set it here
441 if (substr($column, -2, 2) == 'id') {
443 $value = bigintval($value);
446 setCurrentUserId($value);
448 // Don't look for invalid userids...
449 if (!isValidUserId($value)) {
450 // Invalid, so abort here
451 debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
452 } elseif (isUserDataValid()) {
453 // Use cache, so it is fine
456 } elseif (isUserDataValid()) {
457 // Using cache is fine
461 // By default none was found
466 if (isExtensionInstalledAndNewer('user', '0.3.5')) {
467 $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
470 // Query for the user
471 $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
472 array($column, $value), __FUNCTION__, __LINE__);
474 // Do we have a record?
475 if (SQL_NUMROWS($result) == 1) {
476 // Load data from cookies
477 $data = SQL_FETCHARRAY($result);
479 // Set the userid for later use
480 setCurrentUserId($data['userid']);
482 // And cache the data for this userid
483 $GLOBALS['user_data'][getCurrentUserId()] = $data;
485 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
486 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
487 // Backup the raw one and zero it
488 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
489 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = null;
492 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
493 // Seperate data/time
494 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
496 // Seperate data and time again
497 $array['date'] = explode('-', $array[0]);
498 $array['time'] = explode(':', $array[1]);
500 // Now pass it to mktime()
501 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
513 $found = isUserDataValid();
517 SQL_FREERESULT($result);
523 // This patched function will reduce many SELECT queries for the specified or current admin login
524 function isAdmin () {
525 // No admin in installation phase!
526 if ((isInstallationPhase()) || (!isAdminRegistered())) {
535 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
537 // If admin login is not given take current from cookies...
538 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
539 // Get admin login and password from session/cookies
540 $adminId = getCurrentAdminId();
541 $passCookie = getAdminMd5();
543 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId.'/'.$passCookie);
545 // Abort if admin id is zero
546 if ($adminId == '0') {
551 if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
552 // Init it with failed
553 $GLOBALS[__FUNCTION__][$adminId] = false;
555 // Search in array for entry
556 if (isset($GLOBALS['admin_hash'])) {
558 $valPass = $GLOBALS['admin_hash'];
559 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
560 // Login data is valid or not?
561 $valPass = encodeHashForCookie(getAdminHash($adminId));
564 $GLOBALS['admin_hash'] = $valPass;
567 incrementStatsEntry('cache_hits');
568 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
569 // Get admin hash and hash it
570 $valPass = encodeHashForCookie(getAdminHash($adminId));
573 $GLOBALS['admin_hash'] = $valPass;
576 if (!empty($valPass)) {
577 // Check if password is valid
578 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
579 $GLOBALS[__FUNCTION__][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
583 // Return result of comparision
584 return $GLOBALS[__FUNCTION__][$adminId];
587 // Generates a list of "max receiveable emails per day"
588 function addMaxReceiveList ($mode, $default = '', $return = false) {
594 // Guests (in the registration form) are not allowed to select 0 mails per day.
595 $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
596 __FUNCTION__, __LINE__);
600 // Members are allowed to set to zero mails per day (we will change this soon!)
601 $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
602 __FUNCTION__, __LINE__);
606 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
610 // Some entries are found?
611 if (!SQL_HASZERONUMS($result)) {
613 while ($content = SQL_FETCHARRAY($result)) {
614 $OUT .= ' <option value="' . $content['value'] . '"';
615 if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
616 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
617 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
622 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
624 // Maybe the admin has to setup some maximum values?
625 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
629 SQL_FREERESULT($result);
631 if ($return === true) {
632 // Return generated HTML code
635 // Output directly (default)
640 // Checks wether the given email address is used.
641 function isEmailTaken ($email) {
642 // Replace dot with {DOT}
643 $email = str_replace('.', '{DOT}', $email);
645 // Query the database
646 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '%%%s%%' LIMIT 1",
647 array($email), __FUNCTION__, __LINE__);
649 // Is the email there?
650 $isTaken = (SQL_NUMROWS($result) == 1);
653 SQL_FREERESULT($result);
659 // Validate the given menu action
660 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
661 // Is the cache entry there and we shall not update?
662 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
664 incrementStatsEntry('cache_hits');
666 // Then use this cache
667 return $GLOBALS['action_valid'][$mode][$action][$what];
670 // By default nothing is valid
673 // Look in all menus or only unlocked
675 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
677 //* DEBUG: */ debugOutput(__LINE__ . ':' . $mode . '/' . $action . '/' . $what . '*');
678 if (($mode != 'admin') && ($updateEntry === true)) {
679 // Update guest or member menu
680 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
685 ), __FUNCTION__, __LINE__, false);
686 } elseif (($what != 'overview') && (!empty($what))) {
688 $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",
693 ), __FUNCTION__, __LINE__, false);
695 // Admin login overview
696 $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",
700 ), __FUNCTION__, __LINE__, false);
704 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
706 // Should we look for affected rows (only update) or found rows?
707 if ($updateEntry === true) {
708 // Check updated/affected rows
709 $ret = (!SQL_HASZEROAFFECTED());
712 $ret = (!SQL_HASZERONUMS($result));
716 SQL_FREERESULT($result);
719 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
725 // Get action value from mode (admin/guest/member) and what-value
726 function getActionFromModuleWhat ($module, $what) {
728 $data['action'] = '';
730 //* DEBUG: */ debugOutput(__LINE__ . '=' . $module . '/'.$what . '/' . getAction() . '=');
731 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
732 // sql_patches is missing so choose depending on mode
736 } elseif ($module == 'admin') {
743 } elseif ((empty($what)) && ($module != 'admin')) {
744 // Use configured 'home'
745 $what = getIndexHome();
748 if ($module == 'admin') {
749 // Action value for admin area
750 if (isGetRequestParameterSet('action')) {
752 return getRequestParameter('action');
753 } elseif (isActionSet()) {
754 // Get it directly from URL
756 } elseif (($what == 'overview') || (!isWhatSet())) {
757 // Default value for admin area
758 $data['action'] = 'login';
760 } elseif (isActionSet()) {
761 // Get it directly from URL
764 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
766 // Does the module have a menu?
767 if (ifModuleHasMenu($module)) {
768 // Rewriting modules to menu
769 $module = mapModuleToTable($module);
771 // Guest and member menu is 'main' as the default
772 if (empty($data['action'])) $data['action'] = 'main';
774 // Load from database
775 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
776 array($module, $what), __FUNCTION__, __LINE__);
777 if (SQL_NUMROWS($result) == 1) {
778 // Load action value and pray that this one is the right you want... ;-)
779 $data = SQL_FETCHARRAY($result);
783 SQL_FREERESULT($result);
784 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
785 // No sql_patches installed, but maybe we need to register an admin?
786 if (isAdminRegistered()) {
787 // Redirect to admin area
788 redirectToUrl('admin.php');
792 // Return action value
793 return $data['action'];
796 // Get category name back
797 function getCategory ($cid) {
798 // Default is not found
799 $data['cat'] = '{--_CATEGORY_404--}';
801 // Is the category id set?
804 $data['cat'] = '{--_CATEGORY_NONE--}';
805 } elseif ($cid > 0) {
806 // Lookup the category in database
807 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
808 array(bigintval($cid)), __FUNCTION__, __LINE__);
809 if (SQL_NUMROWS($result) == 1) {
810 // Category found... :-)
811 $data = SQL_FETCHARRAY($result);
815 SQL_FREERESULT($result);
822 // Get a string of "mail title" and price back
823 function getPaymentTitlePrice ($pid, $full=false) {
824 // Default is not found
825 $ret = '{--_PAYMENT_404--}';
828 $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
829 array(bigintval($pid)), __FUNCTION__, __LINE__);
831 // Do we have an entry?
832 if (SQL_NUMROWS($result) == 1) {
833 // Payment type found... :-)
834 $data = SQL_FETCHARRAY($result);
836 // Only title or also including price?
837 if ($full === false) {
838 $ret = $data['mail_title'];
840 $ret = $data['mail_title'] . ' / {%pipe,translateComma=' . $data['price'] . '%} {?POINTS?}';
845 SQL_FREERESULT($result);
851 // Get (basicly) the price of given payment id
852 function getPaymentPoints ($pid, $lookFor = 'price') {
854 $data[$lookFor] = -1;
856 // Search for it in database
857 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
858 array($lookFor, $pid), __FUNCTION__, __LINE__);
860 // Is the entry there?
861 if (SQL_NUMROWS($result) == 1) {
862 // Payment type found... :-)
863 $data = SQL_FETCHARRAY($result);
867 SQL_FREERESULT($result);
870 return $data[$lookFor];
873 // Remove a receiver's id from $receivers and add a link for him to confirm
874 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = 0, $isBonusMail = false) {
875 // Default is not removed
878 // Is the userid valid?
879 if (isValidUserId($userid)) {
880 // Remove entry from array
881 unset($receivers[$key]);
883 // Is there already a line for this user available?
885 // Default is 'normal' mail
887 $rowName = 'stats_id';
889 // Only when we got a real stats id continue searching for the entry
890 if ($isBonusMail === true) {
892 $rowName = 'bonus_id';
895 // Try to look the entry up
896 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
897 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
899 // Was it *not* found?
900 if (SQL_HASZERONUMS($result)) {
902 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
903 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
905 // Update 'mails_sent' if sql_patches is updated
906 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
908 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1",
909 array(bigintval($pool_id)), __FUNCTION__, __LINE__);
918 SQL_FREERESULT($result);
922 // Return status for sending routine
926 // Calculate sum (default) or count records of given criteria
927 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '', $mode = '=') {
931 //* DEBUG: */ debugOutput($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add);
932 if ((empty($search)) && ($search != '0')) {
933 // Count or sum whole table?
934 if ($countRows === true) {
936 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`".$add,
940 ), __FUNCTION__, __LINE__);
943 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`".$add,
947 ), __FUNCTION__, __LINE__);
949 } elseif (($countRows === true) || ($lookFor == 'userid')) {
951 //* DEBUG: */ debugOutput('COUNT!');
952 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'".$add,
959 ), __FUNCTION__, __LINE__);
962 //* DEBUG: */ debugOutput('SUM!');
963 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'".$add,
970 ), __FUNCTION__, __LINE__);
974 $data = SQL_FETCHARRAY($result);
977 SQL_FREERESULT($result);
980 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
982 $data['res'] = '0.00000';
983 } elseif (''.$data['res'].'' == '') {
989 //* DEBUG: */ debugOutput('ret=' . $data['res']);
992 // Getter fro ref level percents
993 function getReferalLevelPercents ($level) {
995 $data['percents'] = '0';
998 if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
999 // First look for level
1000 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1001 if ($key !== false) {
1003 $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1006 incrementStatsEntry('cache_hits');
1008 } elseif (!isExtensionActive('cache')) {
1010 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`=%s LIMIT 1",
1011 array(bigintval($level)), __FUNCTION__, __LINE__);
1014 if (SQL_NUMROWS($result_level) == 1) {
1016 $data = SQL_FETCHARRAY($result_level);
1020 SQL_FREERESULT($result_level);
1024 return $data['percents'];
1029 * Dynamic referal and points system, can also send mails!
1031 * subject = Subject line, write in lower-case letters and underscore is allowed
1032 * userid = Referal id wich should receive...
1033 * points = ... xxx points
1034 * sendNotify = shall I send the referal an email or not?
1035 * refid = inc/modules/guest/what-confirm.php need this
1036 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
1037 * add_mode = Add points only to $userid or also refs? (WARNING! Changing 'REFERAL' to 'DIRECT'
1038 * for default value will cause no referal will get points ever!!!)
1040 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $refid = '0', $addMode = 'REFERAL') {
1041 // By default nothing has been added
1044 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">' . __FUNCTION__ . ' - ENTRY</font> ------------------------<ul><li>');
1045 // Convert mode to upper-case
1046 $addMode = strtoupper($addMode);
1048 // When $userid = '0' add points to jackpot
1049 if (($userid == '0') && (isExtensionActive('jackpot'))) {
1050 // Add points to jackpot
1051 return addPointsToJackpot($points);
1054 // Count up referal depth
1055 if (!isset($GLOBALS['ref_level'])) {
1056 // Initialialize referal system
1057 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' Referal system initialized!');
1058 $GLOBALS['ref_level'] = NULL;
1060 // Increase referal level
1061 $GLOBALS['ref_level']++;
1062 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' Referal level increased. DEPTH='.$GLOBALS['ref_level']);
1065 // Check user account
1066 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',points='.$points);
1067 if (fetchUserData($userid)) {
1068 // Determine wether the user has some mails to click before he/she gets the points
1069 $locked = ifUserPointsLocked($userid);
1071 // Detect database column
1072 $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $locked);
1074 // This is the user and his ref
1075 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1078 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1079 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',points='.$points.',depth='.$GLOBALS['ref_level'].',per='.$per.',mode='.$addMode);
1081 // Some percents found?
1083 // Calculate new points
1084 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',points='.$points.',per='.$per.',depth='.$GLOBALS['ref_level']);
1085 $ref_points = $points * $per / 100;
1087 // Pay refback here if level > 0 and in ref-mode
1088 if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($addMode == 'REFERAL') && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1089 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',data='.$GLOBALS['cache_array']['add_userid'][$userid].',ref_points='.$ref_points.',depth='.$GLOBALS['ref_level'].' - BEFORE!');
1090 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1091 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',data='.$GLOBALS['cache_array']['add_userid'][$userid].',ref_points='.$ref_points.',depth='.$GLOBALS['ref_level'].' - AFTER!');
1095 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
1101 makeZeroToNull($GLOBALS['ref_level'])
1102 ), __FUNCTION__, __LINE__);
1103 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'pointsColumn='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.$GLOBALS['ref_level'].',mode='.$addMode.' - UPDATE! ('.SQL_AFFECTEDROWS().')');
1105 // No entry updated?
1106 if (SQL_HASZEROAFFECTED()) {
1107 // First ref in this level! :-)
1108 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`, `ref_depth`, `%s`) VALUES (%s, %s, %s)",
1112 makeZeroToNull($GLOBALS['ref_level']),
1114 ), __FUNCTION__, __LINE__);
1115 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.$GLOBALS['ref_level'].',mode='.$addMode.' - INSERTED! ('.SQL_AFFECTEDROWS().')');
1118 // Check affected rows
1119 $added = SQL_AFFECTEDROWS();
1120 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added='.intval($added));
1122 // Prepare data for the filter
1123 $filterData = array(
1124 'subject' => $subject,
1125 'userid' => $userid,
1126 'points' => $points,
1127 'ref_points' => $ref_points,
1128 'column' => $pointsColumn,
1129 'notify' => $sendNotify,
1131 'locked' => $locked,
1133 'add_mode' => $addMode,
1138 $filterData = runFilterChain('post_add_points', $filterData);
1141 $added = $filterData['added'];
1142 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added='.intval($added));
1144 // Points updated, maybe I shall send him an email?
1145 if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
1149 'level' => bigintval($GLOBALS['ref_level']),
1150 'points' => $ref_points,
1153 // Load email template
1154 $message = loadEmailTemplate('guest_user_confirmed_referal', $content, bigintval($userid));
1157 sendEmail($userid, '{--THANX_REFERAL_ONE_SUBJECT--}', $message);
1158 } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($addMode == 'DIRECT')) {
1161 'reason' => '{--REASON_DIRECT_PAYMENT--}',
1162 'points' => $ref_points
1166 $message = loadEmailTemplate('member_add_points', $content, $userid);
1169 sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
1170 if (!isGetRequestParameterSet('mid')) {
1171 // Output message to admin
1172 displayMessage('{--ADMIN_POINTS_ADDED--}');
1176 // Maybe there's another ref?
1177 if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($addMode == 'REFERAL')) {
1178 // Then let's credit him here...
1179 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',ref='.getUserData('refid').',points='.$points.' - ADVANCE!');
1180 $added = ($added && addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid')));
1185 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.': added=' . intval($added) . ' - EXIT</font> ------------------------<br />');
1189 // Updates the referal counter
1190 function updateReferalCounter ($userid) {
1191 // Make it sure referal level zero (member him-/herself) is at least selected
1192 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1193 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',level='.$GLOBALS['cache_array']['ref_level'][$userid]);
1196 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`=%s LIMIT 1",
1199 bigintval($GLOBALS['cache_array']['ref_level'][$userid])
1200 ), __FUNCTION__, __LINE__);
1202 // When no entry was updated then we have to create it here
1203 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'updated=' . SQL_AFFECTEDROWS());
1204 if (SQL_HASZEROAFFECTED()) {
1206 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1209 $GLOBALS['cache_array']['ref_level'][$userid]
1210 ), __FUNCTION__, __LINE__);
1211 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid);
1217 // Check for his referal
1218 if (fetchUserData($userid)) {
1220 $ref = getUserData('refid');
1223 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.$userid.',ref='.$ref);
1225 // When he has a referal...
1226 if (($ref > 0) && ($ref != $userid)) {
1227 // Move to next referal level and count his counter one up!
1228 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref='.$ref.' - ADVANCE!');
1229 $GLOBALS['cache_array']['ref_level'][$userid]++;
1230 updateReferalCounter($ref);
1231 } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1232 // Remove cache here
1233 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref='.$ref.' - CACHE!');
1234 rebuildCache('refsystem', 'refsystem');
1238 $GLOBALS['cache_array']['ref_level'][$userid]--;
1240 // Handle refback here if extension is installed
1241 // @TODO Rewrite this to a filter
1242 if (isExtensionActive('refback')) {
1243 updateRefbackTable($userid);
1247 // Sends out mail to all administrators. This function is no longer obsolete
1248 // because we need it when there is no ext-admins installed
1249 function sendAdminEmails ($subj, $message) {
1250 // Load all admin email addresses
1251 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1252 while ($content = SQL_FETCHARRAY($result)) {
1253 // Send the email out
1254 sendEmail($content['email'], $subj, $message);
1258 SQL_FREERESULT($result);
1260 // Really simple... ;-)
1263 // Get id number from administrator's login name
1264 function getAdminId ($adminLogin) {
1265 // By default no admin is found
1269 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1270 // Use it if found to save SQL queries
1271 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1273 // Update cache hits
1274 incrementStatsEntry('cache_hits');
1275 } elseif (!isExtensionActive('cache')) {
1276 // Load from database
1277 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1278 array($adminLogin), __FUNCTION__, __LINE__);
1280 // Do we have an entry?
1281 if (SQL_NUMROWS($result) == 1) {
1283 $data = SQL_FETCHARRAY($result);
1287 SQL_FREERESULT($result);
1294 // "Getter" for current admin id
1295 function getCurrentAdminId () {
1296 // Log debug message
1297 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1299 // Do we have cache?
1300 if (!isset($GLOBALS['current_admin_id'])) {
1301 // Get the admin login from session
1302 $adminId = getSession('admin_id');
1304 // Remember in cache securely
1305 setCurrentAdminId(bigintval($adminId));
1309 return $GLOBALS['current_admin_id'];
1312 // Setter for current admin id
1313 function setCurrentAdminId ($currentAdminId) {
1315 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1318 // Get password hash from administrator's login name
1319 function getAdminHash ($adminId) {
1320 // By default an invalid hash is returned
1321 $data['password'] = -1;
1323 if (isAdminHashSet($adminId)) {
1325 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1327 // Update cache hits
1328 incrementStatsEntry('cache_hits');
1329 } elseif (!isExtensionActive('cache')) {
1330 // Load from database
1331 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1332 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1334 // Do we have an entry?
1335 if (SQL_NUMROWS($result) == 1) {
1337 $data = SQL_FETCHARRAY($result);
1340 setAdminHash($adminId, $data['password']);
1344 SQL_FREERESULT($result);
1347 // Return password hash
1348 return $data['password'];
1351 // "Getter" for admin login
1352 function getAdminLogin ($adminId) {
1353 // By default a non-existent login is returned (other functions react on this!)
1354 $data['login'] = '***';
1356 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1358 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1360 // Update cache hits
1361 incrementStatsEntry('cache_hits');
1362 } elseif (!isExtensionActive('cache')) {
1363 // Load from database
1364 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1365 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1368 if (SQL_NUMROWS($result) == 1) {
1370 $data = SQL_FETCHARRAY($result);
1373 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1377 SQL_FREERESULT($result);
1380 // Return the result
1381 return $data['login'];
1384 // Get email address of admin id
1385 function getAdminEmail ($adminId) {
1386 // By default an invalid emails is returned
1387 $data['email'] = '***';
1389 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1391 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1393 // Update cache hits
1394 incrementStatsEntry('cache_hits');
1395 } elseif (!isExtensionActive('cache')) {
1396 // Load from database
1397 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1398 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1401 if (SQL_NUMROWS($result_admin_id) == 1) {
1403 $data = SQL_FETCHARRAY($result_admin_id);
1406 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1410 SQL_FREERESULT($result_admin_id);
1414 return $data['email'];
1417 // Get default ACL of admin id
1418 function getAdminDefaultAcl ($adminId) {
1419 // By default an invalid ACL value is returned
1420 $data['default_acl'] = 'NO-ACL';
1422 // Is sql_patches there and was it found in cache?
1423 if (!isExtensionActive('sql_patches')) {
1424 // Not found, which is bad, so we need to allow all
1425 $data['default_acl'] = 'allow';
1426 } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1428 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1430 // Update cache hits
1431 incrementStatsEntry('cache_hits');
1432 } elseif (!isExtensionActive('cache')) {
1433 // Load from database
1434 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1435 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1437 // Do we have an entry?
1438 if (SQL_NUMROWS($result_admin_id) == 1) {
1440 $data = SQL_FETCHARRAY($result_admin_id);
1443 $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1447 SQL_FREERESULT($result_admin_id);
1450 // Return default ACL
1451 return $data['default_acl'];
1454 // Generates an option list from various parameters
1455 function generateOptionList ($table, $id, $name, $default = '', $special = '', $where = '', $disabled = array(), $callback = '') {
1457 if ($table == '/ARRAY/') {
1458 // Selection from array
1459 if ((is_array($id)) && (is_array($name)) && ((count($id)) == (count($name)) || (!empty($callback)))) {
1461 foreach ($id as $idx => $value) {
1462 $ret .= '<option value="' . $value . '"';
1463 if ($default == $value) {
1464 // Selected by default
1465 $ret .= ' selected="selected"';
1466 } elseif (isset($disabled[$value])) {
1468 $ret .= ' disabled="disabled"';
1471 // Is the call-back function set?
1472 if (!empty($callback)) {
1474 $name[$idx] = call_user_func_array($callback, array($id[$idx]));
1477 // Finish option tag
1478 $ret .= '>' . $name[$idx] . '</option>';
1481 // Problem in request
1482 debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
1485 // Data from database
1486 $SPEC = ', `' . $id . '`';
1487 if (!empty($special)) {
1488 $SPEC = ', `' . $special . '`';
1491 // Query the database
1492 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1498 ), __FUNCTION__, __LINE__);
1501 if (!SQL_HASZERONUMS($result)) {
1502 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1503 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1504 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1505 if (empty($special)) $add = '';
1506 $ret .= '<option value="' . $value . '"';
1507 if ($default == $value) {
1508 // Selected by default
1509 $ret .= ' selected="selected"';
1510 } elseif (isset($disabled[$value])) {
1512 $ret .= ' disabled="disabled"';
1517 $add = ' ('.$add.')';
1520 // Is the call-back function set?
1521 if (!empty($callback)) {
1523 $title = call_user_func_array($callback, array($title));
1526 // Finish option list
1527 $ret .= '>' . $title . $add . '</option>';
1531 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1535 SQL_FREERESULT($result);
1538 // Return - hopefully - the requested data
1541 // Activate exchange
1542 function FILTER_ACTIVATE_EXCHANGE () {
1543 // Is the extension 'user' there?
1544 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1545 // Silently abort here
1549 // Check total amount of users
1550 if (getTotalConfirmedUser() >= getActivateXchange()) {
1552 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1");
1553 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1556 runFilterChain('run_sqls');
1558 // Update configuration
1559 updateConfiguration('activate_xchange' ,0);
1562 rebuildCache('modules', 'modules');
1566 // Deletes a user account with given reason
1567 function deleteUserAccount ($userid, $reason) {
1569 $data['points'] = '0';
1571 // Search for the points and user data
1572 $result = SQL_QUERY_ESC("SELECT
1573 (SUM(p.`points`) - d.`used_points`) AS `points`
1575 `{?_MYSQL_PREFIX?}_user_points` AS p
1577 `{?_MYSQL_PREFIX?}_user_data` AS d
1579 p.`userid`=d.`userid`
1583 array(bigintval($userid)), __FUNCTION__, __LINE__);
1585 // Do we have an entry?
1586 if (SQL_NUMROWS($result) == 1) {
1587 // Save his points to add them to the jackpot
1588 $data = SQL_FETCHARRAY($result);
1590 // Delete points entries as well
1591 // @TODO Rewrite these lines to a filter
1592 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1593 array(bigintval($userid)), __FUNCTION__, __LINE__);
1595 // Update mediadata as well
1596 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1598 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1601 // Now, when we have all his points adds them do the jackpot!
1602 if (isExtensionActive('jackpot')) {
1603 addPointsToJackpot($data['points']);
1608 SQL_FREERESULT($result);
1610 // Delete category selections as well...
1611 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1612 array(bigintval($userid)), __FUNCTION__, __LINE__);
1614 // Remove from rallye if found
1615 // @TODO Rewrite this to a filter
1616 if (isExtensionActive('rallye')) {
1617 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1618 array(bigintval($userid)), __FUNCTION__, __LINE__);
1621 // Add reason and translate points
1622 $data['text'] = $reason;
1624 // Now a mail to the user and that's all...
1625 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1626 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1628 // Ok, delete the account!
1629 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1632 // Gets the matching what name from module
1633 function getWhatFromModule ($modCheck) {
1634 // Is the request element set?
1635 if (isGetRequestParameterSet('what')) {
1636 // Then return this!
1637 return getRequestParameter('what');
1643 //* DEBUG: */ debugOutput(__LINE__.'!'.$modCheck.'!');
1644 switch ($modCheck) {
1651 // Is ext-sql_patches installed and newer than 0.0.5?
1652 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1653 // Use it from config
1654 $what = getIndexHome();
1656 // Use default 'welcome'
1666 // Return what value
1670 // Subtract points from database and mediadata cache
1671 function subtractPoints ($subject, $userid, $points) {
1672 // Add points to used points
1673 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1674 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1676 // Prepare filter data
1677 $filterData = array(
1678 'subject' => $subject,
1679 'userid' => $userid,
1680 'points' => $points,
1682 'added' => (!SQL_HASZEROAFFECTED())
1685 // Insert booking record
1686 $filterData = runFilterChain('sub_points', $filterData);
1689 return $filterData['added'];
1692 // "Getter" for total available receivers
1693 function getTotalReceivers ($mode = 'normal') {
1695 $numRows = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND `receive_mails` > 0' . runFilterChain('exclude_users', $mode));
1701 // Returns HTML code with an option list of all categories
1702 function generateCategoryOptionsList ($mode) {
1703 // Prepare WHERE statement
1704 $whereStatement = " WHERE `visible`='Y'";
1705 if (isAdmin()) $whereStatement = '';
1707 // Initialize array...
1711 'userids' => array()
1715 $result = SQL_QUERY('SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`' . $whereStatement . ' ORDER BY `sort` ASC',
1716 __FUNCTION__, __LINE__);
1718 // Do we have entries?
1719 if (!SQL_HASZERONUMS($result)) {
1720 // ... and begin loading stuff
1721 while ($content = SQL_FETCHARRAY($result)) {
1722 // Transfer some data
1723 $CATS['id'][] = $content['id'];
1724 $CATS['name'][] = $content['cat'];
1726 // Check which users are in this category
1727 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1728 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1734 while ($data = SQL_FETCHARRAY($result_userids)) {
1736 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1740 SQL_FREERESULT($result_userids);
1743 $CATS['userids'][] = $userid_cnt;
1747 SQL_FREERESULT($result);
1751 foreach ($CATS['id'] as $key => $value) {
1752 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1753 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1756 // No cateogries are defined yet
1757 $OUT = '<option class="notice">{--MEMBER_NO_CATEGORIES--}</option>';
1764 // Add bonus mail to queue
1765 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1766 // Is admin or bonus extension there?
1770 } elseif (!isExtensionActive('bonus')) {
1775 // Calculcate target sent
1776 $target = countSelection(explode(';', $receiverList));
1778 // Receiver is zero?
1779 if ($receiver == '0') {
1781 $receiver = $target;
1784 // HTML extension active?
1785 if (isExtensionActive('html_mail')) {
1786 // Determine if we have HTML mode active
1787 $HTML = convertBooleanToYesNo($mode == 'html');
1790 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1791 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1792 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s,'%s')",
1798 bigintval($seconds),
1800 bigintval($categoryId),
1802 bigintval($receiver),
1804 ), __FUNCTION__, __LINE__);
1807 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1808 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1809 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s)",
1815 bigintval($seconds),
1817 bigintval($categoryId),
1819 bigintval($receiver),
1820 ), __FUNCTION__, __LINE__);
1824 // Generate a receiver list for given category and maximum receivers
1825 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1833 $categoryId = bigintval($categoryId);
1834 $receiver = bigintval($receiver);
1836 // Is the receiver zero and mode set?
1837 if (($receiver == '0') && (!empty($mode))) {
1838 // Auto-fix receiver maximum
1839 $receiver = getTotalReceivers($mode);
1843 if ($categoryId > 0) {
1845 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1846 $CAT_WHERE = sprintf(" AND c.`cat_id`=%s", $categoryId);
1849 // Exclude users in holiday?
1850 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1851 // Add something for the holiday extension
1852 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1855 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1856 // Only include HTML receivers
1857 $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",
1860 ), __FUNCTION__, __LINE__);
1863 $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",
1866 ), __FUNCTION__, __LINE__);
1870 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1872 while ($content = SQL_FETCHARRAY($result)) {
1873 // Add receiver when not empty
1874 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1878 SQL_FREERESULT($result);
1880 // Remove trailing semicolon
1881 $receiverList = substr($receiverList, 0, -1);
1885 return $receiverList;
1888 // "Getter" for array for user refs and points in given level
1889 function getUserReferalPoints ($userid, $level) {
1890 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">'.__FUNCTION__.' - ENTRY</font> ------------------------<ul><li>');
1891 // Default is no refs and no nickname
1894 // Get refs from database
1895 $result = SQL_QUERY_ESC("SELECT
1896 ur.`id`, ur.`refid`, ud.`status`, ud.`last_online`, ud.`mails_confirmed`, ud.`emails_received`
1898 `{?_MYSQL_PREFIX?}_user_refs` AS ur
1900 `{?_MYSQL_PREFIX?}_user_points` AS up
1902 ur.refid=up.userid AND
1903 (ur.level=0 OR ur.level IS NULL)
1905 `{?_MYSQL_PREFIX?}_user_data` AS ud
1907 ur.`refid`=ud.`userid`
1916 ), __FUNCTION__, __LINE__);
1918 // Are there some entries?
1919 if (!SQL_HASZERONUMS($result)) {
1920 // Fetch all entries
1921 while ($row = SQL_FETCHARRAY($result)) {
1922 // Get total points of this user
1923 $row['points'] = getTotalPoints($row['refid']);
1925 // Get unconfirmed mails
1926 $row['unconfirmed'] = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
1928 // Init clickrate with zero
1929 $row['clickrate'] = '0';
1931 // Is at least one mail received?
1932 if ($row['emails_received'] > 0) {
1933 // Calculate clickrate
1934 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
1937 // Activity is 'active' by default because if autopurge is not installed
1938 $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
1940 // Is autopurge installed and the user inactive?
1941 if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online'])) {
1943 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
1946 // Remove some entries
1947 unset($row['mails_confirmed']);
1948 unset($row['emails_received']);
1949 unset($row['last_online']);
1952 $refs[$row['id']] = $row;
1957 SQL_FREERESULT($result);
1960 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
1964 // Recuce the amount of received emails for the receipients for given email
1965 function reduceRecipientReceivedMails ($column, $id, $count) {
1966 // Search for mail in database
1967 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1968 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1970 // Are there entries?
1971 if (!SQL_HASZERONUMS($result)) {
1972 // Now load all userids for one big query!
1974 while ($data = SQL_FETCHARRAY($result)) {
1975 // By default we want to reduce and have no mails found
1978 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1979 // @TODO Rewrite this to a filter
1980 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1982 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1983 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1985 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1988 // Reduce this users total received emails?
1989 if ($num === 0) $userids[$data['userid']] = $data['userid'];
1992 if (count($userids) > 0) {
1993 // Now update all user accounts
1994 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1995 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1998 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
2003 SQL_FREERESULT($result);
2006 // Creates a new task
2007 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
2008 // Insert the task data into the database
2009 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())",
2016 ), __FUNCTION__, __LINE__, true, $strip);
2018 // Return insert id which is the task id
2019 return SQL_INSERTID();
2022 // Updates last module / online time
2023 // @TODO Fix inconsistency between last_module and getWhat()
2024 function updateLastActivity($userid) {
2025 // Run the update query
2026 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
2031 ), __FUNCTION__, __LINE__);
2034 // Get points data for given extension's name
2035 function getPointsDataArrayFromExtensionName ($ext_name) {
2036 // If we have cache, shortcut it here
2037 if (isset($GLOBALS['cache_array']['points_data'][$ext_name])) {
2039 return $GLOBALS['cache_array']['points_data'][$ext_name];
2042 // Now checkout the entry in database table
2043 $result = SQL_QUERY_ESC("SELECT `id`, `ext_name`, `column_name`, `locked_mode`, `payment_method` FROM `{?_MYSQL_PREFIX?}_points_data` WHERE `ext_name`='%s' LIMIT 1",
2044 array($ext_name), __FUNCTION__, __LINE__);
2046 // Do we have an entry?
2047 if (SQL_NUMROWS($result) == 1) {
2049 $pointsData = SQL_FETCHARRAY($result);
2051 // Add all remaining entries
2052 foreach ($pointsData as $key=>$value) {
2053 $GLOBALS['cache_array']['points_data'][$ext_name][$key] = $value;
2057 * Having no entry is not bad but it means that all points will go to
2058 * the general account which the user can let payout.
2060 logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ' - No entry found, switching to general points account.');
2064 SQL_FREERESULT($result);
2067 return $GLOBALS['cache_array']['points_data'][$ext_name];
2070 // Determines the right points column name for given extension and 'locked'
2071 function getPointsColumnNameFromExtensionNameLocked ($ext_name, $isLocked) {
2072 // Extension sql_patches must be up-to-date
2073 if (isExtensionInstalledAndOlder('sql_patches', '0.8.0')) {
2074 // Please update ext-sql_patches
2075 debug_report_bug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.0 to continue. ext_name=' . $ext_name . ',isLocked=' . intval($isLocked));
2078 // Get the points_data entry
2079 $pointsData = getPointsDataArrayFromExtensionName($ext_name);
2081 // Regular points by default
2082 $columnName = $pointsData['column_name'];
2084 // Are the points locked?
2085 if (($isLocked === true) && ($pointsData['locked_mode'] == 'LOCKED')) {
2086 // Locked points, so prefix it
2087 $columnName = 'locked_' . $pointsData['column_name'];
2090 // Return the result
2094 // Determines the payment method for given extension and 'locked'
2095 function getPaymentMethodFromExtensionName ($ext_name) {
2096 // Extension sql_patches must be up-to-date
2097 if (isExtensionInstalledAndOlder('sql_patches', '0.8.0')) {
2098 // Please update ext-sql_patches
2099 debug_report_bug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.0 to continue. ext_name=' . $ext_name . ',isLocked=' . intval($isLocked));
2102 // Get the points_data entry
2103 $pointsData = getPointsDataArrayFromExtensionName($ext_name);
2105 // Regular points by default
2106 $paymentMethod = $pointsData['payment_method'];
2108 // Return the result
2109 return $paymentMethod;