\n";
- $NAV_DEPTH = "0";
-
- // Run the filter chain
- $ret = RUN_FILTER('post_youhere_line', array('access_level' => $ACC_LVL, 'type' => $type, 'content' => ""));
- $OUT .= $ret['content'];
- } // END - if
- }
} // END - if
- // Free result
- SQL_FREERESULT($result);
+ // Is ext-sql_patches installed?
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isExtensionInstalledAndNewer()=' . intval(isExtensionInstalledAndNewer('sql_patches', '0.2.3')) . ',youre_here=' . getYoureHere() . ',isAdmin()=' . intval(isAdmin()) . ',modCheck=' . $modCheck);
+ if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (isYoureHereEnabled())) || ((isAdmin()) && ($modCheck == 'admin'))) {
+ // Output HTML code
+ $OUT = $prefix . '' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '';
+
+ // Can we close the you-are-here navigation?
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',getWhat()=' . getWhat() . ',accessLevel=' . $accessLevel . ',isWhatSet()=' . intval(isWhatSet()));
+ if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (($accessLevel == 'admin') && (getWhat() == 'welcome'))))) {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
+ // Add closing div and br-tag
+ $GLOBALS['nav_depth'] = '0';
+
+ // Run the post-filter chain
+ $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => $OUT, 'add' => $ADD));
+
+ // Get content from filter back
+ $OUT = $ret['content'];
+
+ // Close div-tag, so not the filters have to do it
+ $OUT .= '
';
+ } // END - if
+ } // END - if
// Return or output HTML code?
- if ($output) {
- // Output HTML code here
- OUTPUT_HTML($OUT);
- } else {
+ if ($return === TRUE) {
// Return HTML code
return $OUT;
+ } else {
+ // Output HTML code here
+ outputHtml($OUT);
}
}
-//
-function ADD_MENU($MODE, $act, $wht) {
- global $_CONFIG;
+// Adds a menu (mode = guest/member/admin/sponsor) to output
+function addMenu ($mode, $action, $what) {
// Init some variables
- $main_cnt = 0;
- $AND = "";
- $main_action = "";
- $sub_what = "";
+ $main_cnt = '0';
- if (!VALIDATE_MENU_ACTION($MODE, $act, $wht, true)) return CODE_MENU_NOT_VALID;
+ // is the menu action valid?
+ if (!isMenuActionValid($mode, $action, $what, TRUE)) {
+ return getCode('MENU_NOT_VALID');
+ } // END - if
// Non-admin shall not see all menus
- if (!IS_ADMIN()) {
- $AND = " AND visible='Y' AND locked='N'";
- }
+ $ADD = " AND `visible`='Y' AND `locked`='N'";
+ if (isAdmin()) {
+ // Is admin, so make all visible
+ $ADD = '';
+ } // END - if
// Load SQL data and add the menu to the output stream...
- $result_main = SQL_QUERY_ESC("SELECT title, action FROM "._MYSQL_PREFIX."_%s_menu WHERE (what='' OR what IS NULL)".$AND." ORDER BY sort",
- array($MODE), __FILE__, __LINE__);
- //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."* \n";
- if (SQL_NUMROWS($result_main) > 0) {
- OUTPUT_HTML("
");
+ $result_main = sqlQueryEscaped("SELECT
+ `title`,
+ `what`,
+ `action`,
+ `visible`,
+ `locked`
+FROM
+ `{?_MYSQL_PREFIX?}_%s_menu`
+WHERE
+ (`what`='' OR `what` IS NULL)
+ ".$ADD."
+ORDER BY
+ `sort` ASC",
+ array($mode), __FUNCTION__, __LINE__);
+
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
+ if (!ifSqlHasZeroNums($result_main)) {
// There are menus available, so we simply display them... :)
- while (list($main_title, $main_action) = SQL_FETCHROW($result_main)) {
- //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."* \n";
- // Init variables
- $BLOCK_MODE = false; $act = $main_action;
-
- // Prepare content
- $content = array(
- 'action' => $main_action,
- 'title' => $main_title
- );
+ $GLOBALS['rows'] = '';
+ while ($content = sqlFetchArray($result_main)) {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
+ // Disable the block-mode
+ enableBlockMode(FALSE);
// Load menu header template
- LOAD_TEMPLATE($MODE."_menu_title", false, $content);
-
- $result_sub = SQL_QUERY_ESC("SELECT title, what FROM "._MYSQL_PREFIX."_%s_menu WHERE action='%s' AND what != '' AND what IS NOT NULL ".$AND." ORDER BY sort",
- array($MODE, $main_action), __FILE__, __LINE__);
- $ctl = SQL_NUMROWS($result_sub);
- if ($ctl > 0) {
- $cnt=0;
- while (list($sub_title, $sub_what) = SQL_FETCHROW($result_sub)) {
+ $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', TRUE, $content);
+
+ // Sub menu
+ $result_sub = sqlQueryEscaped("SELECT
+ `title` AS `sub_title`,
+ `what` AS `sub_what`,
+ `visible` AS `sub_visible`,
+ `locked` AS `sub_locked`
+FROM
+ `{?_MYSQL_PREFIX?}_%s_menu`
+WHERE
+ `action`='%s' AND
+ `what` != '' AND
+ `what` IS NOT NULL
+ " . $ADD . "
+ORDER BY
+ `sort` ASC",
+ array(
+ $mode,
+ $content['action']
+ ), __FUNCTION__, __LINE__);
+
+ // Are there some entries?
+ if (!ifSqlHasZeroNums($result_sub)) {
+ // Init counter
+ $count = '0';
+
+ // Load all sub menus
+ while ($content2 = sqlFetchArray($result_sub)) {
+ // Merge both arrays in one
+ $content = merge_array($content, $content2);
+
// Init content
- $content = "";
+ $OUT = '';
// Full file name for checking menu
- //* DEBUG: */ echo __LINE__.":!!!!".$sub_what."!!! \n";
- $test_inc = sprintf("%sinc/modules/%s/what-%s.php", PATH, $MODE, $sub_what);
- $test = (FILE_READABLE($test_inc));
- if ($test) {
- if ((!empty($wht)) && (($wht == $sub_what))) {
- $content = "";
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
+ $inc = sprintf('inc/modules/%s/what-%s.php', $mode, $content['sub_what']);
+ if (isIncludeReadable($inc)) {
+ // Mark currently selected menu - open
+ if ((!empty($what)) && (($what == $content['sub_what']))) {
+ $OUT = '';
+ } // END - if
+
+ // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
+ if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
+ // Use index.php as link
+ $OUT .= '';
+ } else {
+ // Regular navigation link
+ $OUT .= '';
}
-
- // Navigation link
- $content .= "";
} else {
- $content .= "";
+ // Not found - open
+ $OUT .= '';
}
// Menu title
- $content .= getConfig('menu_blur_spacer') . $sub_title;
+ $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
- if ($test) {
- $content .= "";
+ if (isIncludeReadable($inc)) {
+ $OUT .= '';
+
+ // Mark currently selected menu - close
+ if ((!empty($what)) && (($what == $content['sub_what']))) {
+ $OUT .= '';
+ } // END - if
} else {
- $content .= "";
+ // Not found - close
+ $OUT .= '';
}
- if ((!empty($wht)) && (($wht == $sub_what))) {
- $content .= "";
- }
- $wht = $sub_what; $cnt++;
- // Prepare array
- $content = array(
- 'menu' => $content,
- 'what' => $sub_what
+ // Cunt it up
+ $count++;
+
+ // Rewrite array
+ $content = array(
+ 'menu' => $OUT,
+ 'what' => $content['sub_what'],
+ 'visible' => $content['sub_visible'],
+ 'locked' => $content['locked'],
);
// Add regular menu row or bottom row?
- if ($cnt < $ctl) {
- LOAD_TEMPLATE($MODE."_menu_row", false, $content);
+ if ($count < sqlNumRows($result_sub)) {
+ $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', TRUE, $content);
} else {
- LOAD_TEMPLATE($MODE."_menu_bottom", false, $content);
+ $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', TRUE, $content);
}
- }
+ } // END - while
} else {
// This is a menu block... ;-)
- $BLOCK_MODE = true;
- $INC_BLOCK = sprintf("%sinc/modules/%s/action-%s.php", PATH, $MODE, $main_action);
- if (FILE_READABLE($INC_BLOCK)) {
+ enableBlockMode();
+
+ // Load menu block
+ $INC = sprintf('inc/modules/%s/action-%s.php', $mode, $content['action']);
+ if (isFileReadable($INC)) {
// Load include file
- if ((!EXT_IS_ACTIVE($main_action)) || ($main_action == "online")) OUTPUT_HTML("
");
- }
+ // Run filter chain
+ $filterData = runFilterChain($mode . '_menu_advert_end', $filterData);
+
+ // Add content output
+ $GLOBALS['rows'] .= $filterData['output'];
+
+ // Prepare data
+ $content = array(
+ 'rows' => $GLOBALS['rows'],
+ 'menu_mode' => $mode
+ );
+
+ // Load main template
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
+ loadTemplate('menu_table', FALSE, $content);
+ } // END - if
}
-// This patched function will reduce many SELECT queries for the specified or current admin login
-function IS_ADMIN($admin="")
-{
- global $cacheArray, $_CONFIG;
- $ret = false; $passCookie = ""; $valPass = "";
- //* DEBUG: */ echo __LINE__."ADMIN:".$admin." ";
- // If admin login is not given take current from cookies...
- if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
- // Get admin login and password from session/cookies
- $admin = get_session('admin_login');
- $passCookie = get_session('admin_md5');
+// Checks whether the current user is a member
+function isMember () {
+ // By default no member
+ $ret = FALSE;
+
+ // Fix missing 'last_online' array, damn stupid code :(((
+ // @TODO Try to rewrite this to one or more functions
+ if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
+ $GLOBALS['last_online'] = array();
+ } // END - if
+
+ // Is the cache entry there?
+ if (isset($GLOBALS[__FUNCTION__])) {
+ // Then return it
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
+ return $GLOBALS[__FUNCTION__];
+ } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
+ // Destroy any existing user session data
+ destroyMemberSession();
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
+
+ // Abort further processing
+ return FALSE;
}
- //* DEBUG: */ echo __LINE__."ADMIN:".$admin."/".$passCookie." ";
- // Search in array for entry
- if (isset($cacheArray['admin_hash'])) {
- // Use cached string
- $valPass = $cacheArray['admin_hash'];
- } elseif ((!empty($passCookie)) && (isset($cacheArray['admins']['password'][$admin])) && (!empty($admin))) {
- // Count cache hits
- if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
+ // Get userid secured from session
+ setMemberId(getSession('userid'));
- // Login data is valid or not?
- $valPass = generatePassString($cacheArray['admins']['password'][$admin]);
+ // ... and set it as currently handled user id
+ setCurrentUserId(getMemberId());
- // Cache it away
- $cacheArray['admin_hash'] = $valPass;
- } elseif ((!empty($admin)) && ((!EXT_IS_ACTIVE("cache"))) || (!isset($cacheArray['admins']['password'][$admin]))) {
- // Search for admin
- $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
- array($admin), __FILE__, __LINE__);
+ // Init user data array
+ initUserData();
- // Is he admin?
- $passDB = "";
- if (SQL_NUMROWS($result) == 1) {
- // Admin login was found so let's load password from DB
- list($passDB) = SQL_FETCHROW($result);
+ // Fix "deleted" cookies
+ fixDeletedCookies(array('userid', 'u_hash'));
- // Temporary cache it
- $cacheArray['admins']['password'][$admin] = $passDB;
+ // Are cookies set and can the member data be loaded?
+ if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === TRUE)) {
+ // Validate password by created the difference of it and the secret key
+ $valPass = encodeHashForCookie(getUserData('password'));
+
+ // So did we now have valid data and an unlocked user?
+ if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
+ // Transfer last module and online time
+ $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
+ $GLOBALS['last_online']['online'] = getUserData('last_online');
- // Generate password hash
- $valPass = generatePassString($passDB);
+ // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
+ $ret = TRUE;
} // END - if
+ } // END - if
- // Free memory
- SQL_FREERESULT($result);
- }
+ // Is $ret still false?
+ if ($ret === FALSE) {
+ // Yes, so destroy the session
+ destroyMemberSession();
+ } // END - if
- if (!empty($valPass)) {
- // Check if password is valid
- //* DEBUG: */ print __FUNCTION__."*".$valPass."/".$passCookie."* \n";
- $ret = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == "*FAILED*") && (!EXT_IS_ACTIVE("cache"))));
- }
+ // Cache status
+ $GLOBALS[__FUNCTION__] = $ret;
- // Return result of comparision
- //* DEBUG: */ if (!$ret) echo __LINE__."OK! ";
+ // Return status
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
return $ret;
}
-//
-function ADD_MAX_RECEIVE_LIST($MODE, $default="", $return=false)
-{
- global $_POST;
- $OUT = "";
- switch ($MODE)
- {
- case "guest":
- // Guests (in the registration form) are not allowed to select 0 mails per day.
- $result = SQL_QUERY("SELECT value, comment FROM "._MYSQL_PREFIX."_max_receive WHERE value > 0 ORDER BY value", __FILE__, __LINE__);
- if (SQL_NUMROWS($result) > 0)
- {
- $OUT = "";
- while (list($value, $comment) = SQL_FETCHROW($result))
- {
- $OUT .= " \n";
- }
- }
- // Return - hopefully - the requested data
- return $ret;
-}
-// Activate exchange (DEPERECATED???)
-function activateExchange() {
- global $_CONFIG;
- $result = SQL_QUERY("SELECT userid FROM `"._MYSQL_PREFIX."_user_data` WHERE status='CONFIRMED' AND max_mails > 0", __FILE__, __LINE__);
- if (SQL_NUMROWS($result) >= getConfig('activate_xchange'))
- {
- // Free memory
- SQL_FREERESULT($result);
-
- // Activate System
- $SQLs = array(
- "UPDATE "._MYSQL_PREFIX."_mod_reg SET locked='N', hidden='N', mem_only='Y' WHERE module='order' LIMIT 1",
- "UPDATE `"._MYSQL_PREFIX."_member_menu` SET visible='Y', locked='N' WHERE what='order' OR what='unconfirmed' LIMIT 2",
- "UPDATE `"._MYSQL_PREFIX."_config` SET activate_xchange='0' WHERE config=0 LIMIT 1"
- );
-
- // Run SQLs
- foreach ($SQLs as $sql) {
- $result = SQL_QUERY($sql, __FILE__, __LINE__);
- }
-
- // @TODO Destroy cache
- }
-}
-//
-function DELETE_USER_ACCOUNT($uid, $reason)
-{
- $points = 0;
- $result = SQL_QUERY_ESC("SELECT (SUM(p.points) - d.used_points) AS points
-FROM "._MYSQL_PREFIX."_user_points AS p
-LEFT JOIN `"._MYSQL_PREFIX."_user_data` AS d
-ON p.userid=d.userid
-WHERE p.userid=%s", array(bigintval($uid)), __FILE__, __LINE__);
- if (SQL_NUMROWS($result) == 1) {
- // Save his points to add them to the jackpot
- list($points) = SQL_FETCHROW($result);
- SQL_FREERESULT($result);
+// Get menu mode (la_mode) of admin id
+function getAdminMenuMode ($adminId) {
+ // By default an invalid mode
+ $data['la_mode'] = 'INVALID';
- // Delete points entries as well
- $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_points WHERE userid=%s", array(bigintval($uid)), __FILE__, __LINE__);
+ // Is ext-sql_patches there and was it found in cache?
+ if (!isExtensionActive('sql_patches')) {
+ // Not found, which is bad, so we need to allow all
+ $data['la_mode'] = 'global';
+ } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
+ // Use cache
+ $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
- // Update mediadata as well
- if (GET_EXT_VERSION("mediadata") >= "0.0.4") {
- // Update database
- MEDIA_UPDATE_ENTRY(array("total_points"), "sub", $points);
- } // END - if
+ // Update cache hits
+ incrementStatsEntry('cache_hits');
+ } elseif (!isExtensionActive('cache')) {
+ // Load from database
+ $result_admin_id = sqlQueryEscaped("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
+ array(bigintval($adminId)), __FUNCTION__, __LINE__);
- // Now, when we have all his points adds them do the jackpot!
- ADD_JACKPOT($points);
- }
+ // Is there an entry?
+ if (sqlNumRows($result_admin_id) == 1) {
+ // Fetch data
+ $data = sqlFetchArray($result_admin_id);
- // Delete category selections as well...
- $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_cats WHERE userid=%s",
- array(bigintval($uid)), __FILE__, __LINE__);
+ // Set cache
+ $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
+ }
- // Remove from rallye if found
- if (EXT_IS_ACTIVE("rallye")) {
- $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_rallye_users WHERE userid=%s",
- array(bigintval($uid)), __FILE__, __LINE__);
+ // Free result
+ sqlFreeResult($result_admin_id);
}
- // Now a mail to the user and that's all...
- $msg = LOAD_EMAIL_TEMPLATE("del-user", array('text' => $reason), $uid);
- SEND_EMAIL($uid, ADMIN_DEL_ACCOUNT, $msg);
-
- // Ok, delete the account!
- $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1", array(bigintval($uid)), __FILE__, __LINE__);
+ // Return default ACL
+ return $data['la_mode'];
}
-//
-function META_DESCRIPTION ($mod, $wht) {
- global $_CONFIG, $DEPTH;
- // Exclude admin and member's area
- if (($mod != "admin") && ($mod != "login")) {
- // Construct dynamic description
- $DESCR = MAIN_TITLE." ".trim(getConfig('title_middle'))." ".ADD_DESCR("guest", "what-".$wht, true);
+// Generates an option list from various parameters
+function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '', $allowNone = FALSE) {
+ $ret = '';
- // Output it directly
- OUTPUT_HTML("");
+ // Allow none?
+ if ($allowNone === TRUE) {
+ // Add option for none
+ $ret .= '';
} // END - if
- // Remove depth
- unset($DEPTH);
-}
-//
-function ADD_JACKPOT($points) {
- $result = SQL_QUERY("SELECT points FROM "._MYSQL_PREFIX."_jackpot WHERE ok='ok' LIMIT 1", __FILE__, __LINE__);
- if (SQL_NUMROWS($result) == 0) {
- // Create line
- $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_jackpot (ok, points) VALUES ('ok','%s')", array($points), __FILE__, __LINE__);
- } else {
- // Free memory
- SQL_FREERESULT($result);
+ if ($table == '/ARRAY/') {
+ // Selection from array
+ if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
+ // Both are arrays
+ foreach ($key as $idx => $optionValue) {
+ $ret .= '';
+ }
- // Return config array
- return $CFG_DUMMY;
-}
-// Gets the matching what name from module
-function GET_WHAT($modCheck) {
- global $_CONFIG;
-
- $wht = "";
- //* DEBUG: */ echo __LINE__."!".$modCheck."! \n";
- switch ($modCheck)
- {
- case "admin":
- $wht = "overview";
- break;
-
- case "login":
- case "index":
- $wht = "welcome";
- if (($modCheck == "index") && (getConfig('index_home') != "")) $wht = getConfig('index_home');
- break;
-
- default:
- $wht = "";
- break;
+ // Free memory
+ sqlFreeResult($result);
}
- // Return what value
- return $wht;
+ // Return - hopefully - the requested data
+ return $ret;
}
-// Subtract points from database and mediadata cache
-function SUB_POINTS ($subject, $uid, $points) {
- // Add points to used points
- $result = SQL_QUERY_ESC("UPDATE `"._MYSQL_PREFIX."_user_data` SET `used_points`=`used_points`+%s WHERE userid=%s LIMIT 1",
- array($points, bigintval($uid)), __FILE__, __LINE__);
+// Deletes a user account with given reason
+function deleteUserAccount ($userid, $reason) {
+ // Init points
+ $data['points'] = '0';
+
+ // Search for the points and user data
+ $result = sqlQueryEscaped("SELECT
+ (SUM(`p`.`points`) - `d`.`used_points`) AS `points`
+FROM
+ `{?_MYSQL_PREFIX?}_user_points` AS `p`
+LEFT JOIN
+ `{?_MYSQL_PREFIX?}_user_data` AS `d`
+ON
+ `p`.`userid`=`d`.`userid`
+WHERE
+ `p`.`userid`=%s
+LIMIT 1",
+ array(bigintval($userid)), __FUNCTION__, __LINE__);
- // Insert booking record
- if (EXT_IS_ACTIVE("booking")) {
- // Add record
- ADD_BOOKING_RECORD($subject, $uid, $points, "sub");
- } // END - if
+ // Is there an entry?
+ if (sqlNumRows($result) == 1) {
+ // Save his points to add them to the jackpot
+ $data = sqlFetchArray($result);
- // Update mediadata as well
- if (GET_EXT_VERSION("mediadata") >= "0.0.4") {
- // Update database
- MEDIA_UPDATE_ENTRY(array("total_points"), "sub", $points);
- } // END - if
-}
+ // Delete points entries as well
+ // @TODO Rewrite these lines to a filter
+ sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
+ array(bigintval($userid)), __FUNCTION__, __LINE__);
-// Update config entries
-function UPDATE_CONFIG ($entries, $values, $updateMode="") {
- global $CSS;
+ // Update mediadata as well
+ if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
+ // Update database
+ updateMediadataEntry(array('total_points'), 'sub', $data['points']);
+ } // END - if
- // Do not update config in CSS mode
- if (($CSS == "1") || ($CSS == -1)) {
- return;
+ // Now, when we have all his points adds them do the jackpot!
+ if (isExtensionActive('jackpot')) {
+ addPointsToJackpot($data['points']);
+ } // END - if
} // END - if
- // Do we have multiple entries?
- if (is_array($entries)) {
- // Walk through all
- $all = "";
- foreach ($entries as $idx => $entry) {
- // Update mode set?
- if (!empty($updateMode)) {
- // Update entry
- $all .= sprintf("%s=%s%s%s,", $entry, $entry, $updateMode, (float)$values[$idx]);
- } else {
- // Check if string or number
- if (($values[$idx] + 0) === $values[$idx]) {
- // Number detected
- $all .= sprintf("%s=%s,", $entry, (float)$values[$idx]);
- } elseif ($values[$idx] == "UNIX_TIMESTAMP()") {
- // Function UNIX_TIMESTAMP() detected
- $all .= sprintf("%s=%s,", $entry, $values[$idx]);
- } else {
- // String detected
- $all .= sprintf("%s='%s',", $entry, SQL_ESCAPE($values[$idx]));
- }
- }
- } // END - foreach
-
- // Remove last comma
- $entries = substr($all, 0, -1);
- } elseif (!empty($updateMode)) {
- // Update mode set
- $entries .= sprintf("=%s%s%s", $entries, $updateMode, (float)$values);
- } else {
- // Regular entry to update
- $entries .= sprintf("='%s'", SQL_ESCAPE($values));
- }
-
- // Run database update
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "entries={$entries}");
- SQL_QUERY("UPDATE `"._MYSQL_PREFIX."_config` SET ".$entries." WHERE config=0 LIMIT 1", __FILE__, __LINE__);
+ // Free the result
+ sqlFreeResult($result);
- // Get affected rows
- $affectedRows = SQL_AFFECTEDROWS();
- //* DEBUG: */ print __FUNCTION__."(".__LINE__."):entries={$entries},affectedRows={$affectedRows} \n";
+ // Delete category selections as well...
+ sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
+ array(bigintval($userid)), __FUNCTION__, __LINE__);
- // Rebuild cache
- REBUILD_CACHE("config", "config");
-}
+ // Remove from rallye if found
+ // @TODO Rewrite this to a filter
+ if (isExtensionActive('rallye')) {
+ sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
+ array(bigintval($userid)), __FUNCTION__, __LINE__);
+ } // END - if
-// Prepares an SQL statement part for HTML mail and/or holiday depency
-function PREPARE_SQL_HTML_HOLIDAY ($mode) {
- // Exclude no users by default
- $MORE = "";
+ // Add reason and translate points
+ $data['text'] = $reason;
- // HTML mail?
- if ($mode == "html") $MORE = " AND html='Y'";
- if (GET_EXT_VERSION("holiday") >= "0.1.3") {
- // Add something for the holiday extension
- $MORE .= " AND holiday_active='N'";
- } // END - if
+ // Now a mail to the user and that's all...
+ $message = loadEmailTemplate('member_user_deleted', $data, $userid);
+ sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
- // Return result
- return $MORE;
+ // Ok, delete the account!
+ sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
}
-// "Getter" for total available receivers
-function GET_TOTAL_RECEIVERS ($mode="normal") {
- // Query database
- $result_all = SQL_QUERY("SELECT userid
-FROM "._MYSQL_PREFIX."_user_data
-WHERE status='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML_HOLIDAY($mode),
- __FILE__, __LINE__);
+// Gets the matching what name from module
+function getWhatFromModule ($modCheck) {
+ // Is the request element set?
+ if (isGetRequestElementSet('what')) {
+ // Then return this!
+ return getRequestElement('what');
+ } // END - if
- // Get num rows
- $numRows = SQL_NUMROWS($result_all);
+ // Default is empty
+ $what = '';
+
+ // Check on given module
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
+ switch ($modCheck) {
+ case 'index': // Guest area
+ // Is ext-sql_patches installed and newer than 0.0.5?
+ if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
+ // Use it from config
+ $what = getIndexHome();
+ } else {
+ // Use default 'welcome'
+ $what = 'welcome';
+ }
+ break;
- // Free result
- SQL_FREERESULT($result_all);
+ default: // Default for all other menus (getIndexHome() is for index module only)
+ $what = 'welcome';
+ break;
+ } // END - switch
- // Return value
- return $numRows;
+ // Return what value
+ return $what;
}
-// Returns HTML code with an "\n";
- }
+ $OUT = '';
+ foreach ($categories['id'] as $key => $value) {
+ $OUT .= ' ';
+ } // END - foreach
} else {
// No cateogries are defined yet
- $OUT = "\n";
+ $OUT = '';
}
// Return HTML code
@@ -1966,120 +1663,169 @@ WHERE userid=%s AND status='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML_H
}
// Add bonus mail to queue
-function ADD_BONUS_MAIL_TO_QUEUE ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode="normal", $receiver=0) {
+function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
// Is admin or bonus extension there?
- if (!IS_ADMIN()) {
+ if (!isAdmin()) {
// Abort here
- return false;
- } elseif (!EXT_IS_ACTIVE("bonus")) {
+ return FALSE;
+ } elseif (!isExtensionActive('bonus')) {
// Abort here
- return false;
+ return FALSE;
}
// Calculcate target sent
- $target = SELECTION_COUNT(explode(";", $receiverList));
+ $target = countSelection(explode(';', $receiverList));
// Receiver is zero?
- if ($receiver == 0) {
+ if ($receiver == '0') {
// Then auto-fix it
$receiver = $target;
} // END - if
// HTML extension active?
- if (EXT_IS_ACTIVE("html")) {
- // No HTML by default
- $HTML = "N";
-
- // HTML mode?
- if ($mode == "html") $HTML = "Y";
-
+ if (isExtensionActive('html_mail')) {
// Add HTML mail
- $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_bonus
-(subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent, html_msg)
-VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
- array(
- $subject,
- $text,
- $receiverList,
- $points,
- $seconds,
- $url,
- $cat,
- $target,
- bigintval($receiver),
- $HTML
-), __FILE__, __LINE__);
+ sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
+ `subject`,
+ `text`,
+ `receivers`,
+ `points`,
+ `time`,
+ `data_type`,
+ `timestamp`,
+ `url`,
+ `cat_id`,
+ `target_send`,
+ `mails_sent`,
+ `html_msg`
+) VALUES (
+ '%s',
+ '%s',
+ '%s',
+ %s,
+ %s,
+ 'NEW',
+ UNIX_TIMESTAMP(),
+ '%s',
+ %s,
+ %s,
+ %s,
+ '%s'
+)",
+ array(
+ $subject,
+ $text,
+ $receiverList,
+ $points,
+ bigintval($seconds),
+ $url,
+ bigintval($categoryId),
+ $target,
+ bigintval($receiver),
+ convertBooleanToYesNo($mode == 'html')
+ ), __FUNCTION__, __LINE__);
} else {
// Add regular mail
- $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_bonus
-(subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent)
-VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
- array(
- $subject,
- $text,
- $receiverList,
- $points,
- $seconds,
- $url,
- $cat,
- $target,
- bigintval($receiver),
-), __FILE__, __LINE__);
+ sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
+ `subject`,
+ `text`,
+ `receivers`,
+ `points`,
+ `time`,
+ `data_type`,
+ `timestamp`,
+ `url`,
+ `cat_id`,
+ `target_send`,
+ `mails_sent`
+) VALUES (
+ '%s',
+ '%s',
+ '%s',
+ %s,
+ %s,
+ 'NEW',
+ UNIX_TIMESTAMP(),
+ '%s',
+ %s,
+ %s,
+ %s
+)",
+ array(
+ $subject,
+ $text,
+ $receiverList,
+ $points,
+ bigintval($seconds),
+ $url,
+ bigintval($categoryId),
+ $target,
+ bigintval($receiver),
+ ), __FUNCTION__, __LINE__);
}
}
// Generate a receiver list for given category and maximum receivers
-function GENERATE_RECEIVER_LIST ($cat, $receiver, $mode="") {
- global $_CONFIG;
-
+function generateReceiverList ($categoryId, $receiver, $mode = '') {
// Init variables
- $CAT_TABS = "%s";
- $CAT_WHERE = "";
- $receiverList = "";
+ $extraColumns = '';
+ $receiverList = '';
+ $result = FALSE;
// Secure data
- $cat = bigintval($cat);
- $receiver = bigintval($receiver);
+ $categoryId = bigintval($categoryId);
+ $receiver = bigintval($receiver);
// Is the receiver zero and mode set?
- if (($receiver == 0) && (!empty($mode))) {
+ if (($receiver == '0') && (!empty($mode))) {
// Auto-fix receiver maximum
- $receiver = GET_TOTAL_RECEIVERS($mode);
+ $receiver = getTotalReceivers($mode);
} // END - if
+ // Exclude (maybe exclude) testers
+ $addWhere = runFilterChain('user_exclusion_sql', ' ');
+
// Category given?
- if ($cat > 0) {
+ if (isValidId($categoryId)) {
// Select category
- $CAT_TABS = "LEFT JOIN "._MYSQL_PREFIX."_user_cats AS c ON d.userid=c.userid";
- $CAT_WHERE = " AND c.cat_id=%s";
+ $extraColumns = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS `c` ON `d`.`userid`=`c`.`userid`";
+ $addWhere = sprintf(' AND `c`.`cat_id`=%s', $categoryId);
} // END - if
// Exclude users in holiday?
- if (GET_EXT_VERSION("holiday") >= "0.1.3") {
+ if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
// Add something for the holiday extension
- $CAT_WHERE .= " AND d.holiday_active='N'";
+ $addWhere .= " AND `d`.`holiday_active`='N'";
} // END - if
- if ((EXT_IS_ACTIVE("html_mail")) && ($mode == "html")) {
- // Only include HTML receivers
- $result = SQL_QUERY_ESC("SELECT d.userid FROM `"._MYSQL_PREFIX."_user_data` AS d ".$CAT_TABS." WHERE d.status='CONFIRMED' AND d.html='Y'".$CAT_WHERE." ORDER BY d.%s %s LIMIT %s",
- array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FILE__, __LINE__);
- } else {
- // Include all
- $result = SQL_QUERY_ESC("SELECT d.userid FROM `"._MYSQL_PREFIX."_user_data` AS d ".$CAT_TABS." WHERE d.status='CONFIRMED'".$CAT_WHERE." ORDER BY d.%s %s LIMIT %s",
- array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FILE__, __LINE__);
- }
+ // Run query
+ $result = sqlQueryEscaped("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",
+ array(
+ $receiver
+ ), __FUNCTION__, __LINE__);
// Entries found?
- if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
+ if ((sqlNumRows($result) >= $receiver) && ($receiver > 0)) {
// Load all entries
- while (list($REC) = SQL_FETCHROW($result)) {
+ while ($content = sqlFetchArray($result)) {
// Add receiver when not empty
- if (!empty($REC)) $receiverList .= $REC.";";
+ if (!empty($content['userid'])) {
+ $receiverList .= $content['userid'] . ';';
+ } // END - if
} // END - while
// Free memory
- SQL_FREERESULT($result);
+ sqlFreeResult($result);
// Remove trailing semicolon
$receiverList = substr($receiverList, 0, -1);
@@ -2089,153 +1835,719 @@ function GENERATE_RECEIVER_LIST ($cat, $receiver, $mode="") {
return $receiverList;
}
-// Get timestamp for given stats type and data
-function USER_STATS_GET_TIMESTAMP ($type, $data, $uid = 0) {
- // Default timestamp is zero
- $stamp = 0;
+// Recuce the amount of received emails for the receipients for given email
+function reduceRecipientReceivedMails ($column, $id, $count) {
+ // Search for mail in database
+ $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
+ array(
+ $column,
+ bigintval($id),
+ $count
+ ), __FUNCTION__, __LINE__
+ );
+
+ // Are there entries?
+ if (!ifSqlHasZeroNums($result)) {
+ // Now load all userids for one big query!
+ $userids = array();
+ while ($data = sqlFetchArray($result)) {
+ // By default reduce and found no emails
+ $num = 0;
+
+ // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
+ // @TODO Rewrite this to a filter
+ if ((isset($data['stats_id'])) && (isValidId($data['stats_id']))) {
+ // User email
+ $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
+ } elseif ((isset($data['bonus_id'])) && (isValidId($data['bonus_id']))) {
+ // Bonus mail
+ $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
+ }
- // User id set?
- if ((isset($GLOBALS['userid'])) && ($uid == 0)) {
- $uid = $GLOBALS['userid'];
- } // END - if
+ // Reduce this users total received emails?
+ if ($num === 0) {
+ $userids[$data['userid']] = $data['userid'];
+ } // END - if
+ } // END - while
- // Is the extension installed and updated?
- if ((!EXT_IS_ACTIVE("sql_patches")) || (EXT_VERSION_IS_OLDER("sql_patches", "0.5.6"))) {
- // Return zero here
- return $stamp;
+ if (isFilledArray($userids)) {
+ // Now update all user accounts
+ sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
+ array(
+ implode(',', $userids),
+ count($userids)
+ ), __FUNCTION__, __LINE__);
+ } else {
+ // Nothing deleted
+ displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
+ }
} // END - if
- // Try to find the entry
- $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`inserted`) AS `stamp`
-FROM "._MYSQL_PREFIX."_user_stats_data
-WHERE userid=%s AND stats_type='%s' AND stats_data='%s'
+ // Free result
+ sqlFreeResult($result);
+}
+
+// Creates a new task
+function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = TRUE) {
+ // Insert the task data into the database
+ 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())",
+ array(
+ convertZeroToNull($adminId),
+ convertZeroToNull($userid),
+ $taskType,
+ $subject,
+ $notes
+ ), __FUNCTION__, __LINE__, TRUE, $strip);
+
+ // Return insert id which is the task id
+ return getSqlInsertId();
+}
+
+// Updates last module / online time
+function updateLastActivity ($userid) {
+ // Is 'what' set?
+ if (isWhatSet()) {
+ // Run the update query
+ sqlQueryEscaped("UPDATE
+ `{?_MYSQL_PREFIX?}_user_data`
+SET
+ `{%%pipe,getUserLastWhatName%%}`='{%%pipe,getWhat%%}',
+ `last_online`=UNIX_TIMESTAMP(),
+ `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
+WHERE
+ `userid`=%s
LIMIT 1",
- array(bigintval($uid), $type, $data), __FILE__, __LINE__);
+ array(
+ bigintval($userid)
+ ), __FUNCTION__, __LINE__);
+ } else {
+ // No what set, needs to be ignored (last_module is last_what)
+ sqlQueryEscaped("UPDATE
+ `{?_MYSQL_PREFIX?}_user_data`
+SET
+ `{%%pipe,getUserLastWhatName%%}`=NULL,
+ `last_online`=UNIX_TIMESTAMP(),
+ `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
+WHERE
+ `userid`=%s
+LIMIT 1",
+ array(
+ bigintval($userid)
+ ), __FUNCTION__, __LINE__);
+ }
+}
- // Is the entry there?
- if (SQL_NUMROWS($result) == 1) {
- // Get this stamp
- list($stamp) = SQL_FETCHROW($result);
- } // END - if
+// List all given joined rows (callback function from XML)
+function doGenericJoinedListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
+ // Verify that tableName and columns are not empty
+ if ((!is_array($tableName)) || (count($tableName) != 1)) {
+ // No tableName specified
+ reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
+ } elseif (!isFilledArray($columns)) {
+ // No columns specified
+ reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
+ }
- // Free result
- SQL_FREERESULT($result);
+ // This is the minimum query, so at least columns and tableName must have entries
+ $sql = 'SELECT ';
+
+ // Get the sql part back from given array
+ $sql .= getSqlPartFromXmlArray($columns);
+
+ // Add "FROM"
+ $sql .= getSqlXmlFromTable($tableName);
- // Return stamp
- return $stamp;
+ // Add "JOIN"
+ $sql .= getSqlXmlJoinedTable($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable);
+
+ // Add "WHERE"
+ $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
+
+ // Add "ORDER BY"
+ $sql .= getSqlXmlOrderBy($orderByColumns);
+
+ // Now handle all over to the inner function which will execute the listing
+ doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
}
-// Inserts user stats
-function USER_STATS_INSERT_RECORD ($uid, $type, $data) {
- // Is the extension installed and updated?
- if ((!EXT_IS_ACTIVE("sql_patches")) || (EXT_VERSION_IS_OLDER("sql_patches", "0.5.6"))) {
- // Return zero here
- return false;
- } // END - if
+// List all given rows (callback function from XML)
+function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
+ // Verify that tableName and columns are not empty
+ if ((!is_array($tableName)) || (count($tableName) != 1)) {
+ // No tableName specified
+ reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
+ } elseif (!isFilledArray($columns)) {
+ // No columns specified
+ reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
+ }
+
+ // This is the minimum query, so at least columns and tableName must have entries
+ $sql = 'SELECT ';
+
+ // Get the sql part back from given array
+ $sql .= getSqlPartFromXmlArray($columns);
+
+ // Add "FROM"
+ $sql .= getSqlXmlFromTable($tableName);
+
+ // Add "WHERE"
+ $sql .= getSqlXmlWhereConditions($whereColumns, $conditions);
+
+ // Add "ORDER BY"
+ $sql .= getSqlXmlOrderBy($orderByColumns);
+
+ // Now handle all over to the inner function which will execute the listing
+ doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
+}
+
+// Do the listing of entries
+function doListEntries ($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array(), $content = array()) {
+ // Run the SQL query
+ $result = sqlQuery($sql, __FUNCTION__, __LINE__);
+
+ // Are there some URLs left?
+ if (!ifSqlHasZeroNums($result)) {
+ // List all URLs
+ $OUT = '';
+ while ($row = sqlFetchArray($result)) {
+ // "Translate" content
+ foreach ($callbackColumns as $columnName => $callbackName) {
+ // Fill the callback arguments
+ $args = array($row[$columnName]);
+
+ // Is there more to add?
+ if (isset($extraParameters[$columnName])) {
+ // Add them as well
+ $args = merge_array($args, $extraParameters[$columnName]);
+ } // END - if
+
+ // Call the callback-function
+ //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=
'.print_r($args, TRUE).'
');
+ // @TODO If the EL sub-system can support more than one parameter, this call_user_func_array() can be avoided
+ $row[$columnName] = call_user_func_array($callbackName, $args);
+ } // END - foreach
+
+ // Load row template
+ $OUT .= loadTemplate(trim($rowTemplate[0]), TRUE, $row);
+ } // END - while
+
+ // Is at least one entry set in content?
+ if (isFilledArray($content)) {
+ // Then add generic 'rows' element
+ $content['rows'] = $OUT;
+ } else {
+ // Direct output is content
+ $content = $OUT;
+ }
- // Does it exist?
- if ((!USER_STATS_GET_TIMESTAMP($type, $data, $uid)) && (!is_array($data))) {
- // Then insert it!
- SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_user_stats_data (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
- array(bigintval($uid), $type, $data), __FILE__, __LINE__);
- } elseif (is_array($data)) {
- // Invalid data!
- DEBUG_LOG(__FUNCTION__, __LINE__, " uid={$uid},type={$type},data={".gettype($data).": Invalid statistics data type!");
+ // Load main template
+ loadTemplate(trim($tableTemplate[0]), FALSE, $content);
+ } else {
+ // No URLs in surfbar
+ displayMessage('{--' .$noEntryMessageId[0] . '--}');
}
+
+ // Free result
+ sqlFreeResult($result);
}
-// "Getter" for array for user refs and points in given level
-function GET_USER_REF_POINTS ($uid, $level) {
- global $_CONFIG;
+// Adds a given entry to the database
+function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
+ //* DEBUG: */ die(__FUNCTION__.':columns=
'.print_r($columns,TRUE).'
,filterFunctions=
'.print_r($filterFunctions,TRUE).'
,extraValues=
'.print_r($extraValues,TRUE).'
,timeColumns=
'.print_r($timeColumns,TRUE).'
,columnIndex=
'.print_r($columnIndex,TRUE).'
,POST=
'.print_r($_POST,TRUE).'
');
+ // Verify that tableName and columns are not empty
+ if ((!is_array($tableName)) || (count($tableName) != 1)) {
+ // No tableName specified
+ reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
+ } elseif (!isFilledArray($columns)) {
+ // No columns specified
+ reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
+ }
+
+ // Init columns and value elements
+ $sqlColumns = array();
+ $sqlValues = array();
- //* DEBUG: */ print "----------------------- ".__FUNCTION__." - ENTRY ------------------------
\n";
- // Default is no refs and no nickname
- $ADD = "";
- $refs = array();
+ // Default is that all went fine
+ $GLOBALS['__XML_PARSE_RESULT'] = TRUE;
- // Do we have nickname extension installed?
- if (EXT_IS_ACTIVE("nickname")) {
- $ADD = ", ud.nickname";
+ // Is there "time columns"?
+ if (isFilledArray($timeColumns)) {
+ // Then "walk" through all entries
+ foreach ($timeColumns as $column) {
+ // Convert all (possible) selections
+ convertSelectionsToEpocheTimeInPostData($column . '_ye');
+ } // END - foreach
} // END - if
- // Get refs from database
- $result = SQL_QUERY_ESC("SELECT ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$ADD."
-FROM "._MYSQL_PREFIX."_user_refs AS ur
-LEFT JOIN "._MYSQL_PREFIX."_user_points AS up
-ON ur.refid=up.userid AND ur.level=0
-LEFT JOIN `"._MYSQL_PREFIX."_user_data` AS ud
-ON ur.refid=ud.userid
-WHERE ur.userid=%s AND ur.level=%s
-ORDER BY ur.refid ASC",
- array(bigintval($uid), bigintval($level)), __FILE__, __LINE__);
-
- // Are there some entries?
- if (SQL_NUMROWS($result) > 0) {
- // Fetch all entries
- while ($row = SQL_FETCHARRAY($result)) {
- // Get total points of this user
- $row['points'] = GET_TOTAL_DATA($row['refid'], "user_points", "points") - GET_TOTAL_DATA($row['refid'], "user_data", "used_points");
-
- // Get unconfirmed mails
- $row['unconfirmed'] = GET_TOTAL_DATA($row['refid'], "user_links", "id", "userid", true);
-
- // Init clickrate with zero
- $row['clickrate'] = 0;
-
- // Is at least one mail received?
- if ($row['emails_received'] > 0) {
- // Calculate clickrate
- $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
+ // Add columns and values
+ foreach ($columns as $key => $columnName) {
+ //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
+ // Is columnIndex set?
+ if (!is_null($columnIndex)) {
+ // Check conditions
+ //* DEBUG: */ die('columnName=
'.print_r($columnName,TRUE).'
columnIndex=
'.print_r($columnIndex,TRUE).'
'.debug_get_printable_backtrace());
+ assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
+
+ // Then use that index "blindly"
+ $columnName = $columnName[$columnIndex];
+ } // END - if
+
+ // Debug message
+ //* 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'])));
+
+ // Get value back (no array supported)
+ $value = postRequestElement($columnName);
+
+ // Is this an array and element 0 is set?
+ if ((is_array($value)) && (isset($value[0]))) {
+ // Then only take this
+ $value = $value[0];
+ } // END - if
+
+ // Copy entry securely to the final arrays
+ $sqlColumns[$key] = sqlEscapeString($columnName);
+ $sqlValues[$key] = sqlEscapeString($value);
+
+ // Search for it
+ $search = key(search_array($columns, 'column', $columnName));
+
+ // Try to handle call-back functions and/or extra values on the list
+ //* DEBUG: */ outputHtml($key . '/' . $columnName . '=
');
+ sqlQuery($sql, __FUNCTION__, __LINE__);
+
+ // Add affected rows
+ $edited = sqlAffectedRows();
+ $affected += $edited;
+
+ // Load all data from that id
+ $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
+ array(
+ $tableName[0],
+ $idColumn[0],
+ $id
+ ), __FUNCTION__, __LINE__);
+
+ // Fetch the data and merge it into $content
+ $content = merge_array($content, sqlFetchArray($result));
+
+ // Prepare filter data array
+ $filterData = array(
+ 'mode' => 'edit',
+ 'table_name' => $tableName,
+ 'content' => $content,
+ 'id' => $id,
+ 'subject' => $subject,
+ 'userid_column' => $userIdColumn,
+ 'raw_userid' => $rawUserId,
+ 'affected' => $edited,
+ 'sql' => $sql,
+ );
- // Is autopurge installed and the user inactive?
- if ((EXT_IS_ACTIVE("autopurge")) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online'])) {
- // Inactive user!
- $row['activity'] = MEMBER_ACTIVITY_INACTIVE;
+ // Send "build mail" out
+ runFilterChain('send_build_mail', $filterData);
+
+ // Free the result
+ sqlFreeResult($result);
+ } // END - foreach
+
+ // Delete cache?
+ if ((isFilledArray($cacheFiles)) && (!empty($cacheFiles[0]))) {
+ // Delete cache file(s)
+ foreach ($cacheFiles as $cache) {
+ // Skip any empty entries
+ if (empty($cache)) {
+ // This may cause trouble in loadCacheFile()
+ continue;
} // END - if
- // Remove some entries
- unset($row['mails_confirmed']);
- unset($row['emails_received']);
- unset($row['last_online']);
+ // Use rebuildCache() to delete it
+ rebuildCache($cache);
+ } // END - foreach
+ } // END - if
- // Add row
- $refs[$row['id']] = $row;
- } // END - while
+ // Return affected rows
+ return $affected;
+}
+
+// Delete rows by given id numbers
+function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
+ // The base SQL command:
+ $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
+
+ // Is a user id provided?
+ //* BUG: */ die('
'.print_r($rawUserId,TRUE).'
'.print_r($userIdColumn,TRUE).'
');
+ if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
+ // Add user id as well
+ $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
} // END - if
- // Free result
- SQL_FREERESULT($result);
+ // $idColumn[0] in POST must be an array again
+ if (!is_array(postRequestElement($idColumn[0]))) {
+ // This indicates that you have conflicting form field naming with XML names
+ reportBug(__FUNCTION__, __LINE__, 'You have a wrong form field element, idColumn[0]=' . $idColumn[0]);
+ } // END - if
- // Return result
- //* DEBUG: */ print "
----------------------- ".__FUNCTION__." - EXIT ------------------------ \n";
- return $refs;
+ // Delete them all
+ //* BUG: */ die($sql.'
'.print_r($tableName,TRUE).'
'.print_r($columns,TRUE).'
'.print_r($filterFunctions,TRUE).'
'.print_r($extraValues,TRUE).'
'.print_r($deleteNow,TRUE).'
'.print_r($idColumn,TRUE).'
');
+ $idList = '';
+ foreach (postRequestElement($idColumn[0]) as $id => $sel) {
+ // Is id zero?
+ if (!isValidId($id)) {
+ // Then skip this
+ continue;
+ } // END - if
+
+ // Is there a userid?
+ if (isPostRequestElementSet($userIdColumn[0])) {
+ // Load all data from that id
+ $result = sqlQueryEscaped("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
+ array(
+ $tableName[0],
+ $idColumn[0],
+ $id
+ ), __FUNCTION__, __LINE__);
+
+ // Fetch the data
+ $content = sqlFetchArray($result);
+
+ // Free the result
+ sqlFreeResult($result);
+
+ // Send "build mails" out
+ sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
+ } // END - if
+
+ // Add id number
+ $idList .= $id . ',';
+ } // END - foreach
+
+ // Run the query
+ sqlQueryEscaped($sql,
+ array(
+ $tableName[0],
+ $idColumn[0],
+ convertNullToZero(substr($idList, 0, -1))
+ ), __FUNCTION__, __LINE__);
+
+ // Return affected rows
+ return sqlAffectedRows();
}
-// Recuced the amount of received emails for the receipients for given email
-function REDUCT_RECIPIENT_RECEIVED_MAILS ($column, $id, $count) {
- // Search for mail in database
- $result = SQL_QUERY_ESC("SELECT `userid` FROM `"._MYSQL_PREFIX."_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
- array($column, bigintval($id), $count), __FILE__, __LINE__);
+// Build a special template list
+// @TODO cacheFiles is not yet supported
+function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
+ // $tableName and $idColumn must bove be arrays!
+ if ((!is_array($tableName)) || (count($tableName) != 1)) {
+ // $tableName is no array
+ reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
+ } elseif (!is_array($idColumn)) {
+ // $idColumn is no array
+ reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
+ } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
+ // $tableName is no array
+ reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
+ }
+
+ // Init row output
+ $OUT = '';
+
+ // "Walk"Â through all entries
+ //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'listType=
'.print_r($listType,TRUE).'
,tableName
'.print_r($tableName,TRUE).'
,columns=
'.print_r($columns,TRUE).'
,filterFunctions=
'.print_r($filterFunctions,TRUE).'
,extraValues=
'.print_r($extraValues,TRUE).'
,idColumn=
'.print_r($idColumn,TRUE).'
,userIdColumn=
'.print_r($userIdColumn,TRUE).'
,rawUserId=
'.print_r($rawUserId,TRUE).'
');
+ foreach (postRequestElement($idColumn[0]) as $id => $selected) {
+ // Secure id number
+ $id = bigintval($id);
+
+ // Get result from a given column array and table name
+ $result = getSqlResultFromArray($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
+
+ // Is there one entry?
+ if (sqlNumRows($result) == 1) {
+ // Load all data
+ $row = sqlFetchArray($result);
+
+ // Filter all data
+ foreach ($row as $key => $value) {
+ // Search index
+ $idx = searchXmlArray($key, $columns, 'column');
+
+ // Default name is NULL
+ $name = NULL;
+
+ // Is the name there?
+ if (isset($columns[$idx]['name'])) {
+ // Then use it
+ $name = $columns[$idx]['name'];
+ } // END - if
+
+ // Skip any missing entries
+ if ($idx === FALSE) {
+ // Skip this one
+ //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
+ continue;
+ } // END - if
+
+ //Â Is there a userid?
+ //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
+ if ($key == $userIdColumn[0]) {
+ // Add it again as raw id
+ //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
+ $row[$userIdColumn[0]] = convertZeroToNull($value);
+ $row[$userIdColumn[0] . '_raw'] = $row[$userIdColumn[0]];
+ } // END - if
+
+ // If the key matches the idColumn variable, we need to temporary remember it
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
+ if ($key == $idColumn[0]) {
+ /*
+ * Found, so remember it securely (to make sure only id
+ * numbers can pass, don't use alpha-numerical values!)
+ */
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
+ $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
+ } // END - if
+
+ // Try to handle call-back functions and/or extra values
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',row[' . $key . ']=' . $row[$key]);
+ //if ($key == 'forced_campaign_created') die($idx.'=
'.print_r($columns,true).'
'.print_r($extraValues,true).'
');
+ $row[$key] = doHandleExtraValues($filterFunctions, $extraValues, $idx, $row[$key], $userIdColumn, ((!is_null($name)) ? $name : $key), $id);
+ } // END - foreach
+
+ // Then list it
+ $OUT .= loadTemplate(sprintf('%s_%s_%s_row',
+ $prefix,
+ $listType,
+ $tableName[0]
+ ), TRUE, $row
+ );
+ } // END - if
+
+ // Free the result
+ sqlFreeResult($result);
+ } // END - foreach
+
+ // Is there an entry in $content?
+ if (isFilledArray($content)) {
+ // Use generic 'rows'
+ $content['rows'] = $OUT;
+ } else {
+ // Use direct output
+ $content = $OUT;
+ }
+
+ // Load master template
+ loadTemplate(
+ sprintf('%s_%s_%s',
+ $prefix,
+ $listType,
+ $tableName[0]
+ ), FALSE, $content
+ );
+}
+
+// Adds key/value pair to a working SQL string together
+function addKeyValueSql ($key, $value) {
+ // Init SQL
+ $sql = '';
+
+ // Is it NULL?
+ if (($value == 'NULL') || (is_null($value))) {
+ // Add key with NULL
+ $sql .= sprintf(' `%s`=NULL,',
+ sqlEscapeString($key)
+ );
+ } elseif ((is_double($value)) || (is_float($value)) || (is_int($value))) {
+ // Is a number, so addd it directly
+ $sql .= sprintf(' `%s`=%s,',
+ sqlEscapeString($key),
+ $value
+ );
+ } else {
+ // Else add the value escape'd
+ $sql .= sprintf(" `%s`='%s',",
+ sqlEscapeString($key),
+ sqlEscapeString($value)
+ );
+ }
+
+ // Return SQL string
+ return $sql;
+}
+
+// "Getter" for an array from given table and columns
+function getArrayFromTable ($tableName, $columns, $orderBy, $ordered = 'ASC', $whereSql = '') {
+ // The table must exist
+ assert(ifSqlTableExists($tableName));
+
+ // Search for it
+ $result = sqlQueryEscaped('SELECT
+ `' . implode('`, `', $columns) . '`
+FROM
+ `{?_MYSQL_PREFIX?}_%s`
+' . $whereSql . '
+ORDER BY
+ `%s` %S',
+ array(
+ $tableName,
+ $orderBy,
+ $ordered
+ ), __FUNCTION__, __LINE__
+ );
+
+ // Init array
+ $rows = array();
// Are there entries?
- if (SQL_NUMROWS($result) > 0) {
- // Now load all userids for one big query!
- $UIDs = array();
- while (list($uid) = SQL_FETCHROW($result)) {
- $UIDs[$uid] = $uid;
+ if (!ifSqlHasZeroNums($result)) {
+ // Load all entries
+ while ($row = sqlFetchArray($result)) {
+ array_push($rows, $row);
} // END - while
-
- // Now update all user accounts
- SQL_QUERY_ESC("UPDATE `"._MYSQL_PREFIX."_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
- array(implode(",", $UIDs), count($UIDs)), __FILE__, __LINE__);
} // END - if
// Free result
- SQL_FREERESULT($result);
+ sqlFreeResult($result);
+
+ // Return all found rows
+ return $rows;
}
// [EOF]