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 (!defined('__SECURITY')) {
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()) {
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($GLOBALS['userid'])) {
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 // Static values are default
302 $reward = $_CONFIG['surfbar_static_reward'];
304 // Do we have static or dynamic?
305 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
306 // "Calculate" dynamic reward
307 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
313 // "Calculate" dynamic add
314 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
315 // Get min/max values
316 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
317 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
319 // "Calculate" dynamic part and return it
320 return mt_rand($min, $max);
323 function SURFBAR_DETERMINE_COSTS () {
326 // Static costs is default
327 $costs = $_CONFIG['surfbar_static_costs'];
329 // Do we have static or dynamic?
330 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
331 // "Calculate" dynamic costs
332 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
338 // Determine right template name
339 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
340 // Default is the frameset
341 $templateName = "surfbar_frameset";
343 // Any frame set? ;-)
344 if (isset($_GET['frame'])) {
345 // Use the frame as a template name part... ;-)
346 $templateName = sprintf("surfbar_frame_%s",
347 SQL_ESCAPE($_GET['frame'])
352 return $templateName;
354 // Check if the "reload lock" of the current user is full, call this function
355 // before you call SURFBAR_CHECK_RELOAD_LOCK().
356 function SURFBAR_CHECK_RELOAD_FULL() {
357 global $SURFBAR_CACHE, $_CONFIG;
362 // Cache static reload lock
363 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
364 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
366 // Do we have dynamic model?
367 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
368 // "Calculate" dynamic lock
369 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
373 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
374 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
376 array($GLOBALS['userid']), __FILE__, __LINE__
380 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
383 if (is_null($SURFBAR_CACHE['user_locks'])) {
384 // Then fix it to zero!
385 $SURFBAR_CACHE['user_locks'] = 0;
389 SQL_FREERESULT($result);
392 $total = SURFBAR_GET_TOTAL_URLS();
394 // Do we have some URLs in lock? Admins can always surf on own URLs!
395 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
396 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
401 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
402 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED", $excludeUserId="") {
403 // Determine depleted user account
404 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
406 // Is the exlude userid set?
407 if ($excludeUserId !== "") {
409 $UIDs[] = $excludeUserId;
412 // Get amount from database
413 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
414 FROM "._MYSQL_PREFIX."_surfbar_urls
415 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
416 array($status), __FILE__, __LINE__
420 list($cnt) = SQL_FETCHROW($result);
423 SQL_FREERESULT($result);
428 // Check wether the user is allowed to book more URLs
429 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
432 // Is this admin and userid is zero or does the user has some URLs left to book?
433 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid) < $_CONFIG['surfbar_max_order']));
435 // Get total amount of URLs of given status for current user
436 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="") {
439 // Is the user 0 and user is logged in?
440 if (($uid == 0) && (IS_MEMBER())) {
441 // Then use this userid
442 $uid = $GLOBALS['userid'];
443 } elseif ($uid == 0) {
445 return ($_CONFIG['surfbar_max_order'] + 1);
448 // Default is all URLs
451 // Is the status set?
452 if (!empty($status)) {
453 $ADD = sprintf(" AND status='%s'", $status);
456 // Get amount from database
457 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
458 FROM "._MYSQL_PREFIX."_surfbar_urls
459 WHERE userid=%s".$ADD."
461 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
465 list($cnt) = SQL_FETCHROW($result);
468 SQL_FREERESULT($result);
473 // Generate a validation code for the given id number
474 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
475 global $_CONFIG, $SURFBAR_CACHE;
477 // @TODO Invalid salt should be refused
478 $SURFBAR_CACHE['salt'] = "INVALID";
480 // Get code length from config
481 $length = $_CONFIG['code_length'];
484 if ($length == 0) $length = 10;
486 // Generate a code until the length matches
488 while (strlen($valCode) != $length) {
491 // Generate random hashed string
492 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
493 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
496 $SURFBAR_CACHE['salt'] = $salt;
497 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
500 // ... and now the validation code
501 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
502 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
505 // Hash it with md5() and salt it with the random string
506 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
508 // Finally encrypt it PGP-like and return it
509 $valHashedCode = generatePassString($hashedCode);
510 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
511 return $valHashedCode;
513 // Check validation code
514 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
515 global $SURFBAR_CACHE;
518 $id = bigintval($id);
520 // Now generate the code again
521 $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
523 // Return result of checking hashes and salts
524 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
525 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
526 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
528 // Lockdown the userid/id combination (reload lock)
529 function SURFBAR_LOCKDOWN_ID ($id) {
530 //* //DEBUG: */ print "LOCK!");
531 ///* //DEBUG: */ return;
532 // Just add it to the database
533 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
534 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
536 // Remove the salt from database
537 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
538 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
540 // Pay points to the user and remove it from the sender
541 function SURFBAR_PAY_POINTS ($id) {
542 // Remove it from the URL owner
543 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
544 if (SURFBAR_GET_USERID() > 0) {
545 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
548 // Book it to the user
549 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
550 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
552 // Updates the statistics of current URL/userid
553 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
556 // Update views_total
557 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
558 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
560 // Update the stats entry
561 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
562 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
564 // Was that update okay?
565 if (SQL_AFFECTEDROWS() == 0) {
566 // No, then insert entry
567 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
568 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
571 // Update total/daily/weekly/monthly counter
572 $_CONFIG['surfbar_total_counter']++;
573 $_CONFIG['surfbar_daily_counter']++;
574 $_CONFIG['surfbar_weekly_counter']++;
575 $_CONFIG['surfbar_monthly_counter']++;
577 // Update config as well
578 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
580 // Update the salt for validation and statistics
581 function SURFBAR_UPDATE_SALT_STATS () {
582 // Update statistics record
583 SURFBAR_UPDATE_INSERT_STATS_RECORD();
585 // Simply store the salt from cache away in database...
586 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
587 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
590 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
593 if (SQL_AFFECTEDROWS() == 0) {
594 // Insert missing entry!
595 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
596 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
600 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
602 // Return if the update was okay
603 return (SQL_AFFECTEDROWS() == 1);
605 // Check if the reload lock is active for given id
606 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
607 //DEBUG_LOG(__FUNCTION__.":id={$id}");
609 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
610 FROM "._MYSQL_PREFIX."_surfbar_locks
611 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
612 ORDER BY last_surfed ASC
614 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
618 list($cnt) = SQL_FETCHROW($result);
621 SQL_FREERESULT($result);
624 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
627 // Determine which user hash no more points left
628 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
632 // Do we have a current user id?
634 // Then add this as well
635 $UIDs[] = $GLOBALS['userid'];
637 // Get all userid except logged in one
638 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
639 WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
641 ORDER BY userid ASC",
642 array($GLOBALS['userid']), __FILE__, __LINE__);
645 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
646 WHERE status='CONFIRMED'
648 ORDER BY userid ASC", __FILE__, __LINE__);
652 while (list($uid) = SQL_FETCHROW($result)) {
654 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
655 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
657 // Shall we add this to ignore?
660 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
666 SQL_FREERESULT($result);
669 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
674 // Determine how many users are Online in surfbar
675 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
678 // Count all users in surfbar modue and return the value
679 $result = SQL_QUERY_ESC("SELECT id
680 FROM "._MYSQL_PREFIX."_surfbar_stats
681 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
683 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
686 $cnt = SQL_NUMROWS($result);
689 SQL_FREERESULT($result);
694 // Determine waiting time for one URL
695 function SURFBAR_DETERMINE_WAIT_TIME () {
698 // Static time is default
699 $time = $_CONFIG['surfbar_static_time'];
701 // Which payment model do we have?
702 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
703 // "Calculate" dynamic time
704 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
710 // Changes the status of an URL from given to other
711 function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
712 // Get URL data for status comparison
713 $data = SURFBAR_GET_URL_DATA($id);
715 // Is the status like prevStatus is saying?
716 if ($data[$id]['status'] != $prevStatus) {
717 // No, then abort here
721 // Update the status now
722 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
723 array($newStatus, bigintval($id)), __FILE__, __LINE__);
726 if (SQL_AFFECTEDROWS() != 1) {
727 // No, something went wrong
731 // Prepare content for notification routines
732 $data[$id]['uid'] = $data[$id]['userid'];
733 $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
734 $data[$id]['reward'] = TRANSLATE_COMMA($data[$id]['reward']);
735 $data[$id]['costs'] = TRANSLATE_COMMA($data[$id]['costs']);
736 $data[$id]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
737 $data[$id]['registered'] = MAKE_DATETIME($data[$id]['registered'], "2");
738 $newStatus = strtolower($newStatus);
740 // Send admin notification
741 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
743 // Send user notification
744 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
749 // Calculate minimum value for dynamic payment model
750 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
753 // Addon is zero by default
757 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
760 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
763 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
766 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
769 $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
771 // Get user's total URLs
772 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "CONFIRMED");
775 if ($totalUrls > 0) {
776 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
778 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
784 // Calculate maximum value for dynamic payment model
785 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
788 // Addon is zero by default
795 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
798 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
801 $addon += abs($max * $percent * $totalUsers);
804 $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
807 $addon += abs($max * $percent * $totalUrls);
812 // Calculate dynamic lock
813 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
816 // Default lock is 30 seconds
820 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
823 $addon = abs(log($onlineUsers / $addon + 1));
828 // "Getter" for lock ids array
829 function SURFBAR_GET_LOCK_IDS () {
830 // Prepare some arrays
835 // Get all id from locks within the timestamp
836 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
838 "._MYSQL_PREFIX."_surfbar_locks
842 id ASC", array($GLOBALS['userid']),
846 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
848 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
850 // Skip entries that are too old
851 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
853 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
855 // Add only if missing or bigger
856 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
858 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
866 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
868 // Ignore these old entries!
876 SQL_FREERESULT($result);
881 // "Getter" for maximum random number
882 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
884 // Count max availabe entries
885 $result = SQL_QUERY("SELECT sbu.id AS cnt
886 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
887 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
889 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
891 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
892 GROUP BY sbu.id", __FILE__, __LINE__);
895 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
898 $maxRand = SQL_NUMROWS($result);
901 SQL_FREERESULT($result);
906 // Load all URLs of the current user and return it as an array
907 function SURFBAR_GET_USER_URLS () {
912 $result = SQL_QUERY_ESC("SELECT u.id, u.url, u.views_total, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
913 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
916 array($GLOBALS['userid']), __FILE__, __LINE__);
918 // Are there entries?
919 if (SQL_NUMROWS($result) > 0) {
921 while ($row = SQL_FETCHARRAY($result)) {
923 $URLs[$row['id']] = $row;
928 SQL_FREERESULT($result);
933 // Determine next id for surfbar or get data for given id, always call this before you call other
934 // getters below this function!!!
935 function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
936 global $SURFBAR_CACHE, $_CONFIG;
938 // Default is no id and no random number
944 // Get array with lock ids
945 $USE = SURFBAR_GET_LOCK_IDS();
947 // Shall we add some URL ids to ignore?
949 if (count($USE) > 0) {
951 $ADD = " AND sbu.id NOT IN (";
952 foreach ($USE as $url_id => $lid) {
957 // Add closing bracket
958 $ADD = substr($ADD, 0, -1) . ")";
961 // Determine depleted user account
962 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
964 // Get maximum randomness factor
965 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
967 // If more than one URL can be called generate the random number!
969 // Generate random number
970 $randNum = mt_rand(0, ($maxRand - 1));
973 // And query the database
974 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
975 $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
976 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
977 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
979 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
981 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
983 ORDER BY l.last_surfed ASC, sbu.id ASC
985 array($randNum), __FILE__, __LINE__
988 // Get data from specified id number
989 $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
990 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
991 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
993 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
995 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
997 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
1001 // Is there an id number?
1002 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1003 if (SQL_NUMROWS($result) == 1) {
1005 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1006 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1007 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1009 // Determine waiting time
1010 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1012 // Is the last salt there?
1013 if (is_null($SURFBAR_CACHE['last_salt'])) {
1014 // Then repair it wit the static!
1015 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1016 $SURFBAR_CACHE['last_salt'] = "";
1019 // Fix missing last_surfed
1020 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1022 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1023 $SURFBAR_CACHE['last_surfed'] = 0;
1026 // Get base/fixed reward and costs
1027 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1028 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1029 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1031 // Only in dynamic model add the dynamic bonus!
1032 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1033 // Calculate dynamic reward/costs and add it
1034 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1035 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1036 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1040 $nextId = SURFBAR_GET_ID();
1044 SQL_FREERESULT($result);
1047 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1050 // -----------------------------------------------------------------------------
1051 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1052 // $SURFBAR_CACHE ARRAY!
1053 // -----------------------------------------------------------------------------
1054 // Private getter for data elements
1055 function SURFBAR_GET_DATA ($element) {
1056 global $SURFBAR_CACHE;
1057 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1062 // Is the entry there?
1063 if (isset($SURFBAR_CACHE[$element])) {
1065 $data = $SURFBAR_CACHE[$element];
1066 } else { // END - if
1068 print_r($SURFBAR_CACHE);
1069 debug_print_backtrace();
1074 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1077 // Getter for reward from cache
1078 function SURFBAR_GET_REWARD () {
1079 // Get data element and return its contents
1080 return SURFBAR_GET_DATA('reward');
1082 // Getter for costs from cache
1083 function SURFBAR_GET_COSTS () {
1084 // Get data element and return its contents
1085 return SURFBAR_GET_DATA('costs');
1087 // Getter for URL from cache
1088 function SURFBAR_GET_URL () {
1089 // Get data element and return its contents
1090 return SURFBAR_GET_DATA('url');
1092 // Getter for salt from cache
1093 function SURFBAR_GET_SALT () {
1094 // Get data element and return its contents
1095 return SURFBAR_GET_DATA('salt');
1097 // Getter for id from cache
1098 function SURFBAR_GET_ID () {
1099 // Get data element and return its contents
1100 return SURFBAR_GET_DATA('id');
1102 // Getter for userid from cache
1103 function SURFBAR_GET_USERID () {
1104 // Get data element and return its contents
1105 return SURFBAR_GET_DATA('userid');
1107 // Getter for user reload locks
1108 function SURFBAR_GET_USER_RELOAD_LOCK () {
1109 // Get data element and return its contents
1110 return SURFBAR_GET_DATA('user_locks');
1112 // Getter for reload time
1113 function SURFBAR_GET_RELOAD_TIME () {
1114 // Get data element and return its contents
1115 return SURFBAR_GET_DATA('time');