Security line in all includes changed
[mailer.git] / inc / libs / surfbar_functions.php
index 1a451ebb2355bca3edf152bae8dc4f90f818404b..7df9fd5b8173bd60c9aac3a65b28af1aabd8f8b5 100644 (file)
  ************************************************************************/
 
 // Some security stuff...
-if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
+if (!defined('__SECURITY')) {
        $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
        require($INC);
 }
 
-// Admin has added an URL with given user id
-function SURFBAR_ADMIN_ADD_URL ($url, $uid, $reward, $costs, $paymentId) {
-       // Is this really an admin?
+// -----------------------------------------------------------------------------
+//                               Admin functions
+// -----------------------------------------------------------------------------
+
+// Admin has added an URL with given user id and so on
+function SURFBAR_ADMIN_ADD_URL ($url) {
+       // Do some pre-checks
        if (!IS_ADMIN()) {
-               // Then leave here
+               // Not an admin
                return false;
-       } // END - if
+       } elseif (!VALIDATE_URL($url)) {
+               // URL invalid
+               return false;
+       } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
+               // URL already found in surfbar!
+               return false;
+       } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS("0")) {
+               // No more allowed!
+               return false;
+       }
 
-       // Check if that URL does not exist
-       if (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
-               // Already found!
+       // Do we have fixed or dynamic payment model?
+       $reward = SURFBAR_DETERMINE_REWARD();
+       $costs  = SURFBAR_DETERMINE_COSTS();
+
+       // Register the new URL
+       return SURFBAR_REGISTER_URL($url, "0", $reward, $costs, "0", "CONFIRMED", "unlock");
+}
+// Admin function for unlocking URLs
+function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
+       // Is this an admin or invalid array?
+       if (!IS_ADMIN()) {
+               // Not admin or invalid IDs array
+               return false;
+       } elseif (!is_array($IDs)) {
+               // No array
                return false;
+       } elseif (count($IDs) == 0) {
+               // Empty array
+               return false;
+       }
+
+       // Set to true to make AND expression valid if first URL got unlocked
+       $done = true;
+
+       // Update the status for all ids
+       foreach ($IDs as $id => $dummy) {
+               // Test all ids through (ignores failed)
+               $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "CONFIRMED")));
        } // END - if
 
+       // Return total status
+       return $done;
+}
+
+// -----------------------------------------------------------------------------
+//                               Member functions
+// -----------------------------------------------------------------------------
+
+// Member has added an URL
+function SURFBAR_MEMBER_ADD_URL ($url) {
+       global $_CONFIG;
+
+       // Do some pre-checks
+       if (!IS_MEMBER()) {
+               // Not a member
+               return false;
+       } elseif (!VALIDATE_URL($url)) {
+               // URL invalid
+               return false;
+       } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
+               // URL already found in surfbar!
+               return false;
+       } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
+               // No more allowed!
+               return false;
+       }
+
+       // Do we have fixed or dynamic payment model?
+       $reward = SURFBAR_DETERMINE_REWARD();
+       $costs  = SURFBAR_DETERMINE_COSTS();
+
        // Register the new URL
-       return SURFBAR_REGISTER_URL($url, $uid, $reward, $costs, $paymentId, "CONFIRMED", "unlock");
+       return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
 }
+// -----------------------------------------------------------------------------
+//                               Generic functions
+// -----------------------------------------------------------------------------
+
 // Looks up by an URL
 function SURFBAR_LOOKUP_BY_URL ($url) {
        // Now lookup that given URL by itself
@@ -75,12 +147,19 @@ function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="AS
                $searchTerm = bigintval($searchTerm);
        } // END - if
 
+       // If the column is "id" there can be only one entry
+       $limit = "";
+       if ($column == "id") {
+               $limit = "LIMIT 1";
+       } // END - if
+
        // Look up the record
        $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
 FROM "._MYSQL_PREFIX."_surfbar_urls
 WHERE %s='%s'
-ORDER BY %s %s",
-               array($column, $searchTerm, $order, $sort), __FILE__, __LINE__);
+ORDER BY %s %s
+%s",
+               array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
 
        // Is there at least one record?
        if (SQL_NUMROWS($result) > 0) {
@@ -104,7 +183,7 @@ ORDER BY %s %s",
        return $lastUrlData;
 }
 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
