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, $limit) {
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()) {
59 } elseif ("".($limit + 0)."" != "".$limit."") {
60 // Invalid amount entered
64 // Register the new URL
65 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", $limit);
67 // Admin unlocked an email so we can migrate the URL
68 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
73 } elseif (!VALIDATE_URL($url)) {
76 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
77 // URL already found in surfbar!
79 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
84 // Register the new URL
85 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
87 // Admin function for unlocking URLs
88 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
89 // Is this an admin or invalid array?
91 // Not admin or invalid IDs array
93 } elseif (!is_array($IDs)) {
96 } elseif (count($IDs) == 0) {
101 // Set to true to make AND expression valid if first URL got unlocked
104 // Update the status for all ids
105 foreach ($IDs as $id => $dummy) {
106 // Test all ids through (ignores failed)
107 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
110 // Return total status
113 // Admin function for rejecting URLs
114 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
115 // Is this an admin or invalid array?
117 // Not admin or invalid IDs array
119 } elseif (!is_array($IDs)) {
122 } elseif (count($IDs) == 0) {
127 // Set to true to make AND expression valid if first URL got unlocked
130 // Update the status for all ids
131 foreach ($IDs as $id => $dummy) {
132 // Test all ids through (ignores failed)
133 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
136 // Return total status
140 // -----------------------------------------------------------------------------
142 // -----------------------------------------------------------------------------
144 // Member has added an URL
145 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
148 // Do some pre-checks
152 } elseif (!VALIDATE_URL($url)) {
155 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
156 // URL already found in surfbar!
158 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
161 } elseif ("".($limit + 0)."" != "".$limit."") {
162 // Invalid amount entered
166 // Register the new URL
167 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", $limit);
169 // Create list of actions depending on status for the user
170 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
171 // Load all actions in an array for given status
172 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
175 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
179 $width = round(100 / count($actionArray));
181 // "Walk" through all actions and create forms
182 foreach ($actionArray as $actionId=>$action) {
183 // Add form for this action
184 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
185 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
186 <input type=\"hidden\" name=\"id\" value=\"%s\" />
187 <input type=\"hidden\" name=\"action\" value=\"%s\" />
188 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
206 // Do the member form request
207 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
208 global $SURFBAR_CACHE;
210 // By default no action is performed
217 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
218 // Important form elements are missing!
220 } elseif (!isset($URLs[$formData['id']])) {
221 // ID not found in cache
223 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
224 // Action not allowed for current URL status
229 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
232 if ($action != $formData['action']) {
233 // Invalid data in action found
237 // Create the function name for selected action
238 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
240 // Is the function there?
241 if (function_exists($functionName)) {
243 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
245 // Extract URL data for call-back
246 $urlData = array(array_merge($URLs[$formData['id']], array($action => $formData)));
248 // Action found so execute it
249 $performed = call_user_func_array($functionName, $urlData);
251 // Log invalid request
252 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
253 ADD_FATAL(sprintf("Invalid member action! action=%s,id=%s,function=%s", $formData['action'], $formData['id'], $functionName));
259 // Validate if the requested action can be performed on current URL status
260 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
261 global $SURFBAR_CACHE;
263 // Search for the requested action/status combination in database
264 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
265 array($action, $status), __FILE__, __LINE__);
267 // Is the entry there?
268 $isValid = (SQL_NUMROWS($result) == 1);
270 // Fetch the new status if found
273 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
277 SQL_FREERESULT($result);
283 // -----------------------------------------------------------------------------
285 // -----------------------------------------------------------------------------
287 // Retreat a booked URL
288 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
289 // Create the data array for next function call
291 $urlData['id'] => $urlData
294 // Simply change the status here
295 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
297 // Book an URL now (from migration)
298 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
299 // Create the data array for next function call
301 $urlData['id'] => $urlData
304 // Simply change the status here
305 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
307 // Show edit form or do the changes
308 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
309 // Is the "execute" flag there?
310 if (isset($urlData['edit']['execute'])) {
311 // Execute the changes
312 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
316 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
318 // Show delete form or do the changes
319 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
320 // Is the "execute" flag there?
321 if (isset($urlData['delete']['execute'])) {
322 // Execute the changes
323 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
327 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
329 // Display selected "action form"
330 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
331 // Translate some data
332 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
333 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
334 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
335 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
336 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
338 // Is the lock reason empty?
339 if (empty($urlData['lock_reason'])) {
340 // Fix it to three dashes
341 $urlData['lock_reason'] = "---";
344 // Default is not limited
345 $urlData['limited_yes'] = "";
346 $urlData['limited_no'] = " checked=\"checked\"";
347 $urlData['limited'] = "false";
349 // Is this URL limited?
350 if ($urlData['views_max'] > 0) {
351 // Then rewrite form data
352 $urlData['limited_yes'] = " checked=\"checked\"";
353 $urlData['limited_no'] = "";
354 $urlData['limited'] = "true";
357 // Load the form and display it
358 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
360 // All fine by default ... ;-)
363 // Execute choosen action
364 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
365 // By default nothing is executed
368 // Is limitation "no" and "limit" is > 0?
369 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
370 // Set it to unlimited
371 $urlData[$action]['limit'] = 0;
374 // Construct function name
375 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
377 // Is 'userid' set and not 'uid' ?
378 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
380 $urlData['uid'] = $urlData['userid'];
383 // Is that function there?
384 if (function_exists($functionName)) {
385 // Execute the function
386 if (call_user_func_array($functionName, array($urlData)) == true) {
387 // Update status as well
388 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
392 ADD_FATAL(sprintf(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName));
398 // "Execute edit" function: Update changed data
399 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
400 // Translate URLs for testing
401 $url1 = COMPILE_CODE($urlData['url']);
402 $url2 = COMPILE_CODE($urlData['edit']['url']);
404 // Has the URL or limit changed?
405 if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
407 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET url='%s', views_allowed=%s, views_max=%s WHERE id=%s AND status='%s' LIMIT 1",
408 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
411 $urlData['new_url'] = $urlData['edit']['url'];
412 $urlData['new_limit'] = $urlData['edit']['limit'];
413 unset($urlData['edit']);
415 // Send admin notification
416 SURFBAR_NOTIFY_ADMIN("url_edited", $urlData);
418 // Send user notification
419 SURFBAR_NOTIFY_USER("url_edited", $urlData);
429 // -----------------------------------------------------------------------------
430 // Self-maintenance functions
431 // -----------------------------------------------------------------------------
434 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
435 // Handle URLs which limit has depleted so we can stop them
436 SURFBAR_HANDLE_DEPLETED_VIEWS();
438 // Handle low-points amounts
439 SURFBAR_HANDLE_LOW_POINTS();
441 // Handle URLs which limit has depleted
442 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
444 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND status='ACTIVE'");
446 // Do we have some entries?
447 if (count($urlArray) > 0) {
449 foreach ($urlArray as $id => $urlData) {
453 // Rewrite array for next call
454 $urlData[$id] = $data;
457 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
461 // Alert users which have URLs booked and are low on points amount
462 function SURFBAR_HANDLE_LOW_POINTS () {
466 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS($_CONFIG['surfbar_warn_low_points']);
468 // "Walk" through all URLs
469 foreach ($UIDs['uid'] as $uid => $dummy) {
470 // Is the last notification far enougth away to notify again?
471 if ((time() - $UIDs['notified'][$uid]) >= $_CONFIG['surfbar_low_interval']) {
475 'low' => TRANSLATE_COMMA($_CONFIG['surfbar_warn_low_points']),
476 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
477 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
478 'interval' => CREATE_FANCY_TIME($_CONFIG['surfbar_low_interval'])
482 SURFBAR_NOTIFY_USER("low_points", $content);
484 // Update last notified
485 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
486 array($uid), __FILE__, __LINE__);
491 // -----------------------------------------------------------------------------
493 // -----------------------------------------------------------------------------
495 // Looks up by an URL
496 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
497 // Now lookup that given URL by itself
498 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
501 return (count($urlArray) > 0);
503 // Load URL data by given search term and column
504 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
507 // By default nothing is found
508 $lastUrlData = array();
510 // Is the column an id number?
511 if (($column == "id") || ($column == "userid")) {
512 // Extra secure input
513 $searchTerm = bigintval($searchTerm);
516 // If the column is "id" there can be only one entry
518 if ($column == "id") {
522 // Look up the record
523 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed
524 FROM "._MYSQL_PREFIX."_surfbar_urls
525 WHERE %s='%s'".$add."
528 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
530 // Is there at least one record?
531 if (SQL_NUMROWS($result) > 0) {
533 while ($dataRow = SQL_FETCHARRAY($result)) {
534 // Shall we group these results?
535 if ($group == "id") {
536 // Add the row by id as index
537 $lastUrlData[$dataRow['id']] = $dataRow;
540 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
546 SQL_FREERESULT($result);
551 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
552 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $limit=0) {
555 // Make sure by the user registered URLs are always pending
556 if ($addMode == "reg") $status = "PENDING";
561 'frametester' => FRAMETESTER($url),
567 // Insert the URL into database
568 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
571 if ($content['insert_id'] == 0) {
572 // INSERT did not insert any data!
576 // Translate status and limit
577 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
579 // If in reg-mode we notify admin
580 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
581 // Notify admin even when he as unlocked an email
582 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
586 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
588 // Return the insert id
589 return $content['insert_id'];
591 // Inserts an url by given data array and return the insert id
592 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
594 $uid = bigintval($urlData['uid']);
597 if (empty($uid)) $uid = 0;
599 // Just run the insert query for now
600 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid,url,status,views_max,views_allowed) VALUES (%s,'%s','%s',%s,%s)",
607 ), __FILE__, __LINE__
611 return SQL_INSERTID();
613 // Notify admin(s) with a selected message and content
614 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
615 // Prepare template name
616 $templateName = sprintf("admin_surfbar_%s", $messageType);
618 // Set default subject if following eval() wents wrong
619 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
621 // Create constant name
622 $constantName = sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
623 strtoupper($messageType)
627 if (defined($constantName)) {
628 $subject = constant($constantName);
630 ADD_FATAL(ADMIN_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
633 // Translate some data if present
634 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
635 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
636 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
637 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
638 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
639 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
641 // Send the notification out
642 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
644 // Notify the user about the performed action
645 function SURFBAR_NOTIFY_USER ($messageType, $content) {
646 // Skip notification if userid is zero
647 if ($content['uid'] == 0) {
651 // Prepare template name
652 $templateName = sprintf("member_surfbar_%s", $messageType);
654 // Set default subject if following eval() wents wrong
655 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
657 // Create constant name
658 $constantName = sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
659 strtoupper($messageType)
663 if (defined($constantName)) {
664 $subject = constant($constantName);
666 ADD_FATAL(MEMBER_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
670 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
673 return SEND_EMAIL($content['uid'], $subject, $mailText);
675 // Translates the limit
676 function SURFBAR_TRANSLATE_LIMIT ($limit) {
680 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
683 $return = TRANSLATE_COMMA($limit);
689 // Translate the URL status
690 function SURFBAR_TRANSLATE_STATUS ($status) {
691 // Create constant name
692 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
694 // Set default translated status
695 $statusTranslated = "!".$constantName."!";
697 // Is the constant there?
698 if (defined($constantName)) {
699 // Then get it's value
700 $statusTranslated = constant($constantName);
704 return $statusTranslated;
707 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
710 // Static values are default
711 $reward = $_CONFIG['surfbar_static_reward'];
713 // Do we have static or dynamic?
714 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
715 // "Calculate" dynamic reward
717 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
719 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
727 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
730 // Static costs is default
731 $costs = $_CONFIG['surfbar_static_costs'];
733 // Do we have static or dynamic?
734 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
735 // "Calculate" dynamic costs
737 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
739 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
746 // "Calculate" dynamic add
747 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
748 // Get min/max values
749 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
750 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
752 // "Calculate" dynamic part and return it
753 return mt_rand($min, $max);
755 // Determine right template name
756 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
757 // Default is the frameset
758 $templateName = "surfbar_frameset";
760 // Any frame set? ;-)
761 if (isset($_GET['frame'])) {
762 // Use the frame as a template name part... ;-)
763 $templateName = sprintf("surfbar_frame_%s",
764 SQL_ESCAPE($_GET['frame'])
769 return $templateName;
771 // Check if the "reload lock" of the current user is full, call this function
772 // before you call SURFBAR_CHECK_RELOAD_LOCK().
773 function SURFBAR_CHECK_RELOAD_FULL() {
774 global $SURFBAR_CACHE, $_CONFIG;
779 // Cache static reload lock
780 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
781 //DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."", false);
783 // Do we have dynamic model?
784 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
785 // "Calculate" dynamic lock
786 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
790 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
791 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
793 array($GLOBALS['userid']), __FILE__, __LINE__
797 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
800 if (is_null($SURFBAR_CACHE['user_locks'])) {
801 // Then fix it to zero!
802 $SURFBAR_CACHE['user_locks'] = 0;
806 SQL_FREERESULT($result);
809 $total = SURFBAR_GET_TOTAL_URLS();
811 // Do we have some URLs in lock? Admins can always surf on own URLs!
812 //DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}", false);
813 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
818 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
819 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
820 // Determine depleted user account
821 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
823 // Is the exlude userid set?
824 if ($excludeUserId > 0) {
826 $UIDs['uid'][$excludeUserId] = $excludeUserId;
829 // Get amount from database
830 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
831 FROM "._MYSQL_PREFIX."_surfbar_urls
832 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
833 array($status), __FILE__, __LINE__
837 list($cnt) = SQL_FETCHROW($result);
840 SQL_FREERESULT($result);
845 // Check wether the user is allowed to book more URLs
846 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
849 // Is this admin and userid is zero or does the user has some URLs left to book?
850 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
852 // Get total amount of URLs of given status for current user
853 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
856 // Is the user 0 and user is logged in?
857 if (($uid == 0) && (IS_MEMBER())) {
858 // Then use this userid
859 $uid = $GLOBALS['userid'];
860 } elseif ($uid == 0) {
862 return ($_CONFIG['surfbar_max_order'] + 1);
865 // Default is all URLs
868 // Is the status set?
869 if (is_array($status)) {
870 // Only URLs with these status
871 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
872 } elseif (!empty($status)) {
873 // Only URLs with this status
874 $ADD = sprintf(" AND status='%s'", $status);
875 } elseif (is_array($exclude)) {
876 // Exclude URLs with these status
877 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
878 } elseif (!empty($exclude)) {
879 // Exclude URLs with this status
880 $ADD = sprintf(" AND status != '%s'", $exclude);
883 // Get amount from database
884 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
885 FROM "._MYSQL_PREFIX."_surfbar_urls
886 WHERE userid=%s".$ADD."
888 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
892 list($cnt) = SQL_FETCHROW($result);
895 SQL_FREERESULT($result);
900 // Generate a validation code for the given id number
901 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
902 global $_CONFIG, $SURFBAR_CACHE;
904 // @TODO Invalid salt should be refused
905 $SURFBAR_CACHE['salt'] = "INVALID";
907 // Get code length from config
908 $length = $_CONFIG['code_length'];
911 if ($length == 0) $length = 10;
913 // Generate a code until the length matches
915 while (strlen($valCode) != $length) {
918 // Generate random hashed string
919 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
920 //DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
923 $SURFBAR_CACHE['salt'] = $salt;
924 //DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
927 // ... and now the validation code
928 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
929 //DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
932 // Hash it with md5() and salt it with the random string
933 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
935 // Finally encrypt it PGP-like and return it
936 $valHashedCode = generatePassString($hashedCode);
938 // Return hashed value
939 //DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
940 return $valHashedCode;
942 // Check validation code
943 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
944 global $SURFBAR_CACHE;
947 $urlId = bigintval($urlId);
949 // Now generate the code again
950 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
952 // Return result of checking hashes and salts
953 //DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
954 //DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
955 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
957 // Lockdown the userid/id combination (reload lock)
958 function SURFBAR_LOCKDOWN_ID ($urlId) {
959 //* DEBUG: */ print "LOCK!");
960 ///* DEBUG: */ return;
961 // Just add it to the database
962 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES (%s, %s)",
963 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
965 // Remove the salt from database
966 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
967 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
969 // Pay points to the user and remove it from the sender
970 function SURFBAR_PAY_POINTS ($urlId) {
971 // Remove it from the URL owner
972 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
973 if (SURFBAR_GET_USERID() > 0) {
974 SUB_POINTS("surfbar", SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
977 // Book it to the user
978 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
979 ADD_POINTS_REFSYSTEM("surfbar", $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
981 // Updates the statistics of current URL/userid
982 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
989 $allowed = SURFBAR_GET_ALLOWED_VIEWS();
991 // Do we have a limit?
993 // Then count views_max down!
994 $ADD .= ",views_max=views_max-1";
998 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
999 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1001 // Update the stats entry
1002 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1003 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1005 // Was that update okay?
1006 if (SQL_AFFECTEDROWS() < 1) {
1007 // No, then insert entry
1008 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES (%s,%s,1)",
1009 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1012 // Update total/daily/weekly/monthly counter
1013 $_CONFIG['surfbar_total_counter']++;
1014 $_CONFIG['surfbar_daily_counter']++;
1015 $_CONFIG['surfbar_weekly_counter']++;
1016 $_CONFIG['surfbar_monthly_counter']++;
1018 // Update config as well
1019 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1021 // Update the salt for validation and statistics
1022 function SURFBAR_UPDATE_SALT_STATS () {
1023 // Update statistics record
1024 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1026 // Simply store the salt from cache away in database...
1027 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1028 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1031 //DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1034 if (SQL_AFFECTEDROWS() < 1) {
1035 // Insert missing entry!
1036 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1037 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1041 //DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1043 // Return if the update was okay
1044 return (SQL_AFFECTEDROWS() == 1);
1046 // Check if the reload lock is active for given id
1047 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1048 //DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1050 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1051 FROM "._MYSQL_PREFIX."_surfbar_locks
1052 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
1053 ORDER BY last_surfed ASC
1055 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1059 list($cnt) = SQL_FETCHROW($result);
1062 SQL_FREERESULT($result);
1065 //DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."", false);
1068 // Determine which user hash no more points left
1069 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1073 'points' => array(),
1074 'notified' => array(),
1077 // Do we have a current user id?
1078 if ((IS_MEMBER()) && ($limit == 0)) {
1079 // Then add this as well
1080 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1081 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1082 $UIDs['notified'][$GLOBALS['userid']] = 0;
1084 // Get all userid except logged in one
1085 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1086 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1087 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1088 ON u.userid=d.userid
1089 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
1091 ORDER BY u.userid ASC",
1092 array($GLOBALS['userid']), __FILE__, __LINE__);
1095 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1096 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1097 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1098 ON u.userid=d.userid
1099 WHERE u.status='ACTIVE'
1101 ORDER BY u.userid ASC", __FILE__, __LINE__);
1105 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1107 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1108 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1110 // Shall we add this to ignore?
1111 if ($points <= $limit) {
1113 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1114 $UIDs['uid'][$uid] = $uid;
1115 $UIDs['points'][$uid] = $points;
1116 $UIDs['notified'][$uid] = $notified;
1121 SQL_FREERESULT($result);
1124 //DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1129 // Determine how many users are Online in surfbar
1130 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1133 // Count all users in surfbar modue and return the value
1134 $result = SQL_QUERY_ESC("SELECT id
1135 FROM "._MYSQL_PREFIX."_surfbar_stats
1136 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1138 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
1141 $cnt = SQL_NUMROWS($result);
1144 SQL_FREERESULT($result);
1149 // Determine waiting time for one URL
1150 function SURFBAR_DETERMINE_WAIT_TIME () {
1153 // Static time is default
1154 $time = $_CONFIG['surfbar_static_time'];
1156 // Which payment model do we have?
1157 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1158 // "Calculate" dynamic time
1159 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1165 // Changes the status of an URL from given to other
1166 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1169 // Make new status always lower-case
1170 $newStatus = strtolower($newStatus);
1172 // Get URL data for status comparison if missing
1173 if ((!is_array($data)) || (count($data) == 0)) {
1174 // Fetch missing URL data
1175 $data = SURFBAR_GET_URL_DATA($urlId);
1178 // Is the new status set?
1179 if ((!is_string($newStatus)) || (empty($newStatus))) {
1180 // Abort here, but fine!
1184 // Is the status like prevStatus is saying?
1185 if ($data[$urlId]['status'] != $prevStatus) {
1186 // No, then abort here
1191 // Update the status now
1192 // ---------- Comment out for debugging/developing member actions! ---------
1193 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1194 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1195 // ---------- Comment out for debugging/developing member actions! ---------
1198 if (SQL_AFFECTEDROWS() != 1) {
1199 // No, something went wrong
1203 // Prepare content for notification routines
1204 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1205 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1206 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
1207 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
1209 // Send admin notification
1210 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
1212 // Send user notification
1213 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
1218 // Calculate minimum value for dynamic payment model
1219 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1222 // Addon is zero by default
1226 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1229 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1232 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1235 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1238 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1240 // Get user's total URLs
1241 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1244 if ($totalUrls > 0) {
1245 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1247 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1253 // Calculate maximum value for dynamic payment model
1254 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1257 // Addon is zero by default
1264 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1267 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1270 $addon += abs($max * $percent * $totalUsers);
1273 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1276 $addon += abs($max * $percent * $totalUrls);
1281 // Calculate dynamic lock
1282 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1285 // Default lock is 30 seconds
1289 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1292 $addon = abs(log($onlineUsers / $addon + 1));
1297 // "Getter" for lock ids array
1298 function SURFBAR_GET_LOCK_IDS () {
1299 // Prepare some arrays
1304 // Get all id from locks within the timestamp
1305 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1307 "._MYSQL_PREFIX."_surfbar_locks
1311 id ASC", array($GLOBALS['userid']),
1312 __FILE__, __LINE__);
1315 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1317 //DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."", false);
1319 // Skip entries that are too old
1320 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1322 //DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1324 // Add only if missing or bigger
1325 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1327 //DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1335 //DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1337 // Ignore these old entries!
1345 SQL_FREERESULT($result);
1350 // "Getter" for maximum random number
1351 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1353 // Count max availabe entries
1354 $result = SQL_QUERY("SELECT sbu.id AS cnt
1355 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1356 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1357 ON sbu.id=sbs.url_id
1358 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1360 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0)) AND sbu.status='ACTIVE'".$ADD."
1361 GROUP BY sbu.id", __FILE__, __LINE__);
1364 //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1367 $maxRand = SQL_NUMROWS($result);
1370 SQL_FREERESULT($result);
1375 // Load all URLs of the current user and return it as an array
1376 function SURFBAR_GET_USER_URLS () {
1381 $result = SQL_QUERY_ESC("SELECT u.id, u.userid, u.url, u.views_total, u.views_max, u.views_allowed, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
1382 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1383 WHERE u.userid=%s AND u.status != 'DELETED'
1385 array($GLOBALS['userid']), __FILE__, __LINE__);
1387 // Are there entries?
1388 if (SQL_NUMROWS($result) > 0) {
1390 while ($row = SQL_FETCHARRAY($result)) {
1392 $URLs[$row['id']] = $row;
1397 SQL_FREERESULT($result);
1402 // "Getter" for member action array for given status
1403 function SURFBAR_GET_ACTION_ARRAY ($status) {
1405 $returnArray = array();
1407 // Get all assigned actions
1408 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1409 array($status), __FILE__, __LINE__);
1411 // Some entries there?
1412 if (SQL_NUMROWS($result) > 0) {
1414 while (list($action) = SQL_FETCHROW($result)) {
1415 $returnArray[] = $action;
1420 SQL_FREERESULT($result);
1423 return $returnArray;
1425 // Reload to configured stop page
1426 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1429 // Internal or external?
1430 if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1431 // Reload to internal page
1432 LOAD_URL("surfbar.php?frame=".$page);
1434 // Reload to external page
1435 LOAD_URL($_CONFIG['surfbar_pause_url']);
1439 // Determine next id for surfbar or get data for given id, always call this before you call other
1440 // getters below this function!!!
1441 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1442 global $SURFBAR_CACHE, $_CONFIG;
1444 // Default is no id and no random number
1450 // Get array with lock ids
1451 $USE = SURFBAR_GET_LOCK_IDS();
1453 // Shall we add some URL ids to ignore?
1455 if (count($USE) > 0) {
1457 $ADD = " AND sbu.id NOT IN (";
1458 foreach ($USE as $url_id => $lid) {
1460 $ADD .= $url_id.",";
1463 // Add closing bracket
1464 $ADD = substr($ADD, 0, -1) . ")";
1467 // Determine depleted user account
1468 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1470 // Get maximum randomness factor
1471 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1473 // If more than one URL can be called generate the random number!
1475 // Generate random number
1476 $randNum = mt_rand(0, ($maxRand - 1));
1479 // And query the database
1480 //DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."", false);
1481 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1482 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1483 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1484 ON sbu.id=sbs.url_id
1485 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1487 WHERE sbu.userid NOT IN (".implode(",", $UIDs['uid']).") AND sbu.status='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$ADD."
1489 ORDER BY l.last_surfed ASC, sbu.id ASC
1491 array($randNum), __FILE__, __LINE__
1494 // Get data from specified id number
1495 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1496 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1497 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1498 ON sbu.id=sbs.url_id
1499 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1501 WHERE sbu.userid != %s AND sbu.status='ACTIVE' AND sbu.id=%s AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))
1503 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1507 // Is there an id number?
1508 //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1509 if (SQL_NUMROWS($result) == 1) {
1511 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1512 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1513 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1515 // Determine waiting time
1516 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1518 // Is the last salt there?
1519 if (is_null($SURFBAR_CACHE['last_salt'])) {
1520 // Then repair it wit the static!
1521 //DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1522 $SURFBAR_CACHE['last_salt'] = "";
1525 // Fix missing last_surfed
1526 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1528 //DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1529 $SURFBAR_CACHE['last_surfed'] = 0;
1532 // Get base/fixed reward and costs
1533 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1534 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1535 //DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1537 // Only in dynamic model add the dynamic bonus!
1538 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1539 // Calculate dynamic reward/costs and add it
1540 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1541 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1542 //DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1546 $nextId = SURFBAR_GET_ID();
1550 SQL_FREERESULT($result);
1553 //DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1556 // -----------------------------------------------------------------------------
1557 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1558 // $SURFBAR_CACHE ARRAY!
1559 // -----------------------------------------------------------------------------
1560 // Private getter for data elements
1561 function SURFBAR_GET_DATA ($element) {
1562 global $SURFBAR_CACHE;
1563 //DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1568 // Is the entry there?
1569 if (isset($SURFBAR_CACHE[$element])) {
1571 $data = $SURFBAR_CACHE[$element];
1572 } else { // END - if
1574 print_r($SURFBAR_CACHE);
1575 debug_print_backtrace();
1580 //DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1583 // Getter for reward from cache
1584 function SURFBAR_GET_REWARD () {
1585 // Get data element and return its contents
1586 return SURFBAR_GET_DATA('reward');
1588 // Getter for costs from cache
1589 function SURFBAR_GET_COSTS () {
1590 // Get data element and return its contents
1591 return SURFBAR_GET_DATA('costs');
1593 // Getter for URL from cache
1594 function SURFBAR_GET_URL () {
1595 // Get data element and return its contents
1596 return SURFBAR_GET_DATA('url');
1598 // Getter for salt from cache
1599 function SURFBAR_GET_SALT () {
1600 // Get data element and return its contents
1601 return SURFBAR_GET_DATA('salt');
1603 // Getter for id from cache
1604 function SURFBAR_GET_ID () {
1605 // Get data element and return its contents
1606 return SURFBAR_GET_DATA('id');
1608 // Getter for userid from cache
1609 function SURFBAR_GET_USERID () {
1610 // Get data element and return its contents
1611 return SURFBAR_GET_DATA('userid');
1613 // Getter for user reload locks
1614 function SURFBAR_GET_USER_RELOAD_LOCK () {
1615 // Get data element and return its contents
1616 return SURFBAR_GET_DATA('user_locks');
1618 // Getter for reload time
1619 function SURFBAR_GET_RELOAD_TIME () {
1620 // Get data element and return its contents
1621 return SURFBAR_GET_DATA('time');
1623 // Getter for allowed views
1624 function SURFBAR_GET_ALLOWED_VIEWS () {
1625 // Get data element and return its contents
1626 return SURFBAR_GET_DATA('views_allowed');