2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2008 *
4 * =============== Last change: 08/31/2008 *
6 * -------------------------------------------------------------------- *
7 * File : surfbar_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for surfbar *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die Surfbar *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
40 // -----------------------------------------------------------------------------
42 // -----------------------------------------------------------------------------
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url) {
50 } elseif (!VALIDATE_URL($url)) {
53 } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54 // URL already found in surfbar!
56 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS("0")) {
61 // Do we have fixed or dynamic payment model?
62 $reward = SURFBAR_DETERMINE_REWARD();
63 $costs = SURFBAR_DETERMINE_COSTS();
65 // Register the new URL
66 return SURFBAR_REGISTER_URL($url, "0", $reward, $costs, "0", "CONFIRMED", "unlock");
68 // Admin function for unlocking URLs
69 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
70 // Is this an admin or invalid array?
72 // Not admin or invalid IDs array
74 } elseif (!is_array($IDs)) {
77 } elseif (count($IDs) == 0) {
82 // Set to true to make AND expression valid if first URL got unlocked
85 // Update the status for all ids
86 foreach ($IDs as $id => $dummy) {
87 // Test all ids through (ignores failed)
88 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "CONFIRMED")));
91 // Return total status
95 // -----------------------------------------------------------------------------
97 // -----------------------------------------------------------------------------
99 // Member has added an URL
100 function SURFBAR_MEMBER_ADD_URL ($url) {
103 // Do some pre-checks
107 } elseif (!VALIDATE_URL($url)) {
110 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
111 // URL already found in surfbar!
113 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
118 // Do we have fixed or dynamic payment model?
119 $reward = SURFBAR_DETERMINE_REWARD();
120 $costs = SURFBAR_DETERMINE_COSTS();
122 // Register the new URL
123 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
125 // -----------------------------------------------------------------------------
127 // -----------------------------------------------------------------------------
129 // Looks up by an URL
130 function SURFBAR_LOOKUP_BY_URL ($url) {
131 // Now lookup that given URL by itself
132 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
135 return (count($urlArray) > 0);
137 // Load URL data by given search term and column
138 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
141 // By default nothing is found
142 $lastUrlData = array();
144 // Is the column an id number?
145 if (($column == "id") || ($column == "userid")) {
146 // Extra secure input
147 $searchTerm = bigintval($searchTerm);
150 // If the column is "id" there can be only one entry
152 if ($column == "id") {
156 // Look up the record
157 $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
158 FROM "._MYSQL_PREFIX."_surfbar_urls
162 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
164 // Is there at least one record?
165 if (SQL_NUMROWS($result) > 0) {
167 while ($dataRow = SQL_FETCHARRAY($result)) {
168 // Shall we group these results?
169 if ($group == "id") {
170 // Add the row by id as index
171 $lastUrlData[$dataRow['id']] = $dataRow;
174 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
180 SQL_FREERESULT($result);
185 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
186 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
189 // Make sure by the user registered URLs are always pending
190 if ($addMode == "reg") $status = "PENDING";
195 'frametester' => FRAMETESTER($url),
202 // Insert the URL into database
203 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
205 // Translate status, reward and costs
206 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
207 $content['reward'] = TRANSLATE_COMMA($content['reward']);
208 $content['costs'] = TRANSLATE_COMMA($content['costs']);
210 // If in reg-mode we notify admin
211 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
212 // Notify admin even when he as unlocked an email
213 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
217 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
219 // Return the insert id
220 return $content['insert_id'];
222 // Inserts an url by given data array and return the insert id
223 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
225 $uid = bigintval($urlData['uid']);
228 if (empty($uid)) $uid = "0";
230 // Just run the insert query for now
231 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, status) VALUES('%s', '%s', %s, %s, '%s')",
235 (float)$urlData['reward'],
236 (float)$urlData['costs'],
238 ), __FILE__, __LINE__
242 return SQL_INSERTID();
244 // Notify admin(s) with a selected message and content
245 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
246 // Prepare template name
247 $templateName = sprintf("admin_surfbar_%s", $messageType);
250 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
251 strtoupper($messageType)
255 // Send the notification out
256 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
258 // Notify the user about the performed action
259 function SURFBAR_NOTIFY_USER ($messageType, $content) {
260 // Skip notification if userid is zero
261 if ($content['uid'] == 0) {
265 // Prepare template name
266 $templateName = sprintf("member_surfbar_%s", $messageType);
269 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
270 strtoupper($messageType)
275 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
278 return SEND_EMAIL($content['uid'], $subject, $mailText);
280 // Translate the URL status
281 function SURFBAR_TRANSLATE_STATUS ($status) {
282 // Create constant name
283 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
285 // Set default translated status
286 $statusTranslated = "!".$constantName."!";
288 // Generate eval() command
289 if (defined($constantName)) {
290 $eval = "\$statusTranslated = ".$constantName.";";
295 return $statusTranslated;
298 function SURFBAR_DETERMINE_REWARD () {
301 // Do we have static or dynamic?
302 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
303 // Static model, so choose static values
304 $reward = $_CONFIG['surfbar_static_reward'];
306 // Dynamic model, so calculate values
307 die("DYNAMIC payment model not yet supported!");
314 function SURFBAR_DETERMINE_COSTS () {
317 // Do we have static or dynamic?
318 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
319 $costs = $_CONFIG['surfbar_static_costs'];
321 // Dynamic model, so calculate values
322 die("DYNAMIC payment model not yet supported!");
328 // Determine right template name
329 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
330 // Default is the frameset
331 $templateName = "surfbar_frameset";
333 // Any frame set? ;-)
334 if (isset($_GET['frame'])) {
335 // Use the frame as a template name part... ;-)
336 $templateName = sprintf("surfbar_frame_%s",
337 SQL_ESCAPE($_GET['frame'])
342 return $templateName;
344 // Check if the "reload lock" of the current user is full, call this function
345 // before you call SURFBAR_CHECK_RELOAD_LOCK().
346 function SURFBAR_CHECK_RELOAD_FULL() {
347 global $SURFBAR_CACHE, $_CONFIG;
352 // Do we have static or dynamic mode?
353 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
354 // Cache static reload lock
355 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
356 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
359 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
360 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
362 array($GLOBALS['userid']), __FILE__, __LINE__
366 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
369 if (is_null($SURFBAR_CACHE['user_locks'])) {
370 // Then fix it to zero!
371 $SURFBAR_CACHE['user_locks'] = 0;
375 SQL_FREERESULT($result);
378 $total = SURFBAR_GET_TOTAL_URLS();
380 // Do we have some URLs in lock? Admins can always surf on own URLs!
381 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
382 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
385 die("DYNAMIC not yet implemented!");
391 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
392 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
393 // Determine depleted user account
394 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
396 // Get amount from database
397 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
398 FROM "._MYSQL_PREFIX."_surfbar_urls
399 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
400 array($status), __FILE__, __LINE__
404 list($cnt) = SQL_FETCHROW($result);
407 SQL_FREERESULT($result);
412 // Check wether the user is allowed to book more URLs
413 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
416 // Simply check it out
417 return (SURFBAR_GET_TOTAL_USER_URLS($uid) < $_CONFIG['surfbar_max_order']);
419 // Get total amount of URLs of given status for current user
420 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0) {
423 // Is the user 0 and user is logged in?
424 if (($uid == 0) && (IS_MEMBER())) {
425 // Then use this userid
426 $uid = $GLOBALS['userid'];
427 } elseif ($uid == 0) {
429 return ($_CONFIG['surfbar_max_order'] + 1);
432 // Get amount from database
433 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
434 FROM "._MYSQL_PREFIX."_surfbar_urls
437 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
441 list($cnt) = SQL_FETCHROW($result);
444 SQL_FREERESULT($result);
449 // Generate a validation code for the given id number
450 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
451 global $_CONFIG, $SURFBAR_CACHE;
453 // Generate a code until the length matches
455 while (strlen($valCode) != $_CONFIG['code_length']) {
458 // Generate random hashed string
459 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
460 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
463 $SURFBAR_CACHE['salt'] = $salt;
464 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
467 // ... and now the validation code
468 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
469 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
472 // Hash it with md5() and salt it with the random string
473 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
475 // Finally encrypt it PGP-like and return it
476 $valHashedCode = generatePassString($hashedCode);
477 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
478 return $valHashedCode;
480 // Check validation code
481 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
482 global $SURFBAR_CACHE;
485 $id = bigintval($id);
487 // Now generate the code again
488 $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
490 // Return result of checking hashes and salts
491 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
492 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
493 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
495 // Lockdown the userid/id combination (reload lock)
496 function SURFBAR_LOCKDOWN_ID ($id) {
497 //* //DEBUG: */ print "LOCK!");
498 ///* //DEBUG: */ return;
499 // Just add it to the database
500 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
501 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
503 // Remove the salt from database
504 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
505 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
507 // Pay points to the user and remove it from the sender
508 function SURFBAR_PAY_POINTS ($id) {
509 // Remove it from the URL owner
510 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
511 if (SURFBAR_GET_USERID() > 0) {
512 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
515 // Book it to the user
516 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
517 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
519 // Updates the statistics of current URL/userid
520 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
523 // Update views_total
524 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
525 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
527 // Update the stats entry
528 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
529 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
531 // Was that update okay?
532 if (SQL_AFFECTEDROWS() == 0) {
533 // No, then insert entry
534 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
535 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
538 // Update total/daily/weekly/monthly counter
539 $_CONFIG['surfbar_total_counter']++;
540 $_CONFIG['surfbar_daily_counter']++;
541 $_CONFIG['surfbar_weekly_counter']++;
542 $_CONFIG['surfbar_monthly_counter']++;
544 // Update config as well
545 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
547 // Update the salt for validation and statistics
548 function SURFBAR_UPDATE_SALT_STATS () {
549 // Update statistics record
550 SURFBAR_UPDATE_INSERT_STATS_RECORD();
552 // Simply store the salt from cache away in database...
553 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
554 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
557 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
560 if (SQL_AFFECTEDROWS() == 0) {
561 // Insert missing entry!
562 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
563 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
567 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
569 // Return if the update was okay
570 return (SQL_AFFECTEDROWS() == 1);
572 // Check if the reload lock is active for given id
573 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
574 //DEBUG_LOG(__FUNCTION__.":id={$id}");
576 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
577 FROM "._MYSQL_PREFIX."_surfbar_locks
578 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
579 ORDER BY last_surfed ASC
581 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
585 list($cnt) = SQL_FETCHROW($result);
588 SQL_FREERESULT($result);
591 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
594 // Determine which user hash no more points left
595 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
599 // Do we have a current user id?
601 // Then add this as well
602 $UIDs[] = $GLOBALS['userid'];
604 // Get all userid except logged in one
605 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
606 WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
608 ORDER BY userid ASC",
609 array($GLOBALS['userid']), __FILE__, __LINE__);
612 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
613 WHERE status='CONFIRMED'
615 ORDER BY userid ASC", __FILE__, __LINE__);
619 while (list($uid) = SQL_FETCHROW($result)) {
621 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
622 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
624 // Shall we add this to ignore?
627 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
633 SQL_FREERESULT($result);
636 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
641 // Determine how many users are Online in surfbar
642 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
645 // Count all users in surfbar modue and return the value
646 $result = SQL_QUERY_ESC("SELECT id
647 FROM "._MYSQL_PREFIX."_surfbar_stats
648 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
650 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
653 $cnt = SQL_NUMROWS($result);
656 SQL_FREERESULT($result);
661 // Determine waiting time for one URL
662 function SURFBAR_DETERMINE_WAIT_TIME () {
668 // Which payment model do we have?
669 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
671 $time = $_CONFIG['surfbar_static_time'];
674 die("DYNAMIC payment model not yet finished!");
680 // Changes the status of an URL from given to other
681 function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
682 // Get URL data for status comparison
683 $data = SURFBAR_GET_URL_DATA($id);
685 // Is the status like prevStatus is saying?
686 if ($data[$id]['status'] != $prevStatus) {
687 // No, then abort here
691 // Update the status now
692 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
693 array($newStatus, bigintval($id)), __FILE__, __LINE__);
696 if (SQL_AFFECTEDROWS() != 1) {
697 // No, something went wrong
701 // Prepare content for notification routines
702 $data[$id]['uid'] = $data[$id]['userid'];
703 $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
704 $data[$id]['reward'] = TRANSLATE_COMMA($data[$id]['reward']);
705 $data[$id]['costs'] = TRANSLATE_COMMA($data[$id]['costs']);
706 $data[$id]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
707 $data[$id]['registered'] = MAKE_DATETIME($data[$id]['registered'], "2");
708 $newStatus = strtolower($newStatus);
710 // Send admin notification
711 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
713 // Send user notification
714 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
719 // "Getter" for lock ids array
720 function SURFBAR_GET_LOCK_IDS () {
721 // Prepare some arrays
726 // Get all id from locks within the timestamp
727 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
729 "._MYSQL_PREFIX."_surfbar_locks
733 id ASC", array($GLOBALS['userid']),
737 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
739 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
741 // Skip entries that are too old
742 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
744 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
746 // Add only if missing or bigger
747 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
749 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
757 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
759 // Ignore these old entries!
767 SQL_FREERESULT($result);
772 // "Getter" for maximum random number
773 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
775 // Count max availabe entries
776 $result = SQL_QUERY("SELECT sbu.id AS cnt
777 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
778 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
780 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
782 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
783 GROUP BY sbu.id", __FILE__, __LINE__);
786 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
789 $maxRand = SQL_NUMROWS($result);
792 SQL_FREERESULT($result);
797 // Determine next id for surfbar or get data for given id, always call this before you call other
798 // getters below this function!!!
799 function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
800 global $SURFBAR_CACHE, $_CONFIG;
802 // Default is no id and no random number
808 // Get array with lock ids
809 $USE = SURFBAR_GET_LOCK_IDS();
811 // Shall we add some URL ids to ignore?
813 if (count($USE) > 0) {
815 $ADD = " AND sbu.id NOT IN (";
816 foreach ($USE as $url_id => $lid) {
821 // Add closing bracket
822 $ADD = substr($ADD, 0, -1) . ")";
825 // Determine depleted user account
826 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
828 // Get maximum randomness factor
829 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
831 // If more than one URL can be called generate the random number!
833 // Generate random number
834 $randNum = mt_rand(0, ($maxRand - 1));
837 // And query the database
838 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
839 $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
840 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
841 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
843 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
845 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
847 ORDER BY l.last_surfed ASC, sbu.id ASC
849 array($randNum), __FILE__, __LINE__
852 // Get data from specified id number
853 $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
854 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
855 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
857 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
859 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
861 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
865 // Is there an id number?
866 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
867 if (SQL_NUMROWS($result) == 1) {
869 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
870 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
871 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
873 // Determine waiting time
874 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
876 // Is the last salt there?
877 if (is_null($SURFBAR_CACHE['last_salt'])) {
878 // Then repair it wit the static!
879 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
880 $SURFBAR_CACHE['last_salt'] = "";
883 // Fix missing last_surfed
884 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
886 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
887 $SURFBAR_CACHE['last_surfed'] = "0";
890 // Get base/fixed reward and costs
891 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
892 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
893 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
895 // Only in dynamic model add the dynamic bonus!
896 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
897 // Calculate dynamic reward/costs and add it
898 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
899 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
900 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
904 $nextId = SURFBAR_GET_ID();
908 SQL_FREERESULT($result);
911 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
914 // -----------------------------------------------------------------------------
915 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
916 // $SURFBAR_CACHE ARRAY!
917 // -----------------------------------------------------------------------------
918 // Private getter for data elements
919 function SURFBAR_GET_DATA ($element) {
920 global $SURFBAR_CACHE;
921 //DEBUG_LOG(__FUNCTION__.":element={$element}");
926 // Is the entry there?
927 if (isset($SURFBAR_CACHE[$element])) {
929 $data = $SURFBAR_CACHE[$element];
932 print_r($SURFBAR_CACHE);
933 debug_print_backtrace();
938 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
941 // Getter for reward from cache
942 function SURFBAR_GET_REWARD () {
943 // Get data element and return its contents
944 return SURFBAR_GET_DATA('reward');
946 // Getter for costs from cache
947 function SURFBAR_GET_COSTS () {
948 // Get data element and return its contents
949 return SURFBAR_GET_DATA('costs');
951 // Getter for URL from cache
952 function SURFBAR_GET_URL () {
953 // Get data element and return its contents
954 return SURFBAR_GET_DATA('url');
956 // Getter for salt from cache
957 function SURFBAR_GET_SALT () {
958 // Get data element and return its contents
959 return SURFBAR_GET_DATA('salt');
961 // Getter for id from cache
962 function SURFBAR_GET_ID () {
963 // Get data element and return its contents
964 return SURFBAR_GET_DATA('id');
966 // Getter for userid from cache
967 function SURFBAR_GET_USERID () {
968 // Get data element and return its contents
969 return SURFBAR_GET_DATA('userid');
971 // Getter for user reload locks
972 function SURFBAR_GET_USER_RELOAD_LOCK () {
973 // Get data element and return its contents
974 return SURFBAR_GET_DATA('user_locks');
976 // Getter for reload time
977 function SURFBAR_GET_RELOAD_TIME () {
978 // Get data element and return its contents
979 return SURFBAR_GET_DATA('time');