-function SURFBAR_REGISTER_URL ($url, $uid, $reward, $paymentId, $costs, $status="PENDING", $addMode="reg") {
+function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
        global $_CONFIG;
 
        // Make sure by the user registered URLs are always pending
@@ -117,7 +196,6 @@ function SURFBAR_REGISTER_URL ($url, $uid, $reward, $paymentId, $costs, $status=
                'uid'         => $uid,
                'reward'      => $reward,
                'costs'       => $costs,
-               'payment_id'  => $paymentId,
                'status'      => $status
        );
 
@@ -143,14 +221,19 @@ function SURFBAR_REGISTER_URL ($url, $uid, $reward, $paymentId, $costs, $status=
 }
 // Inserts an url by given data array and return the insert id
 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
+       // Get userid
+       $uid = bigintval($urlData['uid']);
+
+       // Is the id set?
+       if (empty($uid)) $uid = 0;
+
        // Just run the insert query for now
-       SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, payment_id, status) VALUES(%s, '%s', %s, %s, %s, '%s')",
+       SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, status) VALUES('%s', '%s', %s, %s, '%s')",
                array(
-                       bigintval($urlData['uid']),
+                       $uid,
                        $urlData['url'],
                        (float)$urlData['reward'],
                        (float)$urlData['costs'],
-                       bigintval($urlData['payment_id']),
                        $urlData['status']
                ), __FILE__, __LINE__
        );
@@ -170,10 +253,15 @@ function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
        eval($eval);
 
        // Send the notification out
-       SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
+       return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
 }
 // Notify the user about the performed action
 function SURFBAR_NOTIFY_USER ($messageType, $content) {
+       // Skip notification if userid is zero
+       if ($content['uid'] == 0) {
+               return false;
+       } // END - if
+
        // Prepare template name
        $templateName = sprintf("member_surfbar_%s", $messageType);
 
@@ -187,7 +275,7 @@ function SURFBAR_NOTIFY_USER ($messageType, $content) {
        $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
 
        // Send the email
-       SEND_EMAIL($content['uid'], $subject, $mailText);
+       return SEND_EMAIL($content['uid'], $subject, $mailText);
 }
 // Translate the URL status
 function SURFBAR_TRANSLATE_STATUS ($status) {
@@ -206,6 +294,37 @@ function SURFBAR_TRANSLATE_STATUS ($status) {
        // Return result
        return $statusTranslated;
 }
+// Determine reward
+function SURFBAR_DETERMINE_REWARD () {
+       global $_CONFIG;
+
+       // Do we have static or dynamic?
+       if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
+               // Static model, so choose static values
+               $reward = $_CONFIG['surfbar_static_reward'];
+       } else {
+               // Dynamic model, so calculate values
+               die("DYNAMIC payment model not yet supported!");
+       }
+
+       // Return reward
+       return $reward;
+}
+// Determine costs
+function SURFBAR_DETERMINE_COSTS () {
+       global $_CONFIG;
+
+       // Do we have static or dynamic?
+       if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
+               $costs  = $_CONFIG['surfbar_static_costs'];
+       } else {
+               // Dynamic model, so calculate values
+               die("DYNAMIC payment model not yet supported!");
+       }
+
+       // Return costs
+       return $costs;
+}
 // Determine right template name
 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
        // Default is the frameset
@@ -234,6 +353,7 @@ function SURFBAR_CHECK_RELOAD_FULL() {
        if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
                // Cache static reload lock
                $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
+               //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
 
                // Ask the database
                $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
@@ -258,7 +378,7 @@ LIMIT 1",
                $total = SURFBAR_GET_TOTAL_URLS();
 
                // Do we have some URLs in lock? Admins can always surf on own URLs!
-               //* DEBUG: */ echo __FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}<br />\n";
+               //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
                $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
        } else {
                // Dynamic model...
@@ -270,11 +390,51 @@ LIMIT 1",
 }
 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
