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, $uid, $reward, $costs, $paymentId) {
50 } elseif (!VALIDATE_URL($url)) {
53 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
54 // URL already found in surfbar!
56 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
61 // Register the new URL
62 return SURFBAR_REGISTER_URL($url, $uid, $reward, $costs, $paymentId, "CONFIRMED", "unlock");
64 // Admin function for unlocking URLs
65 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
66 // Is this an admin or invalid array?
68 // Not admin or invalid IDs array
70 } elseif (!is_array($IDs)) {
73 } elseif (count($IDs) == 0) {
78 // Set to true to make AND expression valid if first URL got unlocked
81 // Update the status for all ids
82 foreach ($IDs as $id => $dummy) {
83 // Test all ids through (ignores failed)
84 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "CONFIRMED")));
87 // Return total status
91 // -----------------------------------------------------------------------------
93 // -----------------------------------------------------------------------------
95 // Member has added an URL
96 function SURFBAR_MEMBER_ADD_URL ($url) {
100 if (!IS_LOGGED_IN()) {
103 } elseif (!VALIDATE_URL($url)) {
106 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
107 // URL already found in surfbar!
109 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
114 // Do we have fixed or dynamic payment model?
115 $reward = SURFBAR_DETERMINE_REWARD();
116 $costs = SURFBAR_DETERMINE_COSTS();
118 // Register the new URL
119 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
121 // -----------------------------------------------------------------------------
123 // -----------------------------------------------------------------------------
125 // Looks up by an URL
126 function SURFBAR_LOOKUP_BY_URL ($url) {
127 // Now lookup that given URL by itself
128 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
131 return (count($urlArray) > 0);
133 // Load URL data by given search term and column
134 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
137 // By default nothing is found
138 $lastUrlData = array();
140 // Is the column an id number?
141 if (($column == "id") || ($column == "userid")) {
142 // Extra secure input
143 $searchTerm = bigintval($searchTerm);
146 // If the column is "id" there can be only one entry
148 if ($column == "id") {
152 // Look up the record
153 $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
154 FROM "._MYSQL_PREFIX."_surfbar_urls
158 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
160 // Is there at least one record?
161 if (SQL_NUMROWS($result) > 0) {
163 while ($dataRow = SQL_FETCHARRAY($result)) {
164 // Shall we group these results?
165 if ($group == "id") {
166 // Add the row by id as index
167 $lastUrlData[$dataRow['id']] = $dataRow;
170 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
176 SQL_FREERESULT($result);
181 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
182 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
185 // Make sure by the user registered URLs are always pending
186 if ($addMode == "reg") $status = "PENDING";
191 'frametester' => FRAMETESTER($url),
195 'payment_id' => $paymentId,
199 // Insert the URL into database
200 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
202 // Translate status, reward and costs
203 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
204 $content['reward'] = TRANSLATE_COMMA($content['reward']);
205 $content['costs'] = TRANSLATE_COMMA($content['costs']);
207 // If in reg-mode we notify admin
208 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
209 // Notify admin even when he as unlocked an email
210 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
214 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
216 // Return the insert id
217 return $content['insert_id'];
219 // Inserts an url by given data array and return the insert id
220 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
221 // Just run the insert query for now
222 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, payment_id, status) VALUES(%s, '%s', %s, %s, %d, '%s')",
224 bigintval($urlData['uid']),
226 (float)$urlData['reward'],
227 (float)$urlData['costs'],
228 bigintval($urlData['payment_id']),
230 ), __FILE__, __LINE__
234 return SQL_INSERTID();
236 // Notify admin(s) with a selected message and content
237 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
238 // Prepare template name
239 $templateName = sprintf("admin_surfbar_%s", $messageType);
242 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
243 strtoupper($messageType)
247 // Send the notification out
248 SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
250 // Notify the user about the performed action
251 function SURFBAR_NOTIFY_USER ($messageType, $content) {
252 // Prepare template name
253 $templateName = sprintf("member_surfbar_%s", $messageType);
256 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
257 strtoupper($messageType)
262 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
265 SEND_EMAIL($content['uid'], $subject, $mailText);
267 // Translate the URL status
268 function SURFBAR_TRANSLATE_STATUS ($status) {
269 // Create constant name
270 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
272 // Set default translated status
273 $statusTranslated = "!".$constantName."!";
275 // Generate eval() command
276 if (defined($constantName)) {
277 $eval = "\$statusTranslated = ".$constantName.";";
282 return $statusTranslated;
285 function SURFBAR_DETERMINE_REWARD () {
288 // Do we have static or dynamic?
289 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
290 // Static model, so choose static values
291 $reward = $_CONFIG['surfbar_static_reward'];
293 // Dynamic model, so calculate values
294 die("DYNAMIC payment model not yet supported!");
301 function SURFBAR_DETERMINE_COSTS () {
304 // Do we have static or dynamic?
305 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
306 $costs = $_CONFIG['surfbar_static_costs'];
308 // Dynamic model, so calculate values
309 die("DYNAMIC payment model not yet supported!");
315 // Determine right template name
316 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
317 // Default is the frameset
318 $templateName = "surfbar_frameset";
320 // Any frame set? ;-)
321 if (isset($_GET['frame'])) {
322 // Use the frame as a template name part... ;-)
323 $templateName = sprintf("surfbar_frame_%s",
324 SQL_ESCAPE($_GET['frame'])
329 return $templateName;
331 // Check if the "reload lock" of the current user is full, call this function
332 // before you call SURFBAR_CHECK_RELOAD_LOCK().
333 function SURFBAR_CHECK_RELOAD_FULL() {
334 global $SURFBAR_CACHE, $_CONFIG;
339 // Do we have static or dynamic mode?
340 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
341 // Cache static reload lock
342 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
343 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
346 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
347 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
349 array($GLOBALS['userid']), __FILE__, __LINE__
353 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
356 if (is_null($SURFBAR_CACHE['user_locks'])) {
357 // Then fix it to zero!
358 $SURFBAR_CACHE['user_locks'] = 0;
362 SQL_FREERESULT($result);
365 $total = SURFBAR_GET_TOTAL_URLS();
367 // Do we have some URLs in lock? Admins can always surf on own URLs!
368 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
369 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
372 die("DYNAMIC not yet implemented!");
378 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
379 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
380 // Determine depleted user account
381 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
383 // Get amount from database
384 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
385 FROM "._MYSQL_PREFIX."_surfbar_urls
386 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
387 array($status), __FILE__, __LINE__
391 list($cnt) = SQL_FETCHROW($result);
394 SQL_FREERESULT($result);
399 // Check wether the user is allowed to book more URLs
400 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
403 // Simply check it out
404 return (SURFBAR_GET_TOTAL_USER_URLS($uid) < $_CONFIG['surfbar_max_order']);
406 // Get total amount of URLs of given status for current user
407 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0) {
410 // Is the user 0 and user is logged in?
411 if (($uid == 0) && (IS_LOGGED_IN())) {
412 // Then use this userid
413 $uid = $GLOBALS['userid'];
414 } elseif ($uid == 0) {
416 return ($_CONFIG['surfbar_max_order'] + 1);
419 // Get amount from database
420 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
421 FROM "._MYSQL_PREFIX."_surfbar_urls
424 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
428 list($cnt) = SQL_FETCHROW($result);
431 SQL_FREERESULT($result);
436 // Generate a validation code for the given id number
437 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
438 global $_CONFIG, $SURFBAR_CACHE;
440 // Generate a code until the length matches
442 while (strlen($valCode) != $_CONFIG['code_length']) {
445 // Generate random hashed string
446 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
447 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
450 $SURFBAR_CACHE['salt'] = $salt;
451 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
454 // ... and now the validation code
455 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
456 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
459 // Hash it with md5() and salt it with the random string
460 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
462 // Finally encrypt it PGP-like and return it
463 $valHashedCode = generatePassString($hashedCode);
464 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
465 return $valHashedCode;
467 // Check validation code
468 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
469 global $SURFBAR_CACHE;
472 $id = bigintval($id);
474 // Now generate the code again
475 $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
477 // Return result of checking hashes and salts
478 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
479 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
480 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
482 // Lockdown the userid/id combination (reload lock)
483 function SURFBAR_LOCKDOWN_ID ($id) {
484 //* DEBUG: */ print "LOCK!");
485 ///* DEBUG: */ return;
486 // Just add it to the database
487 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
488 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
490 // Remove the salt from database
491 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
492 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
494 // Pay points to the user and remove it from the sender
495 function SURFBAR_PAY_POINTS ($id) {
496 global $SURFBAR_CACHE, $_CONFIG;
498 // Re-configure ref-system to surfbar levels
499 $_CONFIG['db_percents'] = "percent";
500 $_CONFIG['db_table'] = "surfbar_reflevels";
502 // Remove it from the URL owner
503 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
504 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
506 // Book it to the user
507 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
508 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
510 // Updates the statistics of current URL/userid
511 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
514 // Update views_total
515 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
516 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
518 // Update the stats entry
519 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
520 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
522 // Was that update okay?
523 if (SQL_AFFECTEDROWS() == 0) {
524 // No, then insert entry
525 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
526 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
529 // Update total/daily/weekly/monthly counter
530 $_CONFIG['surfbar_total_counter']++;
531 $_CONFIG['surfbar_daily_counter']++;
532 $_CONFIG['surfbar_weekly_counter']++;
533 $_CONFIG['surfbar_monthly_counter']++;
535 // Update config as well
536 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
538 // Update the salt for validation and statistics
539 function SURFBAR_UPDATE_SALT_STATS () {
540 // Update statistics record
541 SURFBAR_UPDATE_INSERT_STATS_RECORD();
543 // Simply store the salt from cache away in database...
544 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
545 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
548 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
551 if (SQL_AFFECTEDROWS() == 0) {
552 // Insert missing entry!
553 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
554 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
558 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
560 // Return if the update was okay
561 return (SQL_AFFECTEDROWS() == 1);
563 // Check if the reload lock is active for given id
564 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
565 //DEBUG_LOG(__FUNCTION__.":id={$id}");
567 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
568 FROM "._MYSQL_PREFIX."_surfbar_locks
569 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
570 ORDER BY last_surfed ASC
572 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
576 list($cnt) = SQL_FETCHROW($result);
579 SQL_FREERESULT($result);
582 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
585 // Determine which user hash no more points left
586 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
590 // Do we have a current user id?
591 if (IS_LOGGED_IN()) {
592 // Then add this as well
593 $UIDs[] = $GLOBALS['userid'];
595 // Get all userid except logged in one
596 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
597 WHERE userid != %s AND status='CONFIRMED'
599 ORDER BY userid ASC",
600 array($GLOBALS['userid']), __FILE__, __LINE__);
603 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
604 WHERE status='CONFIRMED'
606 ORDER BY userid ASC", __FILE__, __LINE__);
610 while (list($uid) = SQL_FETCHROW($result)) {
612 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
613 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
615 // Shall we add this to ignore?
618 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
624 SQL_FREERESULT($result);
627 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
632 // Determine how many users are Online in surfbar
633 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
636 // Count all users in surfbar modue and return the value
637 $result = SQL_QUERY_ESC("SELECT COUNT(id) FROM "._MYSQL_PREFIX."_surfbar_stats WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s",
638 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
641 list($cnt) = SQL_FETCHROW($result);
644 SQL_FREERESULT($result);
649 // Changes the status of an URL from given to other
650 function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
651 // Get URL data for status comparison
652 $data = SURFBAR_GET_URL_DATA($id);
654 // Is the status like prevStatus is saying?
655 if ($data[$id]['status'] != $prevStatus) {
656 // No, then abort here
660 // Update the status now
661 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
662 array($newStatus, bigintval($id)), __FILE__, __LINE__);
665 if (SQL_AFFECTEDROWS() != 1) {
666 // No, something went wrong
670 // Prepare content for notification routines
671 $data[$id]['uid'] = $data[$id]['userid'];
672 $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
673 $data[$id]['reward'] = TRANSLATE_COMMA($data[$id]['reward']);
674 $data[$id]['costs'] = TRANSLATE_COMMA($data[$id]['costs']);
675 $data[$id]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
676 $data[$id]['registered'] = MAKE_DATETIME($data[$id]['registered'], "2");
677 $newStatus = strtolower($newStatus);
679 // Send admin notification
680 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
682 // Send user notification
683 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
688 // Determine next id for surfbar or get data for given id, always call this before you call other
689 // getters below this function!!!
690 function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
691 global $SURFBAR_CACHE, $_CONFIG;
694 $nextId = 0; $randNum = 0;
698 // Prepare some arrays
703 // Get all id from locks within the timestamp
704 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed)
706 "._MYSQL_PREFIX."_surfbar_locks
710 id ASC", array($GLOBALS['userid']),
714 while (list($id, $url, $last) = SQL_FETCHROW($result)) {
715 //DEBUG_LOG(__FUNCTION__.":next - id={$id},url={$url},last={$last}");
716 // Skip entries that are too old
717 if (($last < (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
718 //DEBUG_LOG(__FUNCTION__.":okay - id={$id},url={$url},last={$last}");
719 // Add only if missing or bigger
720 if ((!isset($IDs[$url])) || ($IDs[$url] <= $last)) {
722 //DEBUG_LOG(__FUNCTION__.":ADD - id={$id},url={$url},last={$last}");
727 // Ignore these old entries!
728 //DEBUG_LOG(__FUNCTION__.":ignore - id={$id},url={$url},last={$last}");
736 SQL_FREERESULT($result);
738 // Shall we add some ids?
740 if (count($USE) > 0) {
741 $ADD = " AND l.id IN (".implode(",", $USE).")";
744 // Determine depleted user account
745 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
747 // Count max availabe entries
748 $result = SQL_QUERY("SELECT sbu.id AS cnt
749 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
750 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
751 ON sbu.payment_id=p.id
752 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
754 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
756 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
757 GROUP BY sbu.id", __FILE__, __LINE__);
760 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
763 $maxRand = SQL_NUMROWS($result);
766 SQL_FREERESULT($result);
768 // If more than one URL can be called generate the random number!
770 // Generate random number
771 $randNum = mt_rand(0, $maxRand);
774 // And query the database
775 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
776 $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
777 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
778 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
779 ON sbu.payment_id=p.id
780 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
782 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
784 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
786 ORDER BY l.last_surfed ASC, sbu.id ASC
788 array($randNum), __FILE__, __LINE__
791 // Get data from specified id number
792 $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
793 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
794 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
795 ON sbu.payment_id=p.id
796 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
798 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
800 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
802 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
806 // Is there an id number?
807 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
808 if (SQL_NUMROWS($result) == 1) {
810 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
811 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
812 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
814 // Is the time there?
815 if (is_null($SURFBAR_CACHE['time'])) {
816 // Then repair it wit the static!
817 //DEBUG_LOG(__FUNCTION__.":time - STATIC!");
818 $SURFBAR_CACHE['time'] = $_CONFIG['surfbar_static_time'];
821 // Is the last salt there?
822 if (is_null($SURFBAR_CACHE['last_salt'])) {
823 // Then repair it wit the static!
824 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
825 $SURFBAR_CACHE['last_salt'] = "";
828 // Fix missing last_surfed
829 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
831 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
832 $SURFBAR_CACHE['last_surfed'] = "0";
835 // Get base/fixed reward and costs
836 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
837 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
838 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
840 // Only in dynamic model add the dynamic bonus!
841 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
842 // Calculate dynamic reward/costs and add it
843 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
844 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
845 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
849 $nextId = SURFBAR_GET_ID();
853 SQL_FREERESULT($result);
856 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
859 // -----------------------------------------------------------------------------
860 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
861 // $SURFBAR_CACHE ARRAY!
862 // -----------------------------------------------------------------------------
863 // Private getter for data elements
864 function SURFBAR_GET_DATA ($element) {
865 global $SURFBAR_CACHE;
866 //DEBUG_LOG(__FUNCTION__.":element={$element}");
871 // Is the entry there?
872 if (isset($SURFBAR_CACHE[$element])) {
874 $data = $SURFBAR_CACHE[$element];
877 print_r($SURFBAR_CACHE);
878 debug_print_backtrace();
883 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
886 // Getter for reward from cache
887 function SURFBAR_GET_REWARD () {
888 // Get data element and return its contents
889 return SURFBAR_GET_DATA('reward');
891 // Getter for costs from cache
892 function SURFBAR_GET_COSTS () {
893 // Get data element and return its contents
894 return SURFBAR_GET_DATA('costs');
896 // Getter for URL from cache
897 function SURFBAR_GET_URL () {
898 // Get data element and return its contents
899 return SURFBAR_GET_DATA('url');
901 // Getter for salt from cache
902 function SURFBAR_GET_SALT () {
903 // Get data element and return its contents
904 return SURFBAR_GET_DATA('salt');
906 // Getter for id from cache
907 function SURFBAR_GET_ID () {
908 // Get data element and return its contents
909 return SURFBAR_GET_DATA('id');
911 // Getter for userid from cache
912 function SURFBAR_GET_USERID () {
913 // Get data element and return its contents
914 return SURFBAR_GET_DATA('userid');
916 // Getter for user reload locks
917 function SURFBAR_GET_USER_RELOAD_LOCK () {
918 // Get data element and return its contents
919 return SURFBAR_GET_DATA('user_locks');
921 // Getter for reload time
922 function SURFBAR_GET_RELOAD_TIME () {
923 // Get data element and return its contents
924 return SURFBAR_GET_DATA('time');