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 - 2013 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 = sqlQueryEscaped("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
69 ), __FUNCTION__, __LINE__);
72 if (sqlNumRows($result) == 1) {
74 $data = sqlFetchArray($result);
78 sqlFreeResult($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 // Is there 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();
132 $modCheck = getModule();
135 // Begin the navigation line
136 if (!isset($GLOBALS['nav_depth'])) {
138 $GLOBALS['nav_depth'] = '0';
140 // Run the pre-filter chain
141 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => '', 'add' => $ADD));
144 $prefix = $ret['content'];
146 // Add default content
147 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--} <strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $linkAdd . '%}">Home</a></strong>';
148 } elseif ($return === FALSE) {
150 $GLOBALS['nav_depth']++;
154 $prefix .= ' -> ';
156 // We need to remove .php and the end
157 if (substr($search, -4, 4) == '.php') {
159 $search = substr($search, 0, -4);
162 // Is ext-sql_patches installed?
163 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isExtensionInstalledAndNewer()=' . intval(isExtensionInstalledAndNewer('sql_patches', '0.2.3')) . ',youre_here=' . getYoureHere() . ',isAdmin()=' . intval(isAdmin()) . ',modCheck=' . $modCheck);
164 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (isYoureHereEnabled())) || ((isAdmin()) && ($modCheck == 'admin'))) {
166 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&' . $type . '=' . $search . $linkAdd . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
168 // Can we close the you-are-here navigation?
169 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',getWhat()=' . getWhat() . ',accessLevel=' . $accessLevel . ',isWhatSet()=' . intval(isWhatSet()));
170 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (($accessLevel == 'admin') && (getWhat() == 'welcome'))))) {
171 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
172 // Add closing div and br-tag
173 $GLOBALS['nav_depth'] = '0';
175 // Run the post-filter chain
176 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => $OUT, 'add' => $ADD));
178 // Get content from filter back
179 $OUT = $ret['content'];
181 // Close div-tag, so not the filters have to do it
186 // Return or output HTML code?
187 if ($return === TRUE) {
191 // Output HTML code here
196 // Adds a menu (mode = guest/member/admin/sponsor) to output
197 function addMenu ($mode, $action, $what) {
198 // Init some variables
201 // is the menu action valid?
202 if (!isMenuActionValid($mode, $action, $what, TRUE)) {
203 return getCode('MENU_NOT_VALID');
206 // Non-admin shall not see all menus
207 $ADD = " AND `visible`='Y' AND `locked`='N'";
209 // Is admin, so make all visible
213 // Load SQL data and add the menu to the output stream...
214 $result_main = sqlQueryEscaped("SELECT
221 `{?_MYSQL_PREFIX?}_%s_menu`
223 (`what`='' OR `what` IS NULL)
227 array($mode), __FUNCTION__, __LINE__);
229 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
230 if (!ifSqlHasZeroNums($result_main)) {
231 // There are menus available, so we simply display them... :)
232 $GLOBALS['rows'] = '';
233 while ($content = sqlFetchArray($result_main)) {
234 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
235 // Disable the block-mode
236 enableBlockMode(FALSE);
238 // Load menu header template
239 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', TRUE, $content);
242 $result_sub = sqlQueryEscaped("SELECT
243 `title` AS `sub_title`,
244 `what` AS `sub_what`,
245 `visible` AS `sub_visible`,
246 `locked` AS `sub_locked`
248 `{?_MYSQL_PREFIX?}_%s_menu`
259 ), __FUNCTION__, __LINE__);
261 // Are there some entries?
262 if (!ifSqlHasZeroNums($result_sub)) {
266 // Load all sub menus
267 while ($content2 = sqlFetchArray($result_sub)) {
268 // Merge both arrays in one
269 $content = merge_array($content, $content2);
274 // Full file name for checking menu
275 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
276 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
277 if (isIncludeReadable($inc)) {
278 // Mark currently selected menu - open
279 if ((!empty($what)) && (($what == $content['sub_what']))) {
283 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
284 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
285 // Use index.php as link
286 $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
288 // Regular navigation link
289 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
293 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
297 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
299 if (isIncludeReadable($inc)) {
302 // Mark currently selected menu - close
303 if ((!empty($what)) && (($what == $content['sub_what']))) {
317 'what' => $content['sub_what'],
318 'visible' => $content['sub_visible'],
319 'locked' => $content['locked'],
322 // Add regular menu row or bottom row?
323 if ($count < sqlNumRows($result_sub)) {
324 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', TRUE, $content);
326 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', TRUE, $content);
330 // This is a menu block... ;-)
334 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
335 if (isFileReadable($INC)) {
337 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', TRUE, $mode);
338 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
341 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', TRUE, $mode);
343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
347 sqlFreeResult($result_sub);
352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
353 if (sqlNumRows($result_main) > $main_cnt) {
355 $GLOBALS['rows'] .= loadTemplate('menu_separator', TRUE, $mode);
357 // Prepare filter data array
360 'exclusive' => FALSE,
366 $filterData = runFilterChain($mode . '_menu_advert', $filterData);
368 // Add content output
369 $GLOBALS['rows'] .= $filterData['output'];
374 sqlFreeResult($result_main);
376 // Prepare filter data array
379 'exclusive' => FALSE,
385 $filterData = runFilterChain($mode . '_menu_advert_end', $filterData);
387 // Add content output
388 $GLOBALS['rows'] .= $filterData['output'];
392 'rows' => $GLOBALS['rows'],
396 // Load main template
397 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
398 loadTemplate('menu_table', FALSE, $content);
402 // Checks whether the current user is a member
403 function isMember () {
404 // By default no member
407 // Fix missing 'last_online' array, damn stupid code :(((
408 // @TODO Try to rewrite this to one or more functions
409 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
410 $GLOBALS['last_online'] = array();
413 // Is the cache entry there?
414 if (isset($GLOBALS[__FUNCTION__])) {
416 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
417 return $GLOBALS[__FUNCTION__];
418 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
419 // Destroy any existing user session data
420 destroyMemberSession();
421 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
423 // Abort further processing
427 // Get userid secured from session
428 setMemberId(getSession('userid'));
430 // ... and set it as currently handled user id
431 setCurrentUserId(getMemberId());
433 // Init user data array
436 // Fix "deleted" cookies
437 fixDeletedCookies(array('userid', 'u_hash'));
439 // Are cookies set and can the member data be loaded?
440 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === TRUE)) {
441 // Validate password by created the difference of it and the secret key
442 $valPass = encodeHashForCookie(getUserData('password'));
444 // So did we now have valid data and an unlocked user?
445 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
446 // Transfer last module and online time
447 $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
448 $GLOBALS['last_online']['online'] = getUserData('last_online');
450 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
455 // Is $ret still false?
456 if ($ret === FALSE) {
457 // Yes, so destroy the session
458 destroyMemberSession();
462 $GLOBALS[__FUNCTION__] = $ret;
465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
469 // Fetch user data for given user id
470 function fetchUserData ($value, $column = 'userid') {
471 // Extension ext-user must be there at any case
472 if (!isExtensionActive('user')) {
473 // Absent ext-user is really not good
475 } elseif (is_null($value)) {
476 // This shall never happen, so please report it
477 reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
480 // If we should look for userid secure&set it here
481 if (substr($column, -2, 2) == 'id') {
483 $value = bigintval($value);
485 // Don't look for invalid userids...
486 if (!isValidId($value)) {
487 // Invalid, so abort here
488 reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
491 // Unset cached values if found and different
492 if ((isCurrentUserIdSet()) && (getCurrentUserId() != $value)) {
494 unsetCurrentUserId();
495 } elseif (isValidUserData()) {
496 // Use cache, so it is fine
497 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
500 } elseif (isValidUserData()) {
501 // Using cache is fine
502 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
506 // By default none was found
509 // Extra SQL statements
510 $ADD = runFilterChain('convert_user_data_columns', ' ');
512 // Query for the user
513 $result = sqlQueryEscaped("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
517 ), __FUNCTION__, __LINE__);
519 // Is there a record?
520 if (sqlNumRows($result) == 1) {
521 // Load data from cookies
522 $data = sqlFetchArray($result);
524 // Set the userid for later use
525 setCurrentUserId($data['userid']);
527 // And cache the data for this userid
528 $GLOBALS['user_data'][getCurrentUserId()] = $data;
530 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
531 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
532 // Backup the raw one and zero it
533 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
534 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
537 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
538 // Seperate data/time
539 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
541 // Seperate data and time again
542 $array['date'] = explode('-', $array[0]);
543 $array['time'] = explode(':', $array[1]);
545 // Now pass it to mktime()
546 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
558 $found = isValidUserData();
562 sqlFreeResult($result);
569 * Checks whether the current session bears a valid admin id and password hash.
571 * This patched function will reduce many SELECT queries for the current admin
574 function isAdmin () {
576 if (isset($GLOBALS[__FUNCTION__])) {
578 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isAdmin()=' . intval($GLOBALS[__FUNCTION__]));
579 return $GLOBALS[__FUNCTION__];
582 // No admin in installation phase!
583 if ((isInstaller()) || (!isAdminRegistered())) {
584 $GLOBALS[__FUNCTION__] = FALSE;
591 $passwordFromCookie = '';
592 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
594 // If admin login is not given take current from cookies...
595 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
596 // Get admin login and password from session/cookies
597 $adminId = getCurrentAdminId();
598 $passwordFromCookie = getAdminMd5();
600 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',passwordFromCookie=' . $passwordFromCookie);
602 // Abort if admin id is zero
603 if (($adminId == '0') || (empty($passwordFromCookie))) {
604 // A very noisy debug message ...
605 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
608 $GLOBALS[__FUNCTION__] = FALSE;
612 // Init it with failed
613 $GLOBALS[__FUNCTION__] = FALSE;
615 // Search in array for entry
616 if (isset($GLOBALS['admin_hash'])) {
618 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using admin_hash=' . $GLOBALS['admin_hash'] . ' from cache');
619 } elseif ((!empty($adminId)) && (!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === TRUE)) {
620 // Get admin hash and hash it
621 $GLOBALS['admin_hash'] = encodeHashForCookie(getAdminHash($adminId));
622 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valPass=' . $GLOBALS['admin_hash']);
625 incrementStatsEntry('cache_hits');
626 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === FALSE))) {
627 // Get admin hash and hash it
628 $GLOBALS['admin_hash'] = encodeHashForCookie(getAdminHash($adminId));
629 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valPass=' . $GLOBALS['admin_hash']);
632 // Check if password is valid
633 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $GLOBALS['admin_hash'] . '==' . $passwordFromCookie . ')='.intval($GLOBALS['admin_hash'] == $passwordFromCookie));
634 $GLOBALS[__FUNCTION__] = ((!empty($GLOBALS['admin_hash'])) && ($GLOBALS['admin_hash'] == $passwordFromCookie));
636 // Return result of comparision
637 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isAdmin()=' . intval($GLOBALS[__FUNCTION__]));
638 return $GLOBALS[__FUNCTION__];
641 // Generates a list of "max receiveable emails per day"
642 function addMaxReceiveList ($mode, $default = '') {
648 // Guests (in the registration form) are not allowed to select 0 mails per day.
649 $result = sqlQuery('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
650 __FUNCTION__, __LINE__);
655 // Members are allowed to set to zero mails per day (we will change this soon!)
656 $result = sqlQuery('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
657 __FUNCTION__, __LINE__);
661 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
665 // Some entries are found?
666 if (!ifSqlHasZeroNums($result)) {
668 while ($content = sqlFetchArray($result)) {
669 $OUT .= ' <option value="' . $content['value'] . '"';
671 if (postRequestElement('max_mails') == $content['value']) {
672 $OUT .= ' selected="selected"';
675 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
676 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
681 $OUT = loadTemplate(($mode . '_receive_table'), TRUE, $OUT);
683 // Maybe the admin has to setup some maximum values?
684 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
688 sqlFreeResult($result);
690 // Return generated HTML code
694 // Checks whether the given email address is used.
695 function isEmailTaken ($email) {
696 // Default is no userid
697 $useridSql = ' IS NOT NULL';
699 // Is a member logged in?
702 $useridSql = '!= ' . bigintval(getMemberId());
705 // Replace dot with {DOT}
706 $email = str_replace('.', '{DOT}', $email);
708 // Query the database
709 $result = sqlQueryEscaped("SELECT
710 COUNT(`userid`) AS `cnt`
712 `{?_MYSQL_PREFIX?}_user_data`
714 '%s' REGEXP `email` AND
720 ), __FUNCTION__, __LINE__);
722 // Is the email there?
723 list($count) = sqlFetchRow($result);
726 sqlFreeResult($result);
729 return ($count == 1);
732 // Validate the given menu action
733 function isMenuActionValid ($mode, $action, $what, $updateEntry = FALSE) {
734 // Is the cache entry there and we shall not update?
735 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === FALSE)) {
737 incrementStatsEntry('cache_hits');
739 // Then use this cache
740 return $GLOBALS['action_valid'][$mode][$action][$what];
743 // By default nothing is valid
746 // Look in all menus or only unlocked
748 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
750 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
751 if (($mode != 'admin') && ($updateEntry === TRUE)) {
752 // Update guest or member menu
753 $sql = sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
758 ), __FUNCTION__, __LINE__, FALSE);
759 } elseif (($what != 'welcome') && (!empty($what))) {
761 $sql = sqlQueryEscaped("SELECT `id`, `what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what`='%s'".$add." ORDER BY `action` DESC LIMIT 1",
766 ), __FUNCTION__, __LINE__, FALSE);
768 // Admin login overview
769 $sql = sqlQueryEscaped("SELECT `id`, `what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND (`what`='' OR `what` IS NULL)".$add." ORDER BY `action` DESC LIMIT 1",
773 ), __FUNCTION__, __LINE__, FALSE);
777 $result = sqlQuery($sql, __FUNCTION__, __LINE__);
779 // Should we look for affected rows (only update) or found rows?
780 if ($updateEntry === TRUE) {
781 // Check updated/affected rows
782 $ret = (!ifSqlHasZeroAffectedRows());
785 $ret = (!ifSqlHasZeroNums($result));
789 sqlFreeResult($result);
792 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
798 // Get action value from mode (admin/guest/member) and what-value
799 function getActionFromModuleWhat ($module, $what) {
800 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
802 $data['action'] = '';
804 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
805 // ext-sql_patches is missing so choose depending on mode
806 $what = determineWhat($module);
807 } elseif ((empty($what)) && ($module != 'admin')) {
808 // Use configured 'home'
809 $what = getIndexHome();
812 if ($module == 'admin') {
813 // Action value for admin area
814 if (isGetRequestElementSet('action')) {
816 return getRequestElement('action');
817 } elseif (isActionSet()) {
818 // Get it directly from URL
820 } elseif (($what == 'welcome') || (!isWhatSet())) {
821 // Default value for admin area
822 $data['action'] = 'login';
824 } elseif (isActionSet()) {
825 // Get it directly from URL
828 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
830 // Does the module have a menu?
831 if (ifModuleHasMenu($module)) {
832 // Rewriting modules to menu
833 $module = mapModuleToTable($module);
835 // Guest and member menu is 'main' as the default
836 if (empty($data['action'])) {
837 $data['action'] = 'main';
840 // Load from database
841 $result = sqlQueryEscaped("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
845 ), __FUNCTION__, __LINE__);
848 if (sqlNumRows($result) == 1) {
849 // Load action value and pray that this one is the right you want... ;-)
850 $data = sqlFetchArray($result);
854 sqlFreeResult($result);
855 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
856 // No ext-sql_patches installed, but maybe we need to register an admin?
857 if (isAdminRegistered()) {
858 // Redirect to admin area
859 redirectToUrl('admin.php');
863 // Return action value
864 return $data['action'];
867 // Get category name back
868 function getCategory ($cid) {
869 // Default is not found
870 $data['cat'] = '{--_CATEGORY_404--}';
872 // Is the category id set?
873 if (!isValidId($cid)) {
875 $data['cat'] = '{--_CATEGORY_NONE--}';
876 } elseif (isValidId($cid)) {
877 // Lookup the category in database
878 $result = sqlQueryEscaped('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
879 array(bigintval($cid)), __FUNCTION__, __LINE__);
880 if (sqlNumRows($result) == 1) {
881 // Category found... :-)
882 $data = sqlFetchArray($result);
886 sqlFreeResult($result);
893 // Get a string of "mail title" and price back
894 function getPaymentTitlePrice ($paymentsId, $full = FALSE) {
895 // Only title or also including price?
896 if ($full === FALSE) {
897 $ret = getPaymentData($paymentsId, 'main_title');
899 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
907 function getPaymentPrice ($paymentsId) {
909 return getPaymentData($paymentsId, 'price');
913 function getPaymentTime ($paymentsId) {
915 return getPaymentData($paymentsId, 'time');
918 // Get payment 'payment'
919 function getPaymentPayment ($paymentsId) {
921 return getPaymentData($paymentsId, 'payment');
924 // "Getter" for payment data (cached)
925 function getPaymentData ($paymentsId, $lookFor) {
927 $data[$lookFor] = NULL;
930 if (isset($GLOBALS['cache_array']['payments'][$lookFor][$paymentsId])) {
931 // Use it if found to save SQL queries
932 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$paymentsId];
935 incrementStatsEntry('cache_hits');
936 } elseif (!isExtensionActive('cache')) {
937 // Search for it in database
938 $result = sqlQueryEscaped('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
941 bigintval($paymentsId)
942 ), __FUNCTION__, __LINE__);
944 // Is the entry there?
945 if (sqlNumRows($result) == 1) {
946 // Payment type found... :-)
947 $data = sqlFetchArray($result);
951 sqlFreeResult($result);
955 return $data[$lookFor];
958 // Remove a receiver's id from $receivers and add a link for him to confirm
959 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = FALSE) {
960 // Default is not removed
963 // Is the userid valid?
964 if (isValidId($userid)) {
965 // Remove entry from array
966 unset($receivers[$key]);
968 // Is there already a line for this user available?
969 if (isValidId($statsId)) {
970 // Default is 'normal' mail
972 $rowName = 'stats_id';
974 // Only when we got a real stats id continue searching for the entry
975 if ($isBonusMail === TRUE) {
977 $rowName = 'bonus_id';
980 // Try to look the entry up
981 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
987 ), __FUNCTION__, __LINE__);
989 // Was it *not* found?
990 if (ifSqlHasZeroNums($result)) {
992 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES (%s,%s,'%s')",
998 ), __FUNCTION__, __LINE__);
1000 // Update 'mails_sent' if ext-sql_patches is updated
1001 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
1003 updatePoolDataById($poolId, 'mails_sent', 1, '+');
1012 sqlFreeResult($result);
1016 // Return status for sending routine
1020 // Calculate sum (default) or count records of given criteria
1021 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = FALSE, $add = '', $mode = '=') {
1023 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
1024 if ((empty($search)) && (!is_null($search))) {
1025 // Count or sum whole table?
1026 if ($countRows === TRUE) {
1027 // Count whole table
1028 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1029 $result = sqlQueryEscaped('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1033 ), __FUNCTION__, __LINE__);
1036 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1037 $result = sqlQueryEscaped('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1041 ), __FUNCTION__, __LINE__);
1043 } elseif (($countRows === TRUE) || ($lookFor == 'userid')) {
1045 if (is_null($search)) {
1049 } elseif ($mode == '!=') {
1054 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT-NULL!');
1055 $result = sqlQueryEscaped("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE (`%s` %s NULL OR `%s`=0)" . $add . ' LIMIT 1',
1062 ), __FUNCTION__, __LINE__);
1065 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1066 $result = sqlQueryEscaped("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1073 ), __FUNCTION__, __LINE__);
1077 if (is_null($search)) {
1081 } elseif ($mode == '!=') {
1086 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM-NULL!');
1087 $result = sqlQueryEscaped("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE (`%s` %s NULL OR `%s`=0)" . $add . ' LIMIT 1',
1094 ), __FUNCTION__, __LINE__);
1097 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1098 $result = sqlQueryEscaped("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1105 ), __FUNCTION__, __LINE__);
1110 $data = sqlFetchArray($result);
1113 sqlFreeResult($result);
1116 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1118 $data['res'] = '0.00000';
1119 } elseif ('' . $data['res'] . '' == '') {
1125 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1126 return $data['res'];
1130 * Sends out mail to all administrators. This function is no longer obsolete
1131 * because we need it when there is no ext-admins installed
1133 function sendAdminEmails ($subject, $message, $isBugReport = FALSE) {
1134 // Default is no special header
1137 // Is it a bug report?
1138 if ($isBugReport === TRUE) {
1139 // Then add a reply-to line back to the author (me)
1140 $mailHeader = 'Reply-To: webmaster@mxchange.org' . PHP_EOL;
1143 // Load all admin email addresses
1144 $result = sqlQuery('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1146 // And send the notification to all of them
1147 while ($content = sqlFetchArray($result)) {
1148 // Send the email out
1149 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1153 sqlFreeResult($result);
1155 // Really simple... ;-)
1158 // Get id number from administrator's login name
1159 function getAdminId ($adminLogin) {
1160 // By default no admin is found
1164 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1165 // Use it if found to save SQL queries
1166 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1168 // Update cache hits
1169 incrementStatsEntry('cache_hits');
1170 } elseif (!isExtensionActive('cache')) {
1171 // Load from database
1172 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1173 array($adminLogin), __FUNCTION__, __LINE__);
1175 // Is there an entry?
1176 if (sqlNumRows($result) == 1) {
1178 $data = sqlFetchArray($result);
1182 sqlFreeResult($result);
1189 // "Getter" for current admin id
1190 function getCurrentAdminId () {
1191 // Log debug message
1192 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1195 if (!isset($GLOBALS['current_admin_id'])) {
1196 // Get the admin login from session
1197 $adminId = getSession('admin_id');
1199 // Remember in cache securely
1200 setCurrentAdminId(bigintval($adminId));
1204 return $GLOBALS['current_admin_id'];
1207 // Setter for current admin id
1208 function setCurrentAdminId ($currentAdminId) {
1210 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1213 // Get password hash from administrator's login name
1214 function getAdminHash ($adminId) {
1215 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ' - ENTERED!');
1216 // By default an invalid hash is returned
1217 $data['password'] = -1;
1219 // Is admin hash set?
1220 if (isAdminHashSet($adminId)) {
1222 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1224 // Update cache hits
1225 incrementStatsEntry('cache_hits');
1226 } elseif (!isExtensionActive('cache')) {
1227 // Load from database
1228 $result = sqlQueryEscaped("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1229 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1231 // Is there an entry?
1232 if (sqlNumRows($result) == 1) {
1234 $data = sqlFetchArray($result);
1237 setAdminHash($adminId, $data['password']);
1241 sqlFreeResult($result);
1244 // Return password hash
1245 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',data[password]=' . $data['password'] . ' - EXIT!');
1246 return $data['password'];
1249 // "Getter" for admin login
1250 function getAdminLogin ($adminId) {
1251 // By default a non-existent login is returned (other functions react on this!)
1252 $data['login'] = '***';
1254 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1256 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1258 // Update cache hits
1259 incrementStatsEntry('cache_hits');
1260 } elseif (!isExtensionActive('cache')) {
1261 // Load from database
1262 $result = sqlQueryEscaped("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1263 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1266 if (sqlNumRows($result) == 1) {
1268 $data = sqlFetchArray($result);
1271 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1275 sqlFreeResult($result);
1278 // Return the result
1279 return $data['login'];
1282 // Get email address of admin id
1283 function getAdminEmail ($adminId) {
1284 // By default an invalid emails is returned
1285 $data['email'] = '***';
1287 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1289 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1291 // Update cache hits
1292 incrementStatsEntry('cache_hits');
1293 } elseif (!isExtensionActive('cache')) {
1294 // Load from database
1295 $result_admin_id = sqlQueryEscaped("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1296 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1299 if (sqlNumRows($result_admin_id) == 1) {
1301 $data = sqlFetchArray($result_admin_id);
1304 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1308 sqlFreeResult($result_admin_id);
1312 return $data['email'];
1315 // Get default ACL of admin id
1316 function getAdminDefaultAcl ($adminId) {
1317 // By default an invalid ACL value is returned
1318 $data['default_acl'] = 'NO-ACL';
1320 // Is ext-sql_patches there and was it found in cache?
1321 if (!isExtensionActive('sql_patches')) {
1322 // Not found, which is bad, so we need to allow all
1323 $data['default_acl'] = 'allow';
1324 } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1326 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1328 // Update cache hits
1329 incrementStatsEntry('cache_hits');
1330 } elseif (!isExtensionActive('cache')) {
1331 // Load from database
1332 $result_admin_id = sqlQueryEscaped("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1333 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1335 // Is there an entry?
1336 if (sqlNumRows($result_admin_id) == 1) {
1338 $data = sqlFetchArray($result_admin_id);
1341 $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1345 sqlFreeResult($result_admin_id);
1348 // Return default ACL
1349 return $data['default_acl'];
1352 // Get menu mode (la_mode) of admin id
1353 function getAdminMenuMode ($adminId) {
1354 // By default an invalid mode
1355 $data['la_mode'] = 'INVALID';
1357 // Is ext-sql_patches there and was it found in cache?
1358 if (!isExtensionActive('sql_patches')) {
1359 // Not found, which is bad, so we need to allow all
1360 $data['la_mode'] = 'global';
1361 } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1363 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1365 // Update cache hits
1366 incrementStatsEntry('cache_hits');
1367 } elseif (!isExtensionActive('cache')) {
1368 // Load from database
1369 $result_admin_id = sqlQueryEscaped("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1370 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1372 // Is there an entry?
1373 if (sqlNumRows($result_admin_id) == 1) {
1375 $data = sqlFetchArray($result_admin_id);
1378 $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1382 sqlFreeResult($result_admin_id);
1385 // Return default ACL
1386 return $data['la_mode'];
1389 // Generates an option list from various parameters
1390 function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '') {
1392 if ($table == '/ARRAY/') {
1393 // Selection from array
1394 if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
1396 foreach ($key as $idx => $optionValue) {
1397 $ret .= '<option value="' . $optionValue . '"';
1398 if ($default == $optionValue) {
1399 // Selected by default
1400 $ret .= ' selected="selected"';
1401 } elseif (isset($disabled[$optionValue])) {
1403 $ret .= ' disabled="disabled"';
1406 // Is the call-back function set?
1407 if (!empty($callback)) {
1409 $value[$idx] = call_user_func_array($callback, array($key[$idx]));
1412 // Finish option tag
1413 $ret .= '>' . $value[$idx] . '</option>';
1416 // Problem in request
1417 reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: key[' . count($key) . ']=' . gettype($key) . ',value[' . count($value) . ']=' . gettype($value) . ',callback=' . $callback);
1420 ///////////////////////
1421 // Data from database /
1422 ///////////////////////
1424 // Init extra column (if requested)
1426 if (!empty($extra)) {
1427 $extraColumn = ',`' . $extra . '` AS `extra`';
1431 $result = sqlQueryEscaped("SELECT `%s` AS `key`, `%s` AS `value`" . $extraColumn . " FROM `{?_MYSQL_PREFIX?}_%s` " . $whereStatement . " ORDER BY `%s` ASC",
1437 ), __FUNCTION__, __LINE__);
1440 if (!ifSqlHasZeroNums($result)) {
1441 // Found data so add them as OPTION lines
1442 while ($content = sqlFetchArray($result)) {
1444 if (!isset($content['extra'])) {
1446 $content['extra'] = '';
1449 $ret .= '<option value="' . $content['key'] . '"';
1451 if ($default == $content['key']) {
1452 // Selected by default
1453 $ret .= ' selected="selected"';
1454 } elseif (isset($disabled[$content['key']])) {
1456 $ret .= ' disabled="disabled"';
1460 if (!empty($content['extra'])) {
1461 $content['extra'] = ' (' . $content['extra'] . ')';
1464 // Is the call-back function set?
1465 if (!empty($callback)) {
1467 $content['value'] = call_user_func_array($callback, array($content['value']));
1470 // Finish option list
1471 $ret .= '>' . $content['value'] . $content['extra'] . '</option>';
1475 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1479 sqlFreeResult($result);
1482 // Return - hopefully - the requested data
1486 // Deletes a user account with given reason
1487 function deleteUserAccount ($userid, $reason) {
1489 $data['points'] = '0';
1491 // Search for the points and user data
1492 $result = sqlQueryEscaped("SELECT
1493 (SUM(`p`.`points`) - `d`.`used_points`) AS `points`
1495 `{?_MYSQL_PREFIX?}_user_points` AS `p`
1497 `{?_MYSQL_PREFIX?}_user_data` AS `d`
1499 `p`.`userid`=`d`.`userid`
1503 array(bigintval($userid)), __FUNCTION__, __LINE__);
1505 // Is there an entry?
1506 if (sqlNumRows($result) == 1) {
1507 // Save his points to add them to the jackpot
1508 $data = sqlFetchArray($result);
1510 // Delete points entries as well
1511 // @TODO Rewrite these lines to a filter
1512 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1513 array(bigintval($userid)), __FUNCTION__, __LINE__);
1515 // Update mediadata as well
1516 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1518 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1521 // Now, when we have all his points adds them do the jackpot!
1522 if (isExtensionActive('jackpot')) {
1523 addPointsToJackpot($data['points']);
1528 sqlFreeResult($result);
1530 // Delete category selections as well...
1531 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1532 array(bigintval($userid)), __FUNCTION__, __LINE__);
1534 // Remove from rallye if found
1535 // @TODO Rewrite this to a filter
1536 if (isExtensionActive('rallye')) {
1537 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1538 array(bigintval($userid)), __FUNCTION__, __LINE__);
1541 // Add reason and translate points
1542 $data['text'] = $reason;
1544 // Now a mail to the user and that's all...
1545 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1546 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1548 // Ok, delete the account!
1549 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1552 // Gets the matching what name from module
1553 function getWhatFromModule ($modCheck) {
1554 // Is the request element set?
1555 if (isGetRequestElementSet('what')) {
1556 // Then return this!
1557 return getRequestElement('what');
1563 // Check on given module
1564 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1565 switch ($modCheck) {
1566 case 'index': // Guest area
1567 // Is ext-sql_patches installed and newer than 0.0.5?
1568 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1569 // Use it from config
1570 $what = getIndexHome();
1572 // Use default 'welcome'
1577 default: // Default for all other menus (getIndexHome() is for index module only)
1582 // Return what value
1586 // Returns HTML code with an option list of all categories
1587 function generateCategoryOptionsList ($mode, $userid = NULL) {
1588 // Prepare WHERE statement
1589 $whereStatement = " WHERE `visible`='Y'";
1590 if (isAdmin()) $whereStatement = '';
1592 // Initialize array...
1593 $categories = array(
1596 'userids' => array()
1600 $result = sqlQuery('SELECT
1604 `{?_MYSQL_PREFIX?}_cats`
1605 ' . $whereStatement . '
1608 __FUNCTION__, __LINE__);
1610 // Are there entries?
1611 if (!ifSqlHasZeroNums($result)) {
1612 // ... and begin loading stuff
1613 while ($content = sqlFetchArray($result)) {
1614 // Transfer some data
1615 $categories['id'][] = $content['id'];
1616 array_push($categories['name'], $content['cat']);
1618 // Check which users are in this category
1619 $result_userids = sqlQueryEscaped("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1621 bigintval($content['id']),
1622 convertNullToZero($userid)
1623 ), __FUNCTION__, __LINE__);
1629 while ($data = sqlFetchArray($result_userids)) {
1631 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', TRUE, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1635 sqlFreeResult($result_userids);
1638 array_push($categories['userids'], $userid_cnt);
1642 sqlFreeResult($result);
1646 foreach ($categories['id'] as $key => $value) {
1647 $OUT .= ' <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1650 // No cateogries are defined yet
1651 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1658 // Add bonus mail to queue
1659 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1660 // Is admin or bonus extension there?
1664 } elseif (!isExtensionActive('bonus')) {
1669 // Calculcate target sent
1670 $target = countSelection(explode(';', $receiverList));
1672 // Receiver is zero?
1673 if ($receiver == '0') {
1675 $receiver = $target;
1678 // HTML extension active?
1679 if (isExtensionActive('html_mail')) {
1681 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1713 bigintval($seconds),
1715 bigintval($categoryId),
1717 bigintval($receiver),
1718 convertBooleanToYesNo($mode == 'html')
1719 ), __FUNCTION__, __LINE__);
1722 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1752 bigintval($seconds),
1754 bigintval($categoryId),
1756 bigintval($receiver),
1757 ), __FUNCTION__, __LINE__);
1761 // Generate a receiver list for given category and maximum receivers
1762 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1769 $categoryId = bigintval($categoryId);
1770 $receiver = bigintval($receiver);
1772 // Is the receiver zero and mode set?
1773 if (($receiver == '0') && (!empty($mode))) {
1774 // Auto-fix receiver maximum
1775 $receiver = getTotalReceivers($mode);
1778 // Exclude (maybe exclude) testers
1779 $addWhere = runFilterChain('user_exclusion_sql', ' ');
1782 if (isValidId($categoryId)) {
1784 $extraColumns = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS `c` ON `d`.`userid`=`c`.`userid`";
1785 $addWhere = sprintf(" AND `c`.`cat_id`=%s", $categoryId);
1788 // Exclude users in holiday?
1789 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1790 // Add something for the holiday extension
1791 $addWhere .= " AND `d`.`holiday_active`='N'";
1794 // Include only HTML recipients?
1795 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1796 $addWhere .= " AND `d`.`html`='Y'";
1800 $result = sqlQueryEscaped("SELECT
1803 `{?_MYSQL_PREFIX?}_user_data` AS `d`
1804 " . $extraColumns . "
1806 `d`.`status`='CONFIRMED'
1809 `d`.`{?order_select?}` {?order_mode?}
1813 ), __FUNCTION__, __LINE__);
1816 if ((sqlNumRows($result) >= $receiver) && ($receiver > 0)) {
1818 while ($content = sqlFetchArray($result)) {
1819 // Add receiver when not empty
1820 if (!empty($content['userid'])) {
1821 $receiverList .= $content['userid'] . ';';
1826 sqlFreeResult($result);
1828 // Remove trailing semicolon
1829 $receiverList = substr($receiverList, 0, -1);
1833 return $receiverList;
1836 // Recuce the amount of received emails for the receipients for given email
1837 function reduceRecipientReceivedMails ($column, $id, $count) {
1838 // Search for mail in database
1839 $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1844 ), __FUNCTION__, __LINE__
1847 // Are there entries?
1848 if (!ifSqlHasZeroNums($result)) {
1849 // Now load all userids for one big query!
1851 while ($data = sqlFetchArray($result)) {
1852 // By default reduce and found no emails
1855 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1856 // @TODO Rewrite this to a filter
1857 if ((isset($data['stats_id'])) && (isValidId($data['stats_id']))) {
1859 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1860 } elseif ((isset($data['bonus_id'])) && (isValidId($data['bonus_id']))) {
1862 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1865 // Reduce this users total received emails?
1867 $userids[$data['userid']] = $data['userid'];
1871 if (isFilledArray($userids)) {
1872 // Now update all user accounts
1873 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1875 implode(',', $userids),
1877 ), __FUNCTION__, __LINE__);
1880 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1885 sqlFreeResult($result);
1888 // Creates a new task
1889 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = TRUE) {
1890 // Insert the task data into the database
1891 sqlQueryEscaped("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())",
1893 convertZeroToNull($adminId),
1894 convertZeroToNull($userid),
1898 ), __FUNCTION__, __LINE__, TRUE, $strip);
1900 // Return insert id which is the task id
1901 return getSqlInsertId();
1904 // Updates last module / online time
1905 function updateLastActivity ($userid) {
1908 // Run the update query
1909 sqlQueryEscaped("UPDATE
1910 `{?_MYSQL_PREFIX?}_user_data`
1912 `{%%pipe,getUserLastWhatName%%}`='{%%pipe,getWhat%%}',
1913 `last_online`=UNIX_TIMESTAMP(),
1914 `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1920 ), __FUNCTION__, __LINE__);
1922 // No what set, needs to be ignored (last_module is last_what)
1923 sqlQueryEscaped("UPDATE
1924 `{?_MYSQL_PREFIX?}_user_data`
1926 `{%%pipe,getUserLastWhatName%%}`=NULL,
1927 `last_online`=UNIX_TIMESTAMP(),
1928 `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1934 ), __FUNCTION__, __LINE__);
1938 // List all given joined rows (callback function from XML)
1939 function doGenericJoinedListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1940 // Verify that tableName and columns are not empty
1941 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1942 // No tableName specified
1943 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1944 } elseif (!isFilledArray($columns)) {
1945 // No columns specified
1946 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1949 // This is the minimum query, so at least columns and tableName must have entries
1952 // Get the sql part back from given array
1953 $sql .= getSqlPartFromXmlArray($columns);
1956 $sql .= getSqlXmlFromTable($tableName);
1959 $sql .= getSqlXmlJoinedTable($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable);
1962 $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
1965 $sql .= getSqlXmlOrderBy($orderByColumns);
1967 // Now handle all over to the inner function which will execute the listing
1968 doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
1971 // List all given rows (callback function from XML)
1972 function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1973 // Verify that tableName and columns are not empty
1974 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1975 // No tableName specified
1976 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1977 } elseif (!isFilledArray($columns)) {
1978 // No columns specified
1979 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1982 // This is the minimum query, so at least columns and tableName must have entries
1985 // Get the sql part back from given array
1986 $sql .= getSqlPartFromXmlArray($columns);
1989 $sql .= getSqlXmlFromTable($tableName);
1992 $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
1995 $sql .= getSqlXmlOrderBy($orderByColumns);
1997 // Now handle all over to the inner function which will execute the listing
1998 doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
2001 // Do the listing of entries
2002 function doListEntries ($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array(), $content = array()) {
2003 // Run the SQL query
2004 $result = sqlQuery($sql, __FUNCTION__, __LINE__);
2006 // Are there some URLs left?
2007 if (!ifSqlHasZeroNums($result)) {
2010 while ($row = sqlFetchArray($result)) {
2011 // "Translate" content
2012 foreach ($callbackColumns as $columnName => $callbackName) {
2013 // Fill the callback arguments
2014 $args = array($row[$columnName]);
2016 // Is there more to add?
2017 if (isset($extraParameters[$columnName])) {
2019 $args = merge_array($args, $extraParameters[$columnName]);
2022 // Call the callback-function
2023 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, TRUE).'</pre>');
2024 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
2025 $row[$columnName] = call_user_func_array($callbackName, $args);
2028 // Load row template
2029 $OUT .= loadTemplate(trim($rowTemplate[0]), TRUE, $row);
2032 // Is at least one entry set in content?
2033 if (isFilledArray($content)) {
2034 // Then add generic 'rows' element
2035 $content['rows'] = $OUT;
2037 // Direct output is content
2041 // Load main template
2042 loadTemplate(trim($tableTemplate[0]), FALSE, $content);
2044 // No URLs in surfbar
2045 displayMessage('{--' .$noEntryMessageId[0] . '--}');
2049 sqlFreeResult($result);
2052 // Adds a given entry to the database
2053 function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2054 //* DEBUG: */ die(__FUNCTION__.':columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,timeColumns=<pre>'.print_r($timeColumns,TRUE).'</pre>,columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>,POST=<pre>'.print_r($_POST,TRUE).'</pre>');
2055 // Verify that tableName and columns are not empty
2056 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2057 // No tableName specified
2058 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2059 } elseif (!isFilledArray($columns)) {
2060 // No columns specified
2061 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
2064 // Init columns and value elements
2065 $sqlColumns = array();
2066 $sqlValues = array();
2068 // Default is that all went fine
2069 $GLOBALS['__XML_PARSE_RESULT'] = TRUE;
2071 // Is there "time columns"?
2072 if (isFilledArray($timeColumns)) {
2073 // Then "walk" through all entries
2074 foreach ($timeColumns as $column) {
2075 // Convert all (possible) selections
2076 convertSelectionsToEpocheTimeInPostData($column . '_ye');
2080 // Add columns and values
2081 foreach ($columns as $key => $columnName) {
2082 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
2083 // Is columnIndex set?
2084 if (!is_null($columnIndex)) {
2086 //* DEBUG: */ die('columnName=<pre>'.print_r($columnName,TRUE).'</pre>columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>'.debug_get_printable_backtrace());
2087 assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
2089 // Then use that index "blindly"
2090 $columnName = $columnName[$columnIndex];
2094 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName[' . gettype($columnName) . ']=' . $columnName . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . intval(isset($extraValues[$key])) . ',extraValuesName=' . intval(isset($extraValues[$columnName . '_list'])));
2096 // Get value back (no array supported)
2097 $value = postRequestElement($columnName);
2099 // Is this an array and element 0 is set?
2100 if ((is_array($value)) && (isset($value[0]))) {
2101 // Then only take this
2105 // Copy entry securely to the final arrays
2106 $sqlColumns[$key] = sqlEscapeString($columnName);
2107 $sqlValues[$key] = sqlEscapeString($value);
2110 $search = key(search_array($columns, 'column', $columnName));
2112 // Try to handle call-back functions and/or extra values on the list
2113 //* DEBUG: */ outputHtml($key . '/' . $columnName . '=<pre>'.print_r($columns,true).'</pre>search_array()=<pre>'.print_r(search_array($columns, 'column', $columnName), TRUE).'</pre>');
2114 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
2115 if (is_string($key)) {
2117 $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key . '_list', $sqlValues[$key], array(''), $search);
2120 $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key, $sqlValues[$key], array(''), $search);
2123 // Is the value not a number?
2124 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
2125 if (($sqlValues[$key] != 'NULL') && (is_string($sqlValues[$key]))) {
2126 // Add quotes around it
2127 $sqlValues[$key] = chr(39) . $sqlValues[$key] . chr(39);
2130 // Is the value false?
2131 if ($sqlValues[$key] === FALSE) {
2132 // One "parser" didn't like it
2133 $GLOBALS['__XML_PARSE_RESULT'] = FALSE;
2138 // If all values are okay, continue
2139 if ($sqlValues[$key] !== FALSE) {
2140 // Build the SQL query
2141 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`, `', $sqlColumns) . "`) VALUES (" . implode(',', $sqlValues) . ')';
2143 // Run the SQL query
2144 sqlQuery($sql, __FUNCTION__, __LINE__);
2147 setPostRequestElement('id', getSqlInsertId());
2149 // Prepare filter data array
2150 $filterData = array(
2152 'table_name' => $tableName,
2153 'content' => postRequestArray(),
2154 'id' => getSqlInsertId(),
2156 // @TODO Used generic 'userid' here
2157 'userid_column' => array('userid'),
2158 'raw_userid' => array('userid'),
2159 'affected' => sqlAffectedRows(),
2163 // Send "build mail" out
2164 runFilterChain('send_build_mail', $filterData);
2168 // Edit rows by given id numbers
2169 function doGenericEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $subject = '') {
2170 // Is there "time columns"?
2171 if (isFilledArray($timeColumns)) {
2172 // Then "walk" through all entries
2173 foreach ($timeColumns as $column) {
2174 // Convert all (possible) selections
2175 convertSelectionsToEpocheTimeInPostData($column . '_ye');
2181 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2183 $id = bigintval($id);
2185 // Prepare content array (new values)
2188 // Prepare SQL for this row
2189 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
2190 sqlEscapeString($tableName[0])
2193 // "Walk" through all entries
2194 foreach (postRequestArray() as $key => $entries) {
2195 // Skip raw userid which is always invalid
2196 if (($key == $rawUserId[0]) || ($key == ($rawUserId[0] . '_raw')) || ($key == 'do_edit')) {
2197 // Continue with next field
2198 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
2203 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',id=' . $id . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,TRUE).'</pre>');
2205 // Is entries an array?
2206 if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
2207 // Search for the right array index
2208 $search = key(search_array($columns, 'column', $key));
2210 // Add this entry to content
2211 $content[$key] = $entries[$id];
2214 //* BUG: */ die($key.'/'.$id.'/'.$search.'=<pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre>');
2216 // Handle possible call-back functions and/or extra values
2217 $entries[$id] = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries[$id], $userIdColumn, $search);
2219 // Add key/value pair to SQL string
2220 $sql .= addKeyValueSql($key, $entries[$id]);
2221 } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
2223 $search = key(search_array($columns, 'column', $key));
2224 //* BUG: */ die($key.'/<pre>'.print_r($search, TRUE).'</pre>=<pre>'.print_r($columns, TRUE).'</pre>');
2227 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - BEFORE!');
2229 // Add normal entries as well
2230 $content[$key] = $entries;
2232 // Handle possible call-back functions and/or extra values
2233 $entries = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search);
2236 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - AFTER!');
2238 // Add key/value pair to SQL string
2239 $sql .= addKeyValueSql($key, $entries);
2243 // Finish SQL command
2244 $sql = substr($sql, 0, -1) . " WHERE `" . sqlEscapeString($idColumn[0]) . "`=" . $id;
2245 if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2246 // Add user id as well
2247 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2252 //* BUG: */ die($sql.'<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
2253 sqlQuery($sql, __FUNCTION__, __LINE__);
2255 // Add affected rows
2256 $edited = sqlAffectedRows();
2257 $affected += $edited;
2259 // Load all data from that id
2260 $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2265 ), __FUNCTION__, __LINE__);
2267 // Fetch the data and merge it into $content
2268 $content = merge_array($content, sqlFetchArray($result));
2270 // Prepare filter data array
2271 $filterData = array(
2273 'table_name' => $tableName,
2274 'content' => $content,
2276 'subject' => $subject,
2277 'userid_column' => $userIdColumn,
2278 'raw_userid' => $rawUserId,
2279 'affected' => $edited,
2283 // Send "build mail" out
2284 runFilterChain('send_build_mail', $filterData);
2287 sqlFreeResult($result);
2291 if ((isFilledArray($cacheFiles)) && (!empty($cacheFiles[0]))) {
2292 // Delete cache file(s)
2293 foreach ($cacheFiles as $cache) {
2294 // Skip any empty entries
2295 if (empty($cache)) {
2296 // This may cause trouble in loadCacheFile()
2300 // Use rebuildCache() to delete it
2301 rebuildCache($cache);
2305 // Return affected rows
2309 // Delete rows by given id numbers
2310 function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2311 // The base SQL command:
2312 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
2314 // Is a user id provided?
2315 //* BUG: */ die('<pre>'.print_r($rawUserId,TRUE).'</pre><pre>'.print_r($userIdColumn,TRUE).'</pre>');
2316 if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2317 // Add user id as well
2318 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2321 // $idColumn[0] in POST must be an array again
2322 if (!is_array(postRequestElement($idColumn[0]))) {
2323 // This indicates that you have conflicting form field naming with XML names
2324 reportBug(__FUNCTION__, __LINE__, 'You have a wrong form field element, idColumn[0]=' . $idColumn[0]);
2328 //* BUG: */ die($sql.'<pre>'.print_r($tableName,TRUE).'</pre><pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre><pre>'.print_r($extraValues,TRUE).'</pre><pre>'.print_r($deleteNow,TRUE).'</pre><pre>'.print_r($idColumn,TRUE).'</pre>');
2330 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2332 if (!isValidId($id)) {
2337 // Is there a userid?
2338 if (isPostRequestElementSet($userIdColumn[0])) {
2339 // Load all data from that id
2340 $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2345 ), __FUNCTION__, __LINE__);
2348 $content = sqlFetchArray($result);
2351 sqlFreeResult($result);
2353 // Send "build mails" out
2354 sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
2358 $idList .= $id . ',';
2362 sqlQueryEscaped($sql,
2366 convertNullToZero(substr($idList, 0, -1))
2367 ), __FUNCTION__, __LINE__);
2369 // Return affected rows
2370 return sqlAffectedRows();
2373 // Build a special template list
2374 // @TODO cacheFiles is not yet supported
2375 function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2376 // $tableName and $idColumn must bove be arrays!
2377 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2378 // $tableName is no array
2379 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2380 } elseif (!is_array($idColumn)) {
2381 // $idColumn is no array
2382 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2383 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
2384 // $tableName is no array
2385 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2391 // "Walk" through all entries
2392 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'listType=<pre>'.print_r($listType,TRUE).'</pre>,tableName<pre>'.print_r($tableName,TRUE).'</pre>,columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,idColumn=<pre>'.print_r($idColumn,TRUE).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,TRUE).'</pre>,rawUserId=<pre>'.print_r($rawUserId,TRUE).'</pre>');
2393 foreach (postRequestElement($idColumn[0]) as $id => $selected) {
2395 $id = bigintval($id);
2397 // Get result from a given column array and table name
2398 $result = getSqlResultFromArray($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
2400 // Is there one entry?
2401 if (sqlNumRows($result) == 1) {
2403 $row = sqlFetchArray($result);
2406 foreach ($row as $key => $value) {
2408 $idx = searchXmlArray($key, $columns, 'column');
2410 // Default name is NULL
2413 // Is the name there?
2414 if (isset($columns[$idx]['name'])) {
2416 $name = $columns[$idx]['name'];
2419 // Skip any missing entries
2420 if ($idx === FALSE) {
2422 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
2426 // Is there a userid?
2427 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2428 if ($key == $userIdColumn[0]) {
2429 // Add it again as raw id
2430 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2431 $row[$userIdColumn[0]] = convertZeroToNull($value);
2432 $row[$userIdColumn[0] . '_raw'] = $row[$userIdColumn[0]];
2435 // If the key matches the idColumn variable, we need to temporary remember it
2436 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
2437 if ($key == $idColumn[0]) {
2439 * Found, so remember it securely (to make sure only id
2440 * numbers can pass, don't use alpha-numerical values!)
2442 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
2443 $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
2446 // Try to handle call-back functions and/or extra values
2447 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',row[' . $key . ']=' . $row[$key]);
2448 //if ($key == 'forced_campaign_created') die($idx.'=<pre>'.print_r($columns,true).'</pre><pre>'.print_r($extraValues,true).'</pre>');
2449 $row[$key] = doHandleExtraValues($filterFunctions, $extraValues, $idx, $row[$key], $userIdColumn, ((!is_null($name)) ? $name : $key), $id);
2453 $OUT .= loadTemplate(sprintf('%s_%s_%s_row',
2462 sqlFreeResult($result);
2465 // Is there an entry in $content?
2466 if (isFilledArray($content)) {
2467 // Use generic 'rows'
2468 $content['rows'] = $OUT;
2470 // Use direct output
2474 // Load master template
2484 // Adds key/value pair to a working SQL string together
2485 function addKeyValueSql ($key, $value) {
2490 if (($value == 'NULL') || (is_null($value))) {
2491 // Add key with NULL
2492 $sql .= sprintf(' `%s`=NULL,',
2493 sqlEscapeString($key)
2495 } elseif ((is_double($value)) || (is_float($value)) || (is_int($value))) {
2496 // Is a number, so addd it directly
2497 $sql .= sprintf(' `%s`=%s,',
2498 sqlEscapeString($key),
2502 // Else add the value escape'd
2503 $sql .= sprintf(" `%s`='%s',",
2504 sqlEscapeString($key),
2505 sqlEscapeString($value)
2509 // Return SQL string