+       // Determine depleted user account
+       $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
+
+       // Get amount from database
+       $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
+FROM "._MYSQL_PREFIX."_surfbar_urls
+WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
+               array($status), __FILE__, __LINE__
+       );
+
+       // Fetch row
+       list($cnt) = SQL_FETCHROW($result);
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return result
+       return $cnt;
+}
+// Check wether the user is allowed to book more URLs
+function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
+       global $_CONFIG;
+
+       // Simply check it out
+       return (SURFBAR_GET_TOTAL_USER_URLS($uid) < $_CONFIG['surfbar_max_order']);
+}
+// Get total amount of URLs of given status for current user
+function SURFBAR_GET_TOTAL_USER_URLS ($uid=0) {
+       global $_CONFIG;
+
+       // Is the user 0 and user is logged in?
+       if (($uid == 0) && (IS_MEMBER())) {
+               // Then use this userid
+               $uid = $GLOBALS['userid'];
+       } elseif ($uid == 0) {
+               // Error!
+               return ($_CONFIG['surfbar_max_order'] + 1);
+       }
+
        // Get amount from database
        $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
 FROM "._MYSQL_PREFIX."_surfbar_urls
-WHERE userid != %d AND status='%s'",
-               array($GLOBALS['userid'], $status), __FILE__, __LINE__
+WHERE userid=%s
+LIMIT %s",
+               array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
        );
 
        // Fetch row
@@ -290,29 +450,41 @@ WHERE userid != %d AND status='%s'",
 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
        global $_CONFIG, $SURFBAR_CACHE;
 
+       // @TODO Invalid salt should be refused
+       $SURFBAR_CACHE['salt'] = "INVALID";
+
+       // Get code length from config
+       $length = $_CONFIG['code_length'];
+
+       // Fix length to 10
+       if ($length == 0) $length = 10;
+
        // Generate a code until the length matches
        $valCode = "";
-       while (strlen($valCode) != $_CONFIG['code_length']) {
+       while (strlen($valCode) != $length) {
                // Is the salt set?
                if (empty($salt)) {
                        // Generate random hashed string
                        $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
+                       //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
                } else {
                        // Use this as salt!
                        $SURFBAR_CACHE['salt'] = $salt;
+                       //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
                }
-               //* DEBUG: */ echo __FUNCTION__.":".SURFBAR_GET_SALT()."*<br />\n";
 
                // ... and now the validation code
-               $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
-               //* DEBUG: */ echo __FUNCTION__.":valCode={$valCode}<br />\n";
+               $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
+               //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
        } // END - while
 
        // Hash it with md5() and salt it with the random string
        $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
 
        // Finally encrypt it PGP-like and return it
-       return generatePassString($hashedCode);
+       $valHashedCode = generatePassString($hashedCode);
+       //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
+       return $valHashedCode;
 }
 // Check validation code
 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
@@ -325,14 +497,14 @@ function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
        $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
 
        // Return result of checking hashes and salts
-       //* DEBUG: */ echo __FUNCTION__.":---".$code."---<br />\n---".$check."---<br />\n";
-       //* DEBUG: */ echo __FUNCTION__.":+++".$salt."+++<br />\n+++".SURFBAR_GET_DATA('last_salt')."+++<br />\n";
+       //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
+       //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
        return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
 }
 // Lockdown the userid/id combination (reload lock)
 function SURFBAR_LOCKDOWN_ID ($id) {
-       //* DEBUG: */ print "LOCK!<br />\n";
-       //DEBUG: */ return;
+       //* //DEBUG: */ print "LOCK!");
+       ///* //DEBUG: */ return;
        // Just add it to the database
        SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
                array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
@@ -343,28 +515,56 @@ function SURFBAR_LOCKDOWN_ID ($id) {
 }
 // Pay points to the user and remove it from the sender
 function SURFBAR_PAY_POINTS ($id) {
-       global $SURFBAR_CACHE, $_CONFIG;
-
-       // Re-configure ref-system to surfbar levels
-       $_CONFIG['db_percents'] = "percent";
-       $_CONFIG['db_table']    = "surfbar_reflevels";
+       // Remove it from the URL owner
+       //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
+       if (SURFBAR_GET_USERID() > 0) {
+               SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
+       } // END - if
 
        // Book it to the user
+       //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
        ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
-
-       // Remove it from the URL owner
-       SUB_POINTS($SURFBAR_CACHE['userid'], SURFBAR_GET_DATA('costs'));
 }
-// Update the salt for validation
-function SURFBAR_UPDATE_SALT() {
+// Updates the statistics of current URL/userid
+function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
+       global $_CONFIG;
+
        // Update views_total
        SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
                array(SURFBAR_GET_ID()), __FILE__, __LINE__);
 
+       // Update the stats entry
+       SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
+               array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
+
+       // Was that update okay?
+       if (SQL_AFFECTEDROWS() == 0) {
+               // No, then insert entry
+               SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
+                       array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
+       } // END - if
+
+       // Update total/daily/weekly/monthly counter
+       $_CONFIG['surfbar_total_counter']++;
+       $_CONFIG['surfbar_daily_counter']++;
+       $_CONFIG['surfbar_weekly_counter']++;
+       $_CONFIG['surfbar_monthly_counter']++;
+
+       // Update config as well
+       UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
+}
+// Update the salt for validation and statistics
+function SURFBAR_UPDATE_SALT_STATS () {
+       // Update statistics record
+       SURFBAR_UPDATE_INSERT_STATS_RECORD();
+
        // Simply store the salt from cache away in database...
        SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
                array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
 
+       // Debug message
+       //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
+
        // Was that okay?
        if (SQL_AFFECTEDROWS() == 0) {
                // Insert missing entry!
@@ -372,12 +572,15 @@ function SURFBAR_UPDATE_SALT() {
                        array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
        } // END - if
 
+       // Debug message
+       //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
+
        // Return if the update was okay
        return (SQL_AFFECTEDROWS() == 1);
 }
 // Check if the reload lock is active for given id
 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
-       //* DEBUG: */ echo __FUNCTION__.":id={$id}<br />\n";
+       //DEBUG_LOG(__FUNCTION__.":id={$id}");
        // Ask the database
        $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
 FROM "._MYSQL_PREFIX."_surfbar_locks
@@ -394,51 +597,274 @@ LIMIT 1",
        SQL_FREERESULT($result);
 
        // Return check
-       //* DEBUG: */ echo __FUNCTION__.":cnt={$cnt}<br />\n";
+       //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
        return ($cnt == 1);
 }
