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 - 2012 by Mailer Developer Team *
20 * For more information visit: http://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 = '') {
47 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',what=' . $what . ',column=' . $column . ',add=' . $ADD);
51 $what = getIndexHome();
52 } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
54 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
55 } elseif ($what == 'welcome') {
57 return '{--WHAT_IS_WELCOME--}';
60 // Default is not found
61 $data['title'] = '??? (' . $what . ')';
64 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
69 ), __FUNCTION__, __LINE__);
72 if (SQL_NUMROWS($result) == 1) {
74 $data = SQL_FETCHARRAY($result);
78 SQL_FREERESULT($result);
81 return $data['title'];
84 // Add link into output stream (or return it) for 'You Are Here' navigation
85 function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
86 // Use only filename of the FQFN...
87 $file = basename($FQFN);
95 // First we have to do some analysis...
96 if (substr($file, 0, 7) == 'action-') {
97 // This is an action file!
99 $search = substr($file, 7);
101 // Get access level from it
102 $modCheck = getModuleFromFileName($file, $accessLevel);
105 $ADD = " AND (`what`='' OR `what` IS NULL)";
106 } elseif (substr($file, 0, 5) == 'what-') {
107 // This is a 'what file'!
109 $search = substr($file, 5);
111 // Get access level from it
112 $modCheck = getModuleFromFileName($file, $accessLevel);
114 // Do we have admin? Then display all
115 $ADD = " AND `visible`='Y' AND `locked`='N'";
121 $dummy = substr($search, 0, -4);
122 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
123 } elseif ($accessLevel == 'sponsor') {
127 $modCheck = getModule();
133 $modCheck = getModule();
137 // Begin the navigation line
138 if (!isset($GLOBALS['nav_depth'])) {
140 $GLOBALS['nav_depth'] = '0';
142 // Run the pre-filter chain
143 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => '', 'add' => $ADD));
146 $prefix = $ret['content'];
148 // Add default content
149 $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>';
150 } elseif ($return === false) {
152 $GLOBALS['nav_depth']++;
155 $prefix .= ' -> ';
157 // We need to remove .php and the end
158 if (substr($search, -4, 4) == '.php') {
160 $search = substr($search, 0, -4);
163 // Is ext-sql_patches installed?
164 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isExtensionInstalledAndNewer()=' . intval(isExtensionInstalledAndNewer('sql_patches', '0.2.3')) . ',youre_here=' . getConfig('youre_here') . ',isAdmin()=' . intval(isAdmin()) . ',modCheck=' . $modCheck);
165 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
167 $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>';
169 // Can we close the you-are-here navigation?
170 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',getWhat()=' . getWhat() . ',isWhatSet()=' . intval(isWhatSet()));
171 if (($type == 'what') || (($type == 'action') && (!isWhatSet()))) {
172 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
173 // Add closing div and br-tag
174 $GLOBALS['nav_depth'] = '0';
176 // Run the post-filter chain
177 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => $OUT, 'add' => $ADD));
179 // Get content from filter back
180 $OUT = $ret['content'];
182 // Close div-tag, so not the filters have to do it
187 // Return or output HTML code?
188 if ($return === true) {
192 // Output HTML code here
197 // Adds a menu (mode = guest/member/admin/sponsor) to output
198 function addMenu ($mode, $action, $what) {
199 // Init some variables
202 // is the menu action valid?
203 if (!isMenuActionValid($mode, $action, $what, true)) {
204 return getCode('MENU_NOT_VALID');
207 // Non-admin shall not see all menus
208 $ADD = " AND `visible`='Y' AND `locked`='N'";
210 // Is admin, so make all visible
214 // Load SQL data and add the menu to the output stream...
215 $result_main = SQL_QUERY_ESC("SELECT
216 `title`,`what`,`action`,`visible`,`locked`
218 `{?_MYSQL_PREFIX?}_%s_menu`
220 (`what`='' OR `what` IS NULL)
224 array($mode), __FUNCTION__, __LINE__);
226 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
227 if (!SQL_HASZERONUMS($result_main)) {
228 // There are menus available, so we simply display them... :)
229 $GLOBALS['rows'] = '';
230 while ($content = SQL_FETCHARRAY($result_main)) {
231 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
232 // Disable the block-mode
233 enableBlockMode(false);
235 // Load menu header template
236 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
239 $result_sub = SQL_QUERY_ESC("SELECT
240 `title` AS `sub_title`,
241 `what` AS `sub_what`,
242 `visible` AS `sub_visible`,
243 `locked` AS `sub_locked`
245 `{?_MYSQL_PREFIX?}_%s_menu`
253 array($mode, $content['action']), __FUNCTION__, __LINE__);
255 // Do we have some entries?
256 if (!SQL_HASZERONUMS($result_sub)) {
260 // Load all sub menus
261 while ($content2 = SQL_FETCHARRAY($result_sub)) {
262 // Merge both arrays in one
263 $content = merge_array($content, $content2);
268 // Full file name for checking menu
269 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
270 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
271 if (isIncludeReadable($inc)) {
272 // Mark currently selected menu - open
273 if ((!empty($what)) && (($what == $content['sub_what']))) {
277 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
278 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
279 // Use index.php as link
280 $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
282 // Regular navigation link
283 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
287 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
291 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
293 if (isIncludeReadable($inc)) {
296 // Mark currently selected menu - close
297 if ((!empty($what)) && (($what == $content['sub_what']))) {
311 'what' => $content['sub_what'],
312 'visible' => $content['sub_visible'],
313 'locked' => $content['locked'],
316 // Add regular menu row or bottom row?
317 if ($count < SQL_NUMROWS($result_sub)) {
318 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
320 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
324 // This is a menu block... ;-)
328 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
329 if (isFileReadable($INC)) {
331 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
335 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
337 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
341 SQL_FREERESULT($result_sub);
346 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
347 if (SQL_NUMROWS($result_main) > $main_cnt) {
349 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
351 // Should we display adverts in this menu?
352 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
353 // Display advert template
354 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
356 // Add separator again
357 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
363 SQL_FREERESULT($result_main);
365 // Should we display adverts in this menu?
366 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
367 // Add separator again
368 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
370 // Display advert template
371 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
376 'rows' => $GLOBALS['rows'],
380 // Load main template
381 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
382 loadTemplate('menu_table', false, $content);
386 // Checks whether the current user is a member
387 function isMember () {
388 // By default no member
391 // Fix missing 'last_online' array, damn stupid code :(((
392 // @TODO Try to rewrite this to one or more functions
393 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
394 $GLOBALS['last_online'] = array();
397 // Is the cache entry there?
398 if (isset($GLOBALS[__FUNCTION__])) {
400 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
401 return $GLOBALS[__FUNCTION__];
402 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
403 // Destroy any existing user session data
404 destroyMemberSession();
405 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
407 // Abort further processing
411 // Get userid secured from session
412 setMemberId(getSession('userid'));
414 // ... and set it as currently handled user id
415 setCurrentUserId(getMemberId());
417 // Init user data array
420 // Fix "deleted" cookies first
421 fixDeletedCookies(array('userid', 'u_hash'));
423 // Are cookies set and can the member data be loaded?
424 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
425 // Validate password by created the difference of it and the secret key
426 $valPass = encodeHashForCookie(getUserData('password'));
428 // So did we now have valid data and an unlocked user?
429 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
430 // Transfer last module and online time
431 $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
432 $GLOBALS['last_online']['online'] = getUserData('last_online');
434 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
439 // Is $ret still false?
440 if ($ret === false) {
441 // Yes, so destroy the session
442 destroyMemberSession();
446 $GLOBALS[__FUNCTION__] = $ret;
449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
453 // Fetch user data for given user id
454 function fetchUserData ($value, $column = 'userid') {
455 // Extension ext-user must be there at any case
456 if (!isExtensionActive('user')) {
457 // Absent ext-user is really not good
459 } elseif (is_null($value)) {
460 // This shall never happen, so please report it
461 reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
464 // If we should look for userid secure&set it here
465 if (substr($column, -2, 2) == 'id') {
467 $value = bigintval($value);
469 // Don't look for invalid userids...
470 if (!isValidUserId($value)) {
471 // Invalid, so abort here
472 reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
473 } elseif (isUserDataValid()) {
474 // Use cache, so it is fine
475 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
478 } elseif (isUserDataValid()) {
479 // Using cache is fine
480 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
484 // By default none was found
487 // Extra SQL statements
488 $ADD = runFilterChain('convert_user_data_columns', '');
490 // Query for the user
491 $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
492 array($column, $value), __FUNCTION__, __LINE__);
494 // Do we have a record?
495 if (SQL_NUMROWS($result) == 1) {
496 // Load data from cookies
497 $data = SQL_FETCHARRAY($result);
499 // Set the userid for later use
500 setCurrentUserId($data['userid']);
502 // And cache the data for this userid
503 $GLOBALS['user_data'][getCurrentUserId()] = $data;
505 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
506 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
507 // Backup the raw one and zero it
508 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
509 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
512 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
513 // Seperate data/time
514 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
516 // Seperate data and time again
517 $array['date'] = explode('-', $array[0]);
518 $array['time'] = explode(':', $array[1]);
520 // Now pass it to mktime()
521 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
533 $found = isUserDataValid();
537 SQL_FREERESULT($result);
544 * Checks whether the current session bears a valid admin id and password hash.
546 * This patched function will reduce many SELECT queries for the current admin
549 function isAdmin () {
550 // No admin in installation phase!
551 if ((isInstallationPhase()) || (!isAdminRegistered())) {
558 $passwordFromCookie = '';
560 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
562 // If admin login is not given take current from cookies...
563 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
564 // Get admin login and password from session/cookies
565 $adminId = getCurrentAdminId();
566 $passwordFromCookie = getAdminMd5();
568 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . 'passwordFromCookie=' . $passwordFromCookie);
570 // Abort if admin id is zero
571 if ($adminId == '0') {
572 // A very noisy debug message ...
573 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
580 if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
581 // Init it with failed
582 $GLOBALS[__FUNCTION__][$adminId] = false;
584 // Search in array for entry
585 if (isset($GLOBALS['admin_hash'])) {
587 $valPass = $GLOBALS['admin_hash'];
588 } elseif ((!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
589 // Login data is valid or not?
590 $valPass = encodeHashForCookie(getAdminHash($adminId));
593 $GLOBALS['admin_hash'] = $valPass;
596 incrementStatsEntry('cache_hits');
597 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
598 // Get admin hash and hash it
599 $valPass = encodeHashForCookie(getAdminHash($adminId));
602 $GLOBALS['admin_hash'] = $valPass;
605 if (!empty($valPass)) {
606 // Check if password is valid
607 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passwordFromCookie . ')='.intval($valPass == $passwordFromCookie));
608 $GLOBALS[__FUNCTION__][$adminId] = ($GLOBALS['admin_hash'] == $passwordFromCookie);
612 // Return result of comparision
613 return $GLOBALS[__FUNCTION__][$adminId];
616 // Generates a list of "max receiveable emails per day"
617 function addMaxReceiveList ($mode, $default = '', $return = false) {
623 // Guests (in the registration form) are not allowed to select 0 mails per day.
624 $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
625 __FUNCTION__, __LINE__);
630 // Members are allowed to set to zero mails per day (we will change this soon!)
631 $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
632 __FUNCTION__, __LINE__);
636 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
640 // Some entries are found?
641 if (!SQL_HASZERONUMS($result)) {
643 while ($content = SQL_FETCHARRAY($result)) {
644 $OUT .= ' <option value="' . $content['value'] . '"';
646 if (postRequestElement('max_mails') == $content['value']) {
647 $OUT .= ' selected="selected"';
650 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
651 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
656 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
658 // Maybe the admin has to setup some maximum values?
659 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
663 SQL_FREERESULT($result);
665 if ($return === true) {
666 // Return generated HTML code
669 // Output directly (default)
674 // Checks whether the given email address is used.
675 function isEmailTaken ($email) {
676 // Default is no userid
677 $useridSql = ' IS NOT NULL';
679 // Is a member logged in?
682 $useridSql = '!= ' . bigintval(getMemberId());
685 // Replace dot with {DOT}
686 $email = str_replace('.', '{DOT}', $email);
688 // Query the database
689 $result = SQL_QUERY_ESC("SELECT
690 COUNT(`userid`) AS `cnt`
692 `{?_MYSQL_PREFIX?}_user_data`
694 '%s' REGEXP `email` AND
700 ), __FUNCTION__, __LINE__);
702 // Is the email there?
703 list($count) = SQL_FETCHROW($result);
706 SQL_FREERESULT($result);
709 return ($count == 1);
712 // Validate the given menu action
713 function isMenuActionValid ($mode, $action, $what, $updateEntry = false) {
714 // Is the cache entry there and we shall not update?
715 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
717 incrementStatsEntry('cache_hits');
719 // Then use this cache
720 return $GLOBALS['action_valid'][$mode][$action][$what];
723 // By default nothing is valid
726 // Look in all menus or only unlocked
728 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
730 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
731 if (($mode != 'admin') && ($updateEntry === true)) {
732 // Update guest or member menu
733 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
738 ), __FUNCTION__, __LINE__, false);
739 } elseif (($what != 'welcome') && (!empty($what))) {
741 $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",
746 ), __FUNCTION__, __LINE__, false);
748 // Admin login overview
749 $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",
753 ), __FUNCTION__, __LINE__, false);
757 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
759 // Should we look for affected rows (only update) or found rows?
760 if ($updateEntry === true) {
761 // Check updated/affected rows
762 $ret = (!SQL_HASZEROAFFECTED());
765 $ret = (!SQL_HASZERONUMS($result));
769 SQL_FREERESULT($result);
772 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
778 // Get action value from mode (admin/guest/member) and what-value
779 function getActionFromModuleWhat ($module, $what) {
780 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
782 $data['action'] = '';
784 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
785 // sql_patches is missing so choose depending on mode
786 $what = determineWhat($module);
787 } elseif ((empty($what)) && ($module != 'admin')) {
788 // Use configured 'home'
789 $what = getIndexHome();
792 if ($module == 'admin') {
793 // Action value for admin area
794 if (isGetRequestElementSet('action')) {
796 return getRequestElement('action');
797 } elseif (isActionSet()) {
798 // Get it directly from URL
800 } elseif (($what == 'welcome') || (!isWhatSet())) {
801 // Default value for admin area
802 $data['action'] = 'login';
804 } elseif (isActionSet()) {
805 // Get it directly from URL
808 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
810 // Does the module have a menu?
811 if (ifModuleHasMenu($module)) {
812 // Rewriting modules to menu
813 $module = mapModuleToTable($module);
815 // Guest and member menu is 'main' as the default
816 if (empty($data['action'])) {
817 $data['action'] = 'main';
820 // Load from database
821 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
825 ), __FUNCTION__, __LINE__);
826 if (SQL_NUMROWS($result) == 1) {
827 // Load action value and pray that this one is the right you want... ;-)
828 $data = SQL_FETCHARRAY($result);
832 SQL_FREERESULT($result);
833 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
834 // No sql_patches installed, but maybe we need to register an admin?
835 if (isAdminRegistered()) {
836 // Redirect to admin area
837 redirectToUrl('admin.php');
841 // Return action value
842 return $data['action'];
845 // Get category name back
846 function getCategory ($cid) {
847 // Default is not found
848 $data['cat'] = '{--_CATEGORY_404--}';
850 // Is the category id set?
853 $data['cat'] = '{--_CATEGORY_NONE--}';
854 } elseif ($cid > 0) {
855 // Lookup the category in database
856 $result = SQL_QUERY_ESC('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
857 array(bigintval($cid)), __FUNCTION__, __LINE__);
858 if (SQL_NUMROWS($result) == 1) {
859 // Category found... :-)
860 $data = SQL_FETCHARRAY($result);
864 SQL_FREERESULT($result);
871 // Get a string of "mail title" and price back
872 function getPaymentTitlePrice ($paymentsId, $full = false) {
873 // Only title or also including price?
874 if ($full === false) {
875 $ret = getPaymentData($paymentsId, 'main_title');
877 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
884 // "Getter" for payment data (cached)
885 function getPaymentData ($paymentsId, $lookFor = 'price') {
887 $data[$lookFor] = NULL;
890 if (isset($GLOBALS['cache_array']['payments'][$paymentsId]['id'])) {
891 // Use it if found to save SQL queries
892 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$paymentsId];
895 incrementStatsEntry('cache_hits');
896 } elseif (!isExtensionActive('cache')) {
897 // Search for it in database
898 $result = SQL_QUERY_ESC('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
901 bigintval($paymentsId)
902 ), __FUNCTION__, __LINE__);
904 // Is the entry there?
905 if (SQL_NUMROWS($result) == 1) {
906 // Payment type found... :-)
907 $data = SQL_FETCHARRAY($result);
911 SQL_FREERESULT($result);
915 return $data[$lookFor];
918 // Remove a receiver's id from $receivers and add a link for him to confirm
919 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = false) {
920 // Default is not removed
923 // Is the userid valid?
924 if (isValidUserId($userid)) {
925 // Remove entry from array
926 unset($receivers[$key]);
928 // Is there already a line for this user available?
930 // Default is 'normal' mail
932 $rowName = 'stats_id';
934 // Only when we got a real stats id continue searching for the entry
935 if ($isBonusMail === true) {
937 $rowName = 'bonus_id';
940 // Try to look the entry up
941 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
947 ), __FUNCTION__, __LINE__);
949 // Was it *not* found?
950 if (SQL_HASZERONUMS($result)) {
952 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES (%s,%s,'%s')",
958 ), __FUNCTION__, __LINE__);
960 // Update 'mails_sent' if sql_patches is updated
961 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
963 SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1',
964 array(bigintval($poolId)), __FUNCTION__, __LINE__);
973 SQL_FREERESULT($result);
977 // Return status for sending routine
981 // Calculate sum (default) or count records of given criteria
982 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '', $mode = '=') {
986 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
987 if ((empty($search)) && ($search != '0')) {
988 // Count or sum whole table?
989 if ($countRows === true) {
991 $result = SQL_QUERY_ESC('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
995 ), __FUNCTION__, __LINE__);
998 $result = SQL_QUERY_ESC('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1002 ), __FUNCTION__, __LINE__);
1004 } elseif (($countRows === true) || ($lookFor == 'userid')) {
1006 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1007 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1014 ), __FUNCTION__, __LINE__);
1017 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1018 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1025 ), __FUNCTION__, __LINE__);
1029 $data = SQL_FETCHARRAY($result);
1032 SQL_FREERESULT($result);
1035 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1037 $data['res'] = '0.00000';
1038 } elseif (''.$data['res'].'' == '') {
1044 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1045 return $data['res'];
1049 * Sends out mail to all administrators. This function is no longer obsolete
1050 * because we need it when there is no ext-admins installed
1052 function sendAdminEmails ($subject, $message, $isBugReport = false) {
1053 // Default is no special header
1056 // Is it a bug report?
1057 if ($isBugReport === true) {
1058 // Then add a reply-to line back to the author (me)
1059 $mailHeader = 'Reply-To: webmaster@mxchange.org' . chr(10);
1062 // Load all admin email addresses
1063 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1065 // And send the notification to all of them
1066 while ($content = SQL_FETCHARRAY($result)) {
1067 // Send the email out
1068 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1072 SQL_FREERESULT($result);
1074 // Really simple... ;-)
1077 // Get id number from administrator's login name
1078 function getAdminId ($adminLogin) {
1079 // By default no admin is found
1083 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1084 // Use it if found to save SQL queries
1085 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1087 // Update cache hits
1088 incrementStatsEntry('cache_hits');
1089 } elseif (!isExtensionActive('cache')) {
1090 // Load from database
1091 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1092 array($adminLogin), __FUNCTION__, __LINE__);
1094 // Do we have an entry?
1095 if (SQL_NUMROWS($result) == 1) {
1097 $data = SQL_FETCHARRAY($result);
1101 SQL_FREERESULT($result);
1108 // "Getter" for current admin id
1109 function getCurrentAdminId () {
1110 // Log debug message
1111 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1113 // Do we have cache?
1114 if (!isset($GLOBALS['current_admin_id'])) {
1115 // Get the admin login from session
1116 $adminId = getSession('admin_id');
1118 // Remember in cache securely
1119 setCurrentAdminId(bigintval($adminId));
1123 return $GLOBALS['current_admin_id'];
1126 // Setter for current admin id
1127 function setCurrentAdminId ($currentAdminId) {
1129 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1132 // Get password hash from administrator's login name
1133 function getAdminHash ($adminId) {
1134 // By default an invalid hash is returned
1135 $data['password'] = -1;
1137 if (isAdminHashSet($adminId)) {
1139 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1141 // Update cache hits
1142 incrementStatsEntry('cache_hits');
1143 } elseif (!isExtensionActive('cache')) {
1144 // Load from database
1145 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1146 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1148 // Do we have an entry?
1149 if (SQL_NUMROWS($result) == 1) {
1151 $data = SQL_FETCHARRAY($result);
1154 setAdminHash($adminId, $data['password']);
1158 SQL_FREERESULT($result);
1161 // Return password hash
1162 return $data['password'];
1165 // "Getter" for admin login
1166 function getAdminLogin ($adminId) {
1167 // By default a non-existent login is returned (other functions react on this!)
1168 $data['login'] = '***';
1170 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1172 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1174 // Update cache hits
1175 incrementStatsEntry('cache_hits');
1176 } elseif (!isExtensionActive('cache')) {
1177 // Load from database
1178 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1179 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1182 if (SQL_NUMROWS($result) == 1) {
1184 $data = SQL_FETCHARRAY($result);
1187 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1191 SQL_FREERESULT($result);
1194 // Return the result
1195 return $data['login'];
1198 // Get email address of admin id
1199 function getAdminEmail ($adminId) {
1200 // By default an invalid emails is returned
1201 $data['email'] = '***';
1203 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1205 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1207 // Update cache hits
1208 incrementStatsEntry('cache_hits');
1209 } elseif (!isExtensionActive('cache')) {
1210 // Load from database
1211 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1212 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1215 if (SQL_NUMROWS($result_admin_id) == 1) {
1217 $data = SQL_FETCHARRAY($result_admin_id);
1220 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1224 SQL_FREERESULT($result_admin_id);
1228 return $data['email'];
1231 // Get default ACL of admin id
1232 function getAdminDefaultAcl ($adminId) {
1233 // By default an invalid ACL value is returned
1234 $data['default_acl'] = 'NO-ACL';
1236 // Is sql_patches there and was it found in cache?
1237 if (!isExtensionActive('sql_patches')) {
1238 // Not found, which is bad, so we need to allow all
1239 $data['default_acl'] = 'allow';
1240 } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1242 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1244 // Update cache hits
1245 incrementStatsEntry('cache_hits');
1246 } elseif (!isExtensionActive('cache')) {
1247 // Load from database
1248 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1249 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1251 // Do we have an entry?
1252 if (SQL_NUMROWS($result_admin_id) == 1) {
1254 $data = SQL_FETCHARRAY($result_admin_id);
1257 $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1261 SQL_FREERESULT($result_admin_id);
1264 // Return default ACL
1265 return $data['default_acl'];
1268 // Get menu mode (la_mode) of admin id
1269 function getAdminMenuMode ($adminId) {
1270 // By default an invalid mode
1271 $data['la_mode'] = 'INVALID';
1273 // Is sql_patches there and was it found in cache?
1274 if (!isExtensionActive('sql_patches')) {
1275 // Not found, which is bad, so we need to allow all
1276 $data['la_mode'] = 'global';
1277 } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1279 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1281 // Update cache hits
1282 incrementStatsEntry('cache_hits');
1283 } elseif (!isExtensionActive('cache')) {
1284 // Load from database
1285 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1286 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1288 // Do we have an entry?
1289 if (SQL_NUMROWS($result_admin_id) == 1) {
1291 $data = SQL_FETCHARRAY($result_admin_id);
1294 $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1298 SQL_FREERESULT($result_admin_id);
1301 // Return default ACL
1302 return $data['la_mode'];
1305 // Generates an option list from various parameters
1306 function generateOptions ($table, $id, $name, $default = '', $special = '', $whereStatement = '', $disabled = array(), $callback = '') {
1308 if ($table == '/ARRAY/') {
1309 // Selection from array
1310 if ((is_array($id)) && (is_array($name)) && ((count($id)) == (count($name)) || (!empty($callback)))) {
1312 foreach ($id as $idx => $value) {
1313 $ret .= '<option value="' . $value . '"';
1314 if ($default == $value) {
1315 // Selected by default
1316 $ret .= ' selected="selected"';
1317 } elseif (isset($disabled[$value])) {
1319 $ret .= ' disabled="disabled"';
1322 // Is the call-back function set?
1323 if (!empty($callback)) {
1325 $name[$idx] = call_user_func_array($callback, array($id[$idx]));
1328 // Finish option tag
1329 $ret .= '>' . $name[$idx] . '</option>';
1332 // Problem in request
1333 reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
1336 // Data from database
1337 $SPEC = ',`' . $id . '`';
1338 if (!empty($special)) {
1339 $SPEC = ',`' . $special . '` AS `special`';
1342 // Query the database
1343 $result = SQL_QUERY_ESC("SELECT `%s` AS `id`,`%s` AS `name`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$whereStatement." ORDER BY `%s` ASC",
1349 ), __FUNCTION__, __LINE__);
1352 if (!SQL_HASZERONUMS($result)) {
1353 // Found data so add them as OPTION lines
1354 while ($content = SQL_FETCHARRAY($result)) {
1356 if (!isset($content['special'])) {
1358 $content['special'] = '';
1361 $ret .= '<option value="' . $content['id'] . '"';
1363 if ($default == $content['id']) {
1364 // Selected by default
1365 $ret .= ' selected="selected"';
1366 } elseif (isset($disabled[$content['id']])) {
1368 $ret .= ' disabled="disabled"';
1372 if (!empty($content['special'])) {
1373 $content['special'] = ' (' . $content['special'] . ')';
1376 // Is the call-back function set?
1377 if (!empty($callback)) {
1379 $content['name'] = call_user_func_array($callback, array($content['name']));
1382 // Finish option list
1383 $ret .= '>' . $content['name'] . $content['special'] . '</option>';
1387 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1391 SQL_FREERESULT($result);
1394 // Return - hopefully - the requested data
1398 // Deletes a user account with given reason
1399 function deleteUserAccount ($userid, $reason) {
1401 $data['points'] = '0';
1403 // Search for the points and user data
1404 $result = SQL_QUERY_ESC("SELECT
1405 (SUM(p.`points`) - d.`used_points`) AS `points`
1407 `{?_MYSQL_PREFIX?}_user_points` AS p
1409 `{?_MYSQL_PREFIX?}_user_data` AS d
1411 p.`userid`=d.`userid`
1415 array(bigintval($userid)), __FUNCTION__, __LINE__);
1417 // Do we have an entry?
1418 if (SQL_NUMROWS($result) == 1) {
1419 // Save his points to add them to the jackpot
1420 $data = SQL_FETCHARRAY($result);
1422 // Delete points entries as well
1423 // @TODO Rewrite these lines to a filter
1424 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1425 array(bigintval($userid)), __FUNCTION__, __LINE__);
1427 // Update mediadata as well
1428 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1430 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1433 // Now, when we have all his points adds them do the jackpot!
1434 if (isExtensionActive('jackpot')) {
1435 addPointsToJackpot($data['points']);
1440 SQL_FREERESULT($result);
1442 // Delete category selections as well...
1443 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1444 array(bigintval($userid)), __FUNCTION__, __LINE__);
1446 // Remove from rallye if found
1447 // @TODO Rewrite this to a filter
1448 if (isExtensionActive('rallye')) {
1449 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1450 array(bigintval($userid)), __FUNCTION__, __LINE__);
1453 // Add reason and translate points
1454 $data['text'] = $reason;
1456 // Now a mail to the user and that's all...
1457 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1458 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1460 // Ok, delete the account!
1461 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1464 // Gets the matching what name from module
1465 function getWhatFromModule ($modCheck) {
1466 // Is the request element set?
1467 if (isGetRequestElementSet('what')) {
1468 // Then return this!
1469 return getRequestElement('what');
1475 // Check on given module
1476 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1477 switch ($modCheck) {
1478 case 'index': // Guest area
1479 // Is ext-sql_patches installed and newer than 0.0.5?
1480 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1481 // Use it from config
1482 $what = getIndexHome();
1484 // Use default 'welcome'
1489 default: // Default for all other menus (getIndexHome() is for index module only)
1494 // Return what value
1498 // Returns HTML code with an option list of all categories
1499 function generateCategoryOptionsList ($mode, $userid = NULL) {
1500 // Prepare WHERE statement
1501 $whereStatement = " WHERE `visible`='Y'";
1502 if (isAdmin()) $whereStatement = '';
1504 // Initialize array...
1505 $categories = array(
1508 'userids' => array()
1512 $result = SQL_QUERY('SELECT `id`,`cat` FROM `{?_MYSQL_PREFIX?}_cats`' . $whereStatement . ' ORDER BY `sort` ASC',
1513 __FUNCTION__, __LINE__);
1515 // Do we have entries?
1516 if (!SQL_HASZERONUMS($result)) {
1517 // ... and begin loading stuff
1518 while ($content = SQL_FETCHARRAY($result)) {
1519 // Transfer some data
1520 $categories['id'][] = $content['id'];
1521 array_push($categories['name'], $content['cat']);
1523 // Check which users are in this category
1524 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1526 bigintval($content['id']),
1527 convertNullToZero($userid)
1528 ), __FUNCTION__, __LINE__);
1534 while ($data = SQL_FETCHARRAY($result_userids)) {
1536 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1540 SQL_FREERESULT($result_userids);
1543 array_push($categories['userids'], $userid_cnt);
1547 SQL_FREERESULT($result);
1551 foreach ($categories['id'] as $key => $value) {
1552 $OUT .= ' <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1555 // No cateogries are defined yet
1556 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1563 // Add bonus mail to queue
1564 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1565 // Is admin or bonus extension there?
1569 } elseif (!isExtensionActive('bonus')) {
1574 // Calculcate target sent
1575 $target = countSelection(explode(';', $receiverList));
1577 // Receiver is zero?
1578 if ($receiver == '0') {
1580 $receiver = $target;
1583 // HTML extension active?
1584 if (isExtensionActive('html_mail')) {
1585 // Determine if we have HTML mode active
1586 $HTML = convertBooleanToYesNo($mode == 'html');
1589 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1590 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`,`html_msg`)
1591 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s,'%s')",
1597 bigintval($seconds),
1599 bigintval($categoryId),
1601 bigintval($receiver),
1603 ), __FUNCTION__, __LINE__);
1606 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1607 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`)
1608 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s)",
1614 bigintval($seconds),
1616 bigintval($categoryId),
1618 bigintval($receiver),
1619 ), __FUNCTION__, __LINE__);
1623 // Generate a receiver list for given category and maximum receivers
1624 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1631 $categoryId = bigintval($categoryId);
1632 $receiver = bigintval($receiver);
1634 // Is the receiver zero and mode set?
1635 if (($receiver == '0') && (!empty($mode))) {
1636 // Auto-fix receiver maximum
1637 $receiver = getTotalReceivers($mode);
1640 // Exclude (maybe exclude) testers
1641 $addWhere = runFilterChain('user_exclusion_sql', ' ');
1644 if ($categoryId > 0) {
1646 $extraColumns = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1647 $addWhere = sprintf(" AND c.`cat_id`=%s", $categoryId);
1650 // Exclude users in holiday?
1651 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1652 // Add something for the holiday extension
1653 $addWhere .= " AND d.`holiday_active`='N'";
1656 // Include only HTML recipients?
1657 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1658 $addWhere .= " AND d.`html`='Y'";
1662 $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$extraColumns." WHERE d.`status`='CONFIRMED' ".$addWhere." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1665 ), __FUNCTION__, __LINE__);
1668 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1670 while ($content = SQL_FETCHARRAY($result)) {
1671 // Add receiver when not empty
1672 if (!empty($content['userid'])) {
1673 $receiverList .= $content['userid'] . ';';
1678 SQL_FREERESULT($result);
1680 // Remove trailing semicolon
1681 $receiverList = substr($receiverList, 0, -1);
1685 return $receiverList;
1688 // Recuce the amount of received emails for the receipients for given email
1689 function reduceRecipientReceivedMails ($column, $id, $count) {
1690 // Search for mail in database
1691 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1692 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1694 // Are there entries?
1695 if (!SQL_HASZERONUMS($result)) {
1696 // Now load all userids for one big query!
1698 while ($data = SQL_FETCHARRAY($result)) {
1699 // By default we want to reduce and have no mails found
1702 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1703 // @TODO Rewrite this to a filter
1704 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1706 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1707 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1709 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1712 // Reduce this users total received emails?
1714 $userids[$data['userid']] = $data['userid'];
1718 if (count($userids) > 0) {
1719 // Now update all user accounts
1720 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1721 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1724 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1729 SQL_FREERESULT($result);
1732 // Creates a new task
1733 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = true) {
1734 // Insert the task data into the database
1735 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())",
1737 convertZeroToNull($adminId),
1738 convertZeroToNull($userid),
1742 ), __FUNCTION__, __LINE__, true, $strip);
1744 // Return insert id which is the task id
1745 return SQL_INSERTID();
1748 // Updates last module / online time
1749 function updateLastActivity($userid) {
1752 // Run the update query
1753 SQL_QUERY_ESC("UPDATE
1754 `{?_MYSQL_PREFIX?}_user_data`
1757 `last_online`=UNIX_TIMESTAMP(),
1763 getUserLastWhatName(),
1767 ), __FUNCTION__, __LINE__);
1769 // No what set, needs to be ignored (last_module is last_what)
1770 SQL_QUERY_ESC("UPDATE
1771 `{?_MYSQL_PREFIX?}_user_data`
1774 `last_online`=UNIX_TIMESTAMP(),
1780 getUserLastWhatName(),
1783 ), __FUNCTION__, __LINE__);
1788 * Checks if given subject is found and if not, adds an SQL query to the
1789 * extension registration queue.
1791 function registerExtensionPointsData ($subject, $columnName, $lockedMode, $paymentMethod) {
1792 // Default is old extension version
1795 // Is the extension equal or newer 0.8.9?
1796 if (((isInstallationPhase()) && ((getExtensionMode() == 'register') || (getExtensionMode() == 'update'))) || (isExtensionInstalledAndNewer('sql_patches', '0.8.9'))) {
1797 // Then add provider
1798 $add = " AND `account_provider`='EXTENSION'";
1801 // Is the 'subject' there?
1802 if (((!ifSqlTableExists('points_data')) && ((getExtensionMode() == 'register') || (getExtensionMode() == 'update'))) || (countSumTotalData($subject, 'points_data', 'id', 'subject', true, $add) == 0)) {
1804 if (isset($GLOBALS['previous_extension'][getCurrentExtensionName()])) {
1805 $dummy = $GLOBALS['previous_extension'][getCurrentExtensionName()];
1806 reportBug(__FUNCTION__, __LINE__, 'previous_extension[' . gettype($dummy) . ']=' . $dummy . ',getCurrentExtensionName()=' . getCurrentExtensionName() . ' - Under development, please report this!');
1809 // ... add an SQL query
1810 addExtensionSql(sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`) VALUES ('%s','%s','%s','%s')",
1820 * Checks if given subject is found and if so, adds an SQL query to the
1821 * extension unregistration queue.
1823 function unregisterExtensionPointsData ($subject) {
1824 // Default is old extension version
1827 // Is the extension equal or newer 0.8.9?
1828 if (isExtensionInstalledAndNewer('sql_patches', '0.8.9')) {
1829 // Then add provider
1830 $add = " AND `account_provider`='EXTENSION'";
1833 // Is the 'subject' there?
1834 if (countSumTotalData($subject, 'points_data', 'id', 'subject', true, $add) == 1) {
1835 // Found one or more, so add an SQL query
1836 addExtensionSql(sprintf("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_points_data` WHERE `subject`='%s'" . $add . " LIMIT 1",