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 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
165 $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>';
167 // Can we close the you-are-here navigation?
168 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . 'getWhat()=' . getWhat());
169 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'welcome')))) {
170 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
171 // Add closing div and br-tag
172 $GLOBALS['nav_depth'] = '0';
174 // Run the post-filter chain
175 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => $OUT, 'add' => $ADD));
177 // Get content from filter back
178 $OUT = $ret['content'];
180 // Close div-tag, so not the filters have to do it
185 // Return or output HTML code?
186 if ($return === true) {
190 // Output HTML code here
195 // Adds a menu (mode = guest/member/admin/sponsor) to output
196 function addMenu ($mode, $action, $what) {
197 // Init some variables
200 // is the menu action valid?
201 if (!isMenuActionValid($mode, $action, $what, true)) {
202 return getCode('MENU_NOT_VALID');
205 // Non-admin shall not see all menus
206 $ADD = " AND `visible`='Y' AND `locked`='N'";
208 // Is admin, so make all visible
212 // Load SQL data and add the menu to the output stream...
213 $result_main = SQL_QUERY_ESC("SELECT
214 `title`,`what`,`action`,`visible`,`locked`
216 `{?_MYSQL_PREFIX?}_%s_menu`
218 (`what`='' OR `what` IS NULL)
222 array($mode), __FUNCTION__, __LINE__);
224 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
225 if (!SQL_HASZERONUMS($result_main)) {
226 // There are menus available, so we simply display them... :)
227 $GLOBALS['rows'] = '';
228 while ($content = SQL_FETCHARRAY($result_main)) {
229 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
230 // Disable the block-mode
231 enableBlockMode(false);
233 // Load menu header template
234 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
237 $result_sub = SQL_QUERY_ESC("SELECT
238 `title` AS `sub_title`,
239 `what` AS `sub_what`,
240 `visible` AS `sub_visible`,
241 `locked` AS `sub_locked`
243 `{?_MYSQL_PREFIX?}_%s_menu`
251 array($mode, $content['action']), __FUNCTION__, __LINE__);
253 // Do we have some entries?
254 if (!SQL_HASZERONUMS($result_sub)) {
258 // Load all sub menus
259 while ($content2 = SQL_FETCHARRAY($result_sub)) {
260 // Merge both arrays in one
261 $content = merge_array($content, $content2);
266 // Full file name for checking menu
267 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
268 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
269 if (isIncludeReadable($inc)) {
270 // Mark currently selected menu - open
271 if ((!empty($what)) && (($what == $content['sub_what']))) {
275 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
276 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
277 // Use index.php as link
278 $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
280 // Regular navigation link
281 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
285 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
289 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
291 if (isIncludeReadable($inc)) {
294 // Mark currently selected menu - close
295 if ((!empty($what)) && (($what == $content['sub_what']))) {
309 'what' => $content['sub_what'],
310 'visible' => $content['sub_visible'],
311 'locked' => $content['locked'],
314 // Add regular menu row or bottom row?
315 if ($count < SQL_NUMROWS($result_sub)) {
316 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
318 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
322 // This is a menu block... ;-)
326 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
327 if (isFileReadable($INC)) {
329 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
330 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
333 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
335 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
339 SQL_FREERESULT($result_sub);
344 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
345 if (SQL_NUMROWS($result_main) > $main_cnt) {
347 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
349 // Should we display adverts in this menu?
350 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
351 // Display advert template
352 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
354 // Add separator again
355 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
361 SQL_FREERESULT($result_main);
363 // Should we display adverts in this menu?
364 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
365 // Add separator again
366 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
368 // Display advert template
369 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
374 'rows' => $GLOBALS['rows'],
378 // Load main template
379 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
380 loadTemplate('menu_table', false, $content);
384 // Checks whether the current user is a member
385 function isMember () {
386 // By default no member
389 // Fix missing 'last_online' array, damn stupid code :(((
390 // @TODO Try to rewrite this to one or more functions
391 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
392 $GLOBALS['last_online'] = array();
395 // Is the cache entry there?
396 if (isset($GLOBALS[__FUNCTION__])) {
398 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
399 return $GLOBALS[__FUNCTION__];
400 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
401 // Destroy any existing user session data
402 destroyMemberSession();
403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
405 // Abort further processing
409 // Get userid secured from session
410 setMemberId(getSession('userid'));
412 // ... and set it as currently handled user id
413 setCurrentUserId(getMemberId());
415 // Init user data array
418 // Fix "deleted" cookies first
419 fixDeletedCookies(array('userid', 'u_hash'));
421 // Are cookies set and can the member data be loaded?
422 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
423 // Validate password by created the difference of it and the secret key
424 $valPass = encodeHashForCookie(getUserData('password'));
426 // So did we now have valid data and an unlocked user?
427 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
428 // Transfer last module and online time
429 $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
430 $GLOBALS['last_online']['online'] = getUserData('last_online');
432 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
437 // Is $ret still false?
438 if ($ret === false) {
439 // Yes, so destroy the session
440 destroyMemberSession();
444 $GLOBALS[__FUNCTION__] = $ret;
447 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
451 // Fetch user data for given user id
452 function fetchUserData ($value, $column = 'userid') {
453 // Extension ext-user must be there at any case
454 if (!isExtensionActive('user')) {
455 // Absent ext-user is really not good
457 } elseif (is_null($value)) {
458 // This shall never happen, so please report it
459 reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
462 // If we should look for userid secure&set it here
463 if (substr($column, -2, 2) == 'id') {
465 $value = bigintval($value);
468 setCurrentUserId($value);
470 // Don't look for invalid userids...
471 if (!isValidUserId($value)) {
472 // Invalid, so abort here
473 reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
474 } elseif (isUserDataValid()) {
475 // Use cache, so it is fine
476 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
479 } elseif (isUserDataValid()) {
480 // Using cache is fine
481 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
485 // By default none was found
488 // Extra SQL statements
489 $ADD = runFilterChain('convert_user_data_columns', '');
491 // Query for the user
492 $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
493 array($column, $value), __FUNCTION__, __LINE__);
495 // Do we have a record?
496 if (SQL_NUMROWS($result) == 1) {
497 // Load data from cookies
498 $data = SQL_FETCHARRAY($result);
500 // Set the userid for later use
501 setCurrentUserId($data['userid']);
503 // And cache the data for this userid
504 $GLOBALS['user_data'][getCurrentUserId()] = $data;
506 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
507 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
508 // Backup the raw one and zero it
509 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
510 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
513 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
514 // Seperate data/time
515 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
517 // Seperate data and time again
518 $array['date'] = explode('-', $array[0]);
519 $array['time'] = explode(':', $array[1]);
521 // Now pass it to mktime()
522 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
534 $found = isUserDataValid();
538 SQL_FREERESULT($result);
545 * Checks whether the current session bears a valid admin id and password hash.
547 * This patched function will reduce many SELECT queries for the current admin
550 function isAdmin () {
551 // No admin in installation phase!
552 if ((isInstallationPhase()) || (!isAdminRegistered())) {
559 $passwordFromCookie = '';
561 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
563 // If admin login is not given take current from cookies...
564 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
565 // Get admin login and password from session/cookies
566 $adminId = getCurrentAdminId();
567 $passwordFromCookie = getAdminMd5();
569 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . 'passwordFromCookie=' . $passwordFromCookie);
571 // Abort if admin id is zero
572 if ($adminId == '0') {
573 // A very noisy debug message ...
574 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
581 if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
582 // Init it with failed
583 $GLOBALS[__FUNCTION__][$adminId] = false;
585 // Search in array for entry
586 if (isset($GLOBALS['admin_hash'])) {
588 $valPass = $GLOBALS['admin_hash'];
589 } elseif ((!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
590 // Login data is valid or not?
591 $valPass = encodeHashForCookie(getAdminHash($adminId));
594 $GLOBALS['admin_hash'] = $valPass;
597 incrementStatsEntry('cache_hits');
598 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
599 // Get admin hash and hash it
600 $valPass = encodeHashForCookie(getAdminHash($adminId));
603 $GLOBALS['admin_hash'] = $valPass;
606 if (!empty($valPass)) {
607 // Check if password is valid
608 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passwordFromCookie . ')='.intval($valPass == $passwordFromCookie));
609 $GLOBALS[__FUNCTION__][$adminId] = ($GLOBALS['admin_hash'] == $passwordFromCookie);
613 // Return result of comparision
614 return $GLOBALS[__FUNCTION__][$adminId];
617 // Generates a list of "max receiveable emails per day"
618 function addMaxReceiveList ($mode, $default = '', $return = false) {
624 // Guests (in the registration form) are not allowed to select 0 mails per day.
625 $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
626 __FUNCTION__, __LINE__);
631 // Members are allowed to set to zero mails per day (we will change this soon!)
632 $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
633 __FUNCTION__, __LINE__);
637 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
641 // Some entries are found?
642 if (!SQL_HASZERONUMS($result)) {
644 while ($content = SQL_FETCHARRAY($result)) {
645 $OUT .= ' <option value="' . $content['value'] . '"';
647 if (postRequestElement('max_mails') == $content['value']) {
648 $OUT .= ' selected="selected"';
651 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
652 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
657 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
659 // Maybe the admin has to setup some maximum values?
660 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
664 SQL_FREERESULT($result);
666 if ($return === true) {
667 // Return generated HTML code
670 // Output directly (default)
675 // Checks whether the given email address is used.
676 function isEmailTaken ($email) {
677 // Default is no userid
678 $useridSql = ' IS NOT NULL';
680 // Is a member logged in?
683 $useridSql = '!= ' . bigintval(getMemberId());
686 // Replace dot with {DOT}
687 $email = str_replace('.', '{DOT}', $email);
689 // Query the database
690 $result = SQL_QUERY_ESC("SELECT
691 COUNT(`userid`) AS `cnt`
693 `{?_MYSQL_PREFIX?}_user_data`
695 '%s' REGEXP `email` AND
701 ), __FUNCTION__, __LINE__);
703 // Is the email there?
704 list($count) = SQL_FETCHROW($result);
707 SQL_FREERESULT($result);
710 return ($count == 1);
713 // Validate the given menu action
714 function isMenuActionValid ($mode, $action, $what, $updateEntry = false) {
715 // Is the cache entry there and we shall not update?
716 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
718 incrementStatsEntry('cache_hits');
720 // Then use this cache
721 return $GLOBALS['action_valid'][$mode][$action][$what];
724 // By default nothing is valid
727 // Look in all menus or only unlocked
729 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
731 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
732 if (($mode != 'admin') && ($updateEntry === true)) {
733 // Update guest or member menu
734 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
739 ), __FUNCTION__, __LINE__, false);
740 } elseif (($what != 'welcome') && (!empty($what))) {
742 $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",
747 ), __FUNCTION__, __LINE__, false);
749 // Admin login overview
750 $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",
754 ), __FUNCTION__, __LINE__, false);
758 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
760 // Should we look for affected rows (only update) or found rows?
761 if ($updateEntry === true) {
762 // Check updated/affected rows
763 $ret = (!SQL_HASZEROAFFECTED());
766 $ret = (!SQL_HASZERONUMS($result));
770 SQL_FREERESULT($result);
773 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
779 // Get action value from mode (admin/guest/member) and what-value
780 function getActionFromModuleWhat ($module, $what) {
781 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
783 $data['action'] = '';
785 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
786 // sql_patches is missing so choose depending on mode
787 $what = determineWhat($module);
788 } elseif ((empty($what)) && ($module != 'admin')) {
789 // Use configured 'home'
790 $what = getIndexHome();
793 if ($module == 'admin') {
794 // Action value for admin area
795 if (isGetRequestElementSet('action')) {
797 return getRequestElement('action');
798 } elseif (isActionSet()) {
799 // Get it directly from URL
801 } elseif (($what == 'welcome') || (!isWhatSet())) {
802 // Default value for admin area
803 $data['action'] = 'login';
805 } elseif (isActionSet()) {
806 // Get it directly from URL
809 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
811 // Does the module have a menu?
812 if (ifModuleHasMenu($module)) {
813 // Rewriting modules to menu
814 $module = mapModuleToTable($module);
816 // Guest and member menu is 'main' as the default
817 if (empty($data['action'])) {
818 $data['action'] = 'main';
821 // Load from database
822 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
826 ), __FUNCTION__, __LINE__);
827 if (SQL_NUMROWS($result) == 1) {
828 // Load action value and pray that this one is the right you want... ;-)
829 $data = SQL_FETCHARRAY($result);
833 SQL_FREERESULT($result);
834 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
835 // No sql_patches installed, but maybe we need to register an admin?
836 if (isAdminRegistered()) {
837 // Redirect to admin area
838 redirectToUrl('admin.php');
842 // Return action value
843 return $data['action'];
846 // Get category name back
847 function getCategory ($cid) {
848 // Default is not found
849 $data['cat'] = '{--_CATEGORY_404--}';
851 // Is the category id set?
854 $data['cat'] = '{--_CATEGORY_NONE--}';
855 } elseif ($cid > 0) {
856 // Lookup the category in database
857 $result = SQL_QUERY_ESC('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
858 array(bigintval($cid)), __FUNCTION__, __LINE__);
859 if (SQL_NUMROWS($result) == 1) {
860 // Category found... :-)
861 $data = SQL_FETCHARRAY($result);
865 SQL_FREERESULT($result);
872 // Get a string of "mail title" and price back
873 function getPaymentTitlePrice ($pid, $full = false) {
874 // Only title or also including price?
875 if ($full === false) {
876 $ret = getPaymentData($pid, 'main_title');
878 $ret = getPaymentData($pid, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $pid . '%} {?POINTS?}';
885 // "Getter" for payment data (cached)
886 function getPaymentData ($pid, $lookFor = 'price') {
888 $data[$lookFor] = NULL;
891 if (isset($GLOBALS['cache_array']['payments']['id'][$pid])) {
892 // Use it if found to save SQL queries
893 die('<pre>'.print_r($GLOBALS['cache_array']['payments'],true).'</pre>');
894 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$pid];
897 incrementStatsEntry('cache_hits');
898 } elseif (!isExtensionActive('cache')) {
899 // Search for it in database
900 $result = SQL_QUERY_ESC('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
904 ), __FUNCTION__, __LINE__);
906 // Is the entry there?
907 if (SQL_NUMROWS($result) == 1) {
908 // Payment type found... :-)
909 $data = SQL_FETCHARRAY($result);
913 SQL_FREERESULT($result);
917 return $data[$lookFor];
920 // Remove a receiver's id from $receivers and add a link for him to confirm
921 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = false) {
922 // Default is not removed
925 // Is the userid valid?
926 if (isValidUserId($userid)) {
927 // Remove entry from array
928 unset($receivers[$key]);
930 // Is there already a line for this user available?
932 // Default is 'normal' mail
934 $rowName = 'stats_id';
936 // Only when we got a real stats id continue searching for the entry
937 if ($isBonusMail === true) {
939 $rowName = 'bonus_id';
942 // Try to look the entry up
943 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
949 ), __FUNCTION__, __LINE__);
951 // Was it *not* found?
952 if (SQL_HASZERONUMS($result)) {
954 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES (%s,%s,'%s')",
960 ), __FUNCTION__, __LINE__);
962 // Update 'mails_sent' if sql_patches is updated
963 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
965 SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1',
966 array(bigintval($poolId)), __FUNCTION__, __LINE__);
975 SQL_FREERESULT($result);
979 // Return status for sending routine
983 // Calculate sum (default) or count records of given criteria
984 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '', $mode = '=') {
988 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
989 if ((empty($search)) && ($search != '0')) {
990 // Count or sum whole table?
991 if ($countRows === true) {
993 $result = SQL_QUERY_ESC('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
997 ), __FUNCTION__, __LINE__);
1000 $result = SQL_QUERY_ESC('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1004 ), __FUNCTION__, __LINE__);
1006 } elseif (($countRows === true) || ($lookFor == 'userid')) {
1008 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1009 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1016 ), __FUNCTION__, __LINE__);
1019 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1020 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1027 ), __FUNCTION__, __LINE__);
1031 $data = SQL_FETCHARRAY($result);
1034 SQL_FREERESULT($result);
1037 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1039 $data['res'] = '0.00000';
1040 } elseif (''.$data['res'].'' == '') {
1046 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1047 return $data['res'];
1051 * Sends out mail to all administrators. This function is no longer obsolete
1052 * because we need it when there is no ext-admins installed
1054 function sendAdminEmails ($subject, $message, $isBugReport = false) {
1055 // Default is no special header
1058 // Is it a bug report?
1059 if ($isBugReport === true) {
1060 // Then add a reply-to line back to the author (me)
1061 $mailHeader = 'Reply-To: webmaster@mxchange.org' . chr(10);
1064 // Load all admin email addresses
1065 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1067 // And send the notification to all of them
1068 while ($content = SQL_FETCHARRAY($result)) {
1069 // Send the email out
1070 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1074 SQL_FREERESULT($result);
1076 // Really simple... ;-)
1079 // Get id number from administrator's login name
1080 function getAdminId ($adminLogin) {
1081 // By default no admin is found
1085 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1086 // Use it if found to save SQL queries
1087 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1089 // Update cache hits
1090 incrementStatsEntry('cache_hits');
1091 } elseif (!isExtensionActive('cache')) {
1092 // Load from database
1093 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1094 array($adminLogin), __FUNCTION__, __LINE__);
1096 // Do we have an entry?
1097 if (SQL_NUMROWS($result) == 1) {
1099 $data = SQL_FETCHARRAY($result);
1103 SQL_FREERESULT($result);
1110 // "Getter" for current admin id
1111 function getCurrentAdminId () {
1112 // Log debug message
1113 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1115 // Do we have cache?
1116 if (!isset($GLOBALS['current_admin_id'])) {
1117 // Get the admin login from session
1118 $adminId = getSession('admin_id');
1120 // Remember in cache securely
1121 setCurrentAdminId(bigintval($adminId));
1125 return $GLOBALS['current_admin_id'];
1128 // Setter for current admin id
1129 function setCurrentAdminId ($currentAdminId) {
1131 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1134 // Get password hash from administrator's login name
1135 function getAdminHash ($adminId) {
1136 // By default an invalid hash is returned
1137 $data['password'] = -1;
1139 if (isAdminHashSet($adminId)) {
1141 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1143 // Update cache hits
1144 incrementStatsEntry('cache_hits');
1145 } elseif (!isExtensionActive('cache')) {
1146 // Load from database
1147 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1148 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1150 // Do we have an entry?
1151 if (SQL_NUMROWS($result) == 1) {
1153 $data = SQL_FETCHARRAY($result);
1156 setAdminHash($adminId, $data['password']);
1160 SQL_FREERESULT($result);
1163 // Return password hash
1164 return $data['password'];
1167 // "Getter" for admin login
1168 function getAdminLogin ($adminId) {
1169 // By default a non-existent login is returned (other functions react on this!)
1170 $data['login'] = '***';
1172 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1174 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1176 // Update cache hits
1177 incrementStatsEntry('cache_hits');
1178 } elseif (!isExtensionActive('cache')) {
1179 // Load from database
1180 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1181 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1184 if (SQL_NUMROWS($result) == 1) {
1186 $data = SQL_FETCHARRAY($result);
1189 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1193 SQL_FREERESULT($result);
1196 // Return the result
1197 return $data['login'];
1200 // Get email address of admin id
1201 function getAdminEmail ($adminId) {
1202 // By default an invalid emails is returned
1203 $data['email'] = '***';
1205 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1207 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1209 // Update cache hits
1210 incrementStatsEntry('cache_hits');
1211 } elseif (!isExtensionActive('cache')) {
1212 // Load from database
1213 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1214 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1217 if (SQL_NUMROWS($result_admin_id) == 1) {
1219 $data = SQL_FETCHARRAY($result_admin_id);
1222 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1226 SQL_FREERESULT($result_admin_id);
1230 return $data['email'];
1233 // Get default ACL of admin id
1234 function getAdminDefaultAcl ($adminId) {
1235 // By default an invalid ACL value is returned
1236 $data['default_acl'] = 'NO-ACL';
1238 // Is sql_patches there and was it found in cache?
1239 if (!isExtensionActive('sql_patches')) {
1240 // Not found, which is bad, so we need to allow all
1241 $data['default_acl'] = 'allow';
1242 } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1244 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1246 // Update cache hits
1247 incrementStatsEntry('cache_hits');
1248 } elseif (!isExtensionActive('cache')) {
1249 // Load from database
1250 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1251 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1253 // Do we have an entry?
1254 if (SQL_NUMROWS($result_admin_id) == 1) {
1256 $data = SQL_FETCHARRAY($result_admin_id);
1259 $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1263 SQL_FREERESULT($result_admin_id);
1266 // Return default ACL
1267 return $data['default_acl'];
1270 // Get menu mode (la_mode) of admin id
1271 function getAdminMenuMode ($adminId) {
1272 // By default an invalid mode
1273 $data['la_mode'] = 'INVALID';
1275 // Is sql_patches there and was it found in cache?
1276 if (!isExtensionActive('sql_patches')) {
1277 // Not found, which is bad, so we need to allow all
1278 $data['la_mode'] = 'global';
1279 } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1281 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1283 // Update cache hits
1284 incrementStatsEntry('cache_hits');
1285 } elseif (!isExtensionActive('cache')) {
1286 // Load from database
1287 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1288 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1290 // Do we have an entry?
1291 if (SQL_NUMROWS($result_admin_id) == 1) {
1293 $data = SQL_FETCHARRAY($result_admin_id);
1296 $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1300 SQL_FREERESULT($result_admin_id);
1303 // Return default ACL
1304 return $data['la_mode'];
1307 // Generates an option list from various parameters
1308 function generateOptions ($table, $id, $name, $default = '', $special = '', $whereStatement = '', $disabled = array(), $callback = '') {
1310 if ($table == '/ARRAY/') {
1311 // Selection from array
1312 if ((is_array($id)) && (is_array($name)) && ((count($id)) == (count($name)) || (!empty($callback)))) {
1314 foreach ($id as $idx => $value) {
1315 $ret .= '<option value="' . $value . '"';
1316 if ($default == $value) {
1317 // Selected by default
1318 $ret .= ' selected="selected"';
1319 } elseif (isset($disabled[$value])) {
1321 $ret .= ' disabled="disabled"';
1324 // Is the call-back function set?
1325 if (!empty($callback)) {
1327 $name[$idx] = call_user_func_array($callback, array($id[$idx]));
1330 // Finish option tag
1331 $ret .= '>' . $name[$idx] . '</option>';
1334 // Problem in request
1335 reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
1338 // Data from database
1339 $SPEC = ',`' . $id . '`';
1340 if (!empty($special)) {
1341 $SPEC = ',`' . $special . '` AS `special`';
1344 // Query the database
1345 $result = SQL_QUERY_ESC("SELECT `%s` AS `id`,`%s` AS `name`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$whereStatement." ORDER BY `%s` ASC",
1351 ), __FUNCTION__, __LINE__);
1354 if (!SQL_HASZERONUMS($result)) {
1355 // Found data so add them as OPTION lines
1356 while ($content = SQL_FETCHARRAY($result)) {
1358 if (!isset($content['special'])) {
1360 $content['special'] = '';
1363 $ret .= '<option value="' . $content['id'] . '"';
1365 if ($default == $content['id']) {
1366 // Selected by default
1367 $ret .= ' selected="selected"';
1368 } elseif (isset($disabled[$content['id']])) {
1370 $ret .= ' disabled="disabled"';
1374 if (!empty($content['special'])) {
1375 $content['special'] = ' (' . $content['special'] . ')';
1378 // Is the call-back function set?
1379 if (!empty($callback)) {
1381 $content['name'] = call_user_func_array($callback, array($content['name']));
1384 // Finish option list
1385 $ret .= '>' . $content['name'] . $content['special'] . '</option>';
1389 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1393 SQL_FREERESULT($result);
1396 // Return - hopefully - the requested data
1400 // Deletes a user account with given reason
1401 function deleteUserAccount ($userid, $reason) {
1403 $data['points'] = '0';
1405 // Search for the points and user data
1406 $result = SQL_QUERY_ESC("SELECT
1407 (SUM(p.`points`) - d.`used_points`) AS `points`
1409 `{?_MYSQL_PREFIX?}_user_points` AS p
1411 `{?_MYSQL_PREFIX?}_user_data` AS d
1413 p.`userid`=d.`userid`
1417 array(bigintval($userid)), __FUNCTION__, __LINE__);
1419 // Do we have an entry?
1420 if (SQL_NUMROWS($result) == 1) {
1421 // Save his points to add them to the jackpot
1422 $data = SQL_FETCHARRAY($result);
1424 // Delete points entries as well
1425 // @TODO Rewrite these lines to a filter
1426 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1427 array(bigintval($userid)), __FUNCTION__, __LINE__);
1429 // Update mediadata as well
1430 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1432 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1435 // Now, when we have all his points adds them do the jackpot!
1436 if (isExtensionActive('jackpot')) {
1437 addPointsToJackpot($data['points']);
1442 SQL_FREERESULT($result);
1444 // Delete category selections as well...
1445 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1446 array(bigintval($userid)), __FUNCTION__, __LINE__);
1448 // Remove from rallye if found
1449 // @TODO Rewrite this to a filter
1450 if (isExtensionActive('rallye')) {
1451 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1452 array(bigintval($userid)), __FUNCTION__, __LINE__);
1455 // Add reason and translate points
1456 $data['text'] = $reason;
1458 // Now a mail to the user and that's all...
1459 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1460 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1462 // Ok, delete the account!
1463 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1466 // Gets the matching what name from module
1467 function getWhatFromModule ($modCheck) {
1468 // Is the request element set?
1469 if (isGetRequestElementSet('what')) {
1470 // Then return this!
1471 return getRequestElement('what');
1477 // Check on given module
1478 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1479 switch ($modCheck) {
1480 case 'index': // Guest area
1481 // Is ext-sql_patches installed and newer than 0.0.5?
1482 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1483 // Use it from config
1484 $what = getIndexHome();
1486 // Use default 'welcome'
1491 default: // Default for all other menus (getIndexHome() is for index module only)
1496 // Return what value
1500 // Returns HTML code with an option list of all categories
1501 function generateCategoryOptionsList ($mode, $userid = NULL) {
1502 // Prepare WHERE statement
1503 $whereStatement = " WHERE `visible`='Y'";
1504 if (isAdmin()) $whereStatement = '';
1506 // Initialize array...
1507 $categories = array(
1510 'userids' => array()
1514 $result = SQL_QUERY('SELECT `id`,`cat` FROM `{?_MYSQL_PREFIX?}_cats`' . $whereStatement . ' ORDER BY `sort` ASC',
1515 __FUNCTION__, __LINE__);
1517 // Do we have entries?
1518 if (!SQL_HASZERONUMS($result)) {
1519 // ... and begin loading stuff
1520 while ($content = SQL_FETCHARRAY($result)) {
1521 // Transfer some data
1522 $categories['id'][] = $content['id'];
1523 array_push($categories['name'], $content['cat']);
1525 // Check which users are in this category
1526 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1528 bigintval($content['id']),
1529 convertNullToZero($userid)
1530 ), __FUNCTION__, __LINE__);
1536 while ($data = SQL_FETCHARRAY($result_userids)) {
1538 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1542 SQL_FREERESULT($result_userids);
1545 array_push($categories['userids'], $userid_cnt);
1549 SQL_FREERESULT($result);
1553 foreach ($categories['id'] as $key => $value) {
1554 $OUT .= ' <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1557 // No cateogries are defined yet
1558 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1565 // Add bonus mail to queue
1566 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1567 // Is admin or bonus extension there?
1571 } elseif (!isExtensionActive('bonus')) {
1576 // Calculcate target sent
1577 $target = countSelection(explode(';', $receiverList));
1579 // Receiver is zero?
1580 if ($receiver == '0') {
1582 $receiver = $target;
1585 // HTML extension active?
1586 if (isExtensionActive('html_mail')) {
1587 // Determine if we have HTML mode active
1588 $HTML = convertBooleanToYesNo($mode == 'html');
1591 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1592 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`,`html_msg`)
1593 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s,'%s')",
1599 bigintval($seconds),
1601 bigintval($categoryId),
1603 bigintval($receiver),
1605 ), __FUNCTION__, __LINE__);
1608 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1609 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`)
1610 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s)",
1616 bigintval($seconds),
1618 bigintval($categoryId),
1620 bigintval($receiver),
1621 ), __FUNCTION__, __LINE__);
1625 // Generate a receiver list for given category and maximum receivers
1626 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1633 $categoryId = bigintval($categoryId);
1634 $receiver = bigintval($receiver);
1636 // Is the receiver zero and mode set?
1637 if (($receiver == '0') && (!empty($mode))) {
1638 // Auto-fix receiver maximum
1639 $receiver = getTotalReceivers($mode);
1642 // Exclude (maybe exclude) testers
1643 $addWhere = runFilterChain('user_exclusion_sql', ' ');
1646 if ($categoryId > 0) {
1648 $extraColumns = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1649 $addWhere = sprintf(" AND c.`cat_id`=%s", $categoryId);
1652 // Exclude users in holiday?
1653 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1654 // Add something for the holiday extension
1655 $addWhere .= " AND d.`holiday_active`='N'";
1658 // Include only HTML recipients?
1659 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1660 $addWhere .= " AND d.`html`='Y'";
1664 $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",
1667 ), __FUNCTION__, __LINE__);
1670 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1672 while ($content = SQL_FETCHARRAY($result)) {
1673 // Add receiver when not empty
1674 if (!empty($content['userid'])) {
1675 $receiverList .= $content['userid'] . ';';
1680 SQL_FREERESULT($result);
1682 // Remove trailing semicolon
1683 $receiverList = substr($receiverList, 0, -1);
1687 return $receiverList;
1690 // Recuce the amount of received emails for the receipients for given email
1691 function reduceRecipientReceivedMails ($column, $id, $count) {
1692 // Search for mail in database
1693 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1694 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1696 // Are there entries?
1697 if (!SQL_HASZERONUMS($result)) {
1698 // Now load all userids for one big query!
1700 while ($data = SQL_FETCHARRAY($result)) {
1701 // By default we want to reduce and have no mails found
1704 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1705 // @TODO Rewrite this to a filter
1706 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1708 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1709 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1711 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1714 // Reduce this users total received emails?
1716 $userids[$data['userid']] = $data['userid'];
1720 if (count($userids) > 0) {
1721 // Now update all user accounts
1722 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1723 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1726 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1731 SQL_FREERESULT($result);
1734 // Creates a new task
1735 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = true) {
1736 // Insert the task data into the database
1737 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())",
1739 convertZeroToNull($adminId),
1740 convertZeroToNull($userid),
1744 ), __FUNCTION__, __LINE__, true, $strip);
1746 // Return insert id which is the task id
1747 return SQL_INSERTID();
1750 // Updates last module / online time
1751 function updateLastActivity($userid) {
1754 // Run the update query
1755 SQL_QUERY_ESC("UPDATE
1756 `{?_MYSQL_PREFIX?}_user_data`
1759 `last_online`=UNIX_TIMESTAMP(),
1765 getUserLastWhatName(),
1769 ), __FUNCTION__, __LINE__);
1771 // No what set, needs to be ignored (last_module is last_what)
1772 SQL_QUERY_ESC("UPDATE
1773 `{?_MYSQL_PREFIX?}_user_data`
1776 `last_online`=UNIX_TIMESTAMP(),
1782 getUserLastWhatName(),
1785 ), __FUNCTION__, __LINE__);
1790 * Checks if given subject is found and if not, adds an SQL query to the
1791 * extension registration queue.
1793 function registerExtensionPointsData ($subject, $columnName, $lockedMode, $paymentMethod) {
1794 // Default is old extension version
1797 // Is the extension equal or newer 0.8.9?
1798 if ((getExtensionMode() == 'register') || (getExtensionMode() == 'update') || (isExtensionInstalledAndNewer('sql_patches', '0.8.9'))) {
1799 // Then add provider
1800 $add = " AND `account_provider`='EXTENSION'";
1803 // Is the 'subject' there?
1804 if (((!ifSqlTableExists('points_data')) && ((getExtensionMode() == 'register') || (getExtensionMode() == 'update'))) || (countSumTotalData($subject, 'points_data', 'id', 'subject', true, $add) == 0)) {
1805 // Not found so add an SQL query
1806 addExtensionSql(sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`) VALUES ('%s','%s','%s','%s')",
1816 * Checks if given subject is found and if so, adds an SQL query to the
1817 * extension unregistration queue.
1819 function unregisterExtensionPointsData ($subject) {
1820 // Default is old extension version
1823 // Is the extension equal or newer 0.8.9?
1824 if (isExtensionInstalledAndNewer('sql_patches', '0.8.9')) {
1825 // Then add provider
1826 $add = " AND `account_provider`='EXTENSION'";
1829 // Is the 'subject' there?
1830 if (countSumTotalData($subject, 'points_data', 'id', 'subject', true, $add) == 1) {
1831 // Found one or more, so add an SQL query
1832 addExtensionSql(sprintf("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_points_data` WHERE `subject`='%s'" . $add . " LIMIT 1",