-// Determine next id for surfbar view, always call this before you call other
+// Determine which user hash no more points left
+function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
+       // Init array
+       $UIDs = array();
+
+       // Do we have a current user id?
+       if (IS_MEMBER()) {
+               // Then add this as well
+               $UIDs[] = $GLOBALS['userid'];
+
+               // Get all userid except logged in one
+               $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
+WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
+GROUP BY userid
+ORDER BY userid ASC",
+                       array($GLOBALS['userid']), __FILE__, __LINE__);
+       } else {
+               // Get all userid
+               $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
+WHERE status='CONFIRMED'
+GROUP BY userid
+ORDER BY userid ASC", __FILE__, __LINE__);
+       }
+
+       // Load all userid
+       while (list($uid) = SQL_FETCHROW($result)) {
+               // Get total points
+               $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
+               //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
+
+               // Shall we add this to ignore?
+               if ($points <= 0) {
+                       // Ignore this one!
+                       //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
+                       $UIDs[] = $uid;
+               } // END - if
+       } // END - while
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Debug message
+       //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
+
+       // Return result
+       return $UIDs;
+}
+// Determine how many users are Online in surfbar
+function SURFBAR_DETERMINE_TOTAL_ONLINE () {
+       global $_CONFIG;
+
+       // Count all users in surfbar modue and return the value
+       $result = SQL_QUERY_ESC("SELECT id
+FROM "._MYSQL_PREFIX."_surfbar_stats
+WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
+GROUP BY userid",
+               array($_CONFIG['online_timeout']), __FILE__, __LINE__);
+
+       // Fetch count
+       $cnt = SQL_NUMROWS($result);
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return result
+       return $cnt;
+}
+// Determine waiting time for one URL 
+function SURFBAR_DETERMINE_WAIT_TIME () {
+       global $_CONFIG;
+
+       // Init time
+       $time = 0;
+
+       // Which payment model do we have?
+       if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
+               // Static model
+               $time = $_CONFIG['surfbar_static_time'];
+       } else {
+               // Dynamic
+               die("DYNAMIC payment model not yet finished!");
+       }
+
+       // Return value
+       return $time;
+}
+// Changes the status of an URL from given to other
+function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
+       // Get URL data for status comparison
+       $data = SURFBAR_GET_URL_DATA($id);
+
+       // Is the status like prevStatus is saying?
+       if ($data[$id]['status'] != $prevStatus) {
+               // No, then abort here
+               return false;
+       } // END - if
+
+       // Update the status now
+       SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
+               array($newStatus, bigintval($id)), __FILE__, __LINE__);
+
+       // Was that fine?
+       if (SQL_AFFECTEDROWS() != 1) {
+               // No, something went wrong
+               return false;
+       } // END - if
+
+       // Prepare content for notification routines
+       $data[$id]['uid']         = $data[$id]['userid'];
+       $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
+       $data[$id]['reward']      = TRANSLATE_COMMA($data[$id]['reward']);
+       $data[$id]['costs']       = TRANSLATE_COMMA($data[$id]['costs']);
+       $data[$id]['status']      = SURFBAR_TRANSLATE_STATUS($newStatus);
+       $data[$id]['registered']  = MAKE_DATETIME($data[$id]['registered'], "2");
+       $newStatus = strtolower($newStatus);
+
+       // Send admin notification
+       SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
+
+       // Send user notification
+       SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
+
+       // All done!
+       return true;
+}
+// "Getter" for lock ids array
+function SURFBAR_GET_LOCK_IDS () {
+       // Prepare some arrays
+       $IDs = array();
+       $USE = array();
+       $ignored = array();
+
+       // Get all id from locks within the timestamp
+       $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
+FROM
+       "._MYSQL_PREFIX."_surfbar_locks
+WHERE
+       userid=%s
+ORDER BY
+       id ASC", array($GLOBALS['userid']),
+               __FILE__, __LINE__);
+
+       // Load all entries
+       while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
+               // Debug message
+               //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
+
+               // Skip entries that are too old
+               if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
+                       // Debug message
+                       //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
+
+                       // Add only if missing or bigger
+                       if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
+                               // Debug message
+                               //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
+
+                               // Add this ID
+                               $IDs[$url] = $last;
+                               $USE[$url] = $lid;
+                       } // END - if
+               } else {
+                       // Debug message
+                       //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
+
+                       // Ignore these old entries!
+                       $ignored[] = $url;
+                       unset($IDs[$url]);
+                       unset($USE[$url]);
+               }
+       } // END - while
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return array
+       return $USE;
+}
+// "Getter" for maximum random number
+function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
+       global $_CONFIG;
+       // Count max availabe entries
+       $result = SQL_QUERY("SELECT sbu.id AS cnt
+FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
+LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
+ON sbu.id=sbs.url_id
+LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
+ON sbu.id=l.url_id
+WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
+GROUP BY sbu.id", __FILE__, __LINE__);
+
+       // Log last query
+       //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
+
+       // Fetch max rand
+       $maxRand = SQL_NUMROWS($result);
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return value
+       return $maxRand;
+}
+// Determine next id for surfbar or get data for given id, always call this before you call other
 // getters below this function!!!
-function SURFBAR_GET_NEXT_ID ($id = 0) {
+function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
        global $SURFBAR_CACHE, $_CONFIG;
 
-       // Default is no id!
-       $nextId = 0; $randNum = 0;
+       // Default is no id and no random number
+       $nextId = 0;
+       $randNum = 0;
 
        // Is the ID set?
        if ($id == 0) {
-               // Set max random factor to total URLs minus 1
-               $maxRand = SURFBAR_GET_TOTAL_URLS() - 1;
+               // Get array with lock ids
+               $USE = SURFBAR_GET_LOCK_IDS();
+
+               // Shall we add some URL ids to ignore?
+               $ADD = "";
+               if (count($USE) > 0) {
+                       // Ignore some!
+                       $ADD = " AND sbu.id NOT IN (";
+                       foreach ($USE as $url_id => $lid) {
+                               // Add URL id
+                               $ADD .= $url_id.",";
+                       } // END - foreach
+
+                       // Add closing bracket
+                       $ADD = substr($ADD, 0, -1) . ")";
+               } // END - if
+
+               // Determine depleted user account
+               $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
+
+               // Get maximum randomness factor
+               $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
 
                // If more than one URL can be called generate the random number!
                if ($maxRand > 1) {
                        // Generate random number
-                       $randNum = mt_rand(0, $maxRand);
+                       $randNum = mt_rand(0, ($maxRand - 1));
                } // END - if
 
                // And query the database
-               //* DEBUG: */ echo __FUNCTION__.":randNum={$randNum},maxRand={$maxRand}<br />\n";
-               $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
+               //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
+               $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
-LEFT JOIN "._MYSQL_PREFIX."_payments AS p
-ON sbu.payment_id=p.id
 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
 ON sbu.id=sbs.url_id
 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
 ON sbu.id=l.url_id
-WHERE sbu.userid != %d AND sbu.status='CONFIRMED' AND (l.last_surfed IS NULL OR (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") >= UNIX_TIMESTAMP(l.last_surfed))
-ORDER BY l.last_surfed DESC, sbs.last_salt ASC, sbu.id ASC
-LIMIT %d,1",
-                       array($GLOBALS['userid'], $randNum), __FILE__, __LINE__
+WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
+GROUP BY sbu.id
+ORDER BY l.last_surfed ASC, sbu.id ASC
+LIMIT %s,1",
+                       array($randNum), __FILE__, __LINE__
                );
        } else {
                // Get data from specified id number
-               $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, p.time
+               $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
-LEFT JOIN "._MYSQL_PREFIX."_payments AS p
-ON sbu.payment_id=p.id
 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
 ON sbu.id=sbs.url_id
+LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
+ON sbu.id=l.url_id
 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
 LIMIT 1",
                        array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
@@ -446,40 +872,42 @@ LIMIT 1",
        }
 
        // Is there an id number?
+       //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
        if (SQL_NUMROWS($result) == 1) {
                // Load/cache data
-               //* DEBUG: */ echo __FUNCTION__.":".count($SURFBAR_CACHE)."*<br />\n";
+               //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
                $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
-               //* DEBUG: */ echo __FUNCTION__.":".count($SURFBAR_CACHE)."*<br />\n";
+               //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
 
-               // Is the time there?
-               if (is_null($SURFBAR_CACHE['time'])) {
-                       // Then repair it wit the static!
-                       $SURFBAR_CACHE['time'] = $_CONFIG['surfbar_static_time'];
-               } // END - if
+               // Determine waiting time
+               $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
 
                // Is the last salt there?
                if (is_null($SURFBAR_CACHE['last_salt'])) {
                        // Then repair it wit the static!
+                       //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
                        $SURFBAR_CACHE['last_salt'] = "";
                } // END - if
 
                // Fix missing last_surfed
                if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
                        // Fix it here
-                       $SURFBAR_CACHE['last_surfed'] = "0";
+                       //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
+                       $SURFBAR_CACHE['last_surfed'] = 0;
                } // END - if
 
-               // Are we in static mode?
-               if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
-                       // Then use static reward/costs!
-                       $SURFBAR_CACHE['reward'] = $_CONFIG['surfbar_static_reward'];
-                       $SURFBAR_CACHE['costs']  = $_CONFIG['surfbar_static_costs'];
-               } else {
+               // Get base/fixed reward and costs
+               $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
+               $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
+               //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
+
+               // Only in dynamic model add the dynamic bonus!
+               if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
                        // Calculate dynamic reward/costs and add it
                        $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
                        $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
-               }
+                       //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
+               } // END - if
 
                // Now get the id
                $nextId = SURFBAR_GET_ID();
@@ -489,16 +917,17 @@ LIMIT 1",
        SQL_FREERESULT($result);
 
        // Return result
-       //* DEBUG: */ echo __FUNCTION__.":nextId={$nextId}<br />\n";
+       //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
        return $nextId;
 }
-// ----------------------------------------------------------------------------
+// -----------------------------------------------------------------------------
 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
 // $SURFBAR_CACHE ARRAY!
-// ----------------------------------------------------------------------------
+// -----------------------------------------------------------------------------
 // Private getter for data elements
 function SURFBAR_GET_DATA ($element) {
        global $SURFBAR_CACHE;
+       //DEBUG_LOG(__FUNCTION__.":element={$element}");
 
        // Default is null
        $data = null;
@@ -515,6 +944,7 @@ function SURFBAR_GET_DATA ($element) {
        }
 
        // Return result
+       //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
        return $data;
 }
 // Getter for reward from cache
@@ -542,6 +972,11 @@ function SURFBAR_GET_ID () {
        // Get data element and return its contents
        return SURFBAR_GET_DATA('id');
 }
+// Getter for userid from cache
+function SURFBAR_GET_USERID () {
+       // Get data element and return its contents
+       return SURFBAR_GET_DATA('userid');
+}
 // Getter for user reload locks
 function SURFBAR_GET_USER_RELOAD_LOCK () {
        // Get data element and return its contents