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, $reload) {
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
62 } elseif ("".($reload + 0)."" != "".$reload."") {
63 // Invalid amount entered
67 // Register the new URL
68 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", array('limit' => $limit, 'reload' => $reload));
70 // Admin unlocked an email so we can migrate the URL
71 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
76 } elseif (!VALIDATE_URL($url)) {
79 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
80 // URL already found in surfbar!
82 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
87 // Register the new URL
88 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
90 // Admin function for unlocking URLs
91 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
92 // Is this an admin or invalid array?
94 // Not admin or invalid IDs array
96 } elseif (!is_array($IDs)) {
99 } elseif (count($IDs) == 0) {
104 // Set to true to make AND expression valid if first URL got unlocked
107 // Update the status for all ids
108 foreach ($IDs as $id => $dummy) {
109 // Test all ids through (ignores failed)
110 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
113 // Return total status
116 // Admin function for rejecting URLs
117 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
118 // Is this an admin or invalid array?
120 // Not admin or invalid IDs array
122 } elseif (!is_array($IDs)) {
125 } elseif (count($IDs) == 0) {
130 // Set to true to make AND expression valid if first URL got unlocked
133 // Update the status for all ids
134 foreach ($IDs as $id => $dummy) {
135 // Test all ids through (ignores failed)
136 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
139 // Return total status
143 // -----------------------------------------------------------------------------
145 // -----------------------------------------------------------------------------
147 // Member has added an URL
148 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
151 // Do some pre-checks
155 } elseif (!VALIDATE_URL($url)) {
158 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
159 // URL already found in surfbar!
161 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
164 } elseif ("".($limit + 0)."" != "".$limit."") {
165 // Invalid amount entered
169 // Register the new URL
170 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", array('limit' => $limit));
172 // Create list of actions depending on status for the user
173 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
174 // Load all actions in an array for given status
175 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
178 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
182 $width = round(100 / count($actionArray));
184 // "Walk" through all actions and create forms
185 foreach ($actionArray as $actionId=>$action) {
186 // Add form for this action
187 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
188 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
189 <input type=\"hidden\" name=\"id\" value=\"%s\" />
190 <input type=\"hidden\" name=\"action\" value=\"%s\" />
191 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
209 // Do the member form request
210 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
211 global $SURFBAR_CACHE;
213 // By default no action is performed
220 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
221 // Important form elements are missing!
223 } elseif (!isset($URLs[$formData['id']])) {
224 // ID not found in cache
226 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
227 // Action not allowed for current URL status
232 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
235 if ($action != $formData['action']) {
236 // Invalid data in action found
240 // Create the function name for selected action
241 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
243 // Is the function there?
244 if (function_exists($functionName)) {
246 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
248 // Extract URL data for call-back
249 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
251 // Action found so execute it
252 $performed = call_user_func_array($functionName, $urlData);
254 // Log invalid request
255 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
256 ADD_FATAL(sprintf("Invalid member action! action=%s,id=%s,function=%s", $formData['action'], $formData['id'], $functionName));
262 // Validate if the requested action can be performed on current URL status
263 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
264 global $SURFBAR_CACHE;
266 // Search for the requested action/status combination in database
267 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
268 array($action, $status), __FILE__, __LINE__);
270 // Is the entry there?
271 $isValid = (SQL_NUMROWS($result) == 1);
273 // Fetch the new status if found
276 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
280 SQL_FREERESULT($result);
286 // -----------------------------------------------------------------------------
288 // -----------------------------------------------------------------------------
290 // Retreat a booked URL
291 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
292 // Create the data array for next function call
294 $urlData['id'] => $urlData
297 // Simply change the status here
298 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
300 // Book an URL now (from migration)
301 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
302 // Create the data array for next function call
304 $urlData['id'] => $urlData
307 // Simply change the status here
308 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
310 // Show edit form or do the changes
311 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
312 // Is the "execute" flag there?
313 if (isset($urlData['edit']['execute'])) {
314 // Execute the changes
315 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
319 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
321 // Show delete form or do the changes
322 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
323 // Is the "execute" flag there?
324 if (isset($urlData['delete']['execute'])) {
325 // Execute the changes
326 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
330 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
332 // Pause active banner
333 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
334 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
336 // Unpause stopped banner
337 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
338 // Fix missing entry for template
339 $urlData['edit'] = $urlData['unpause'];
340 $urlData['edit']['url'] = $urlData['url'];
341 $urlData['edit']['limit'] = $urlData['views_max'];
343 // Return status change
344 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
346 // Resubmit locked URL
347 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
348 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
350 // Display selected "action form"
351 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
352 // Translate some data
353 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
354 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
355 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
356 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
357 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
359 // Is the lock reason empty?
360 if (empty($urlData['lock_reason'])) {
361 // Fix it to three dashes
362 $urlData['lock_reason'] = "---";
365 // Include fields only for action 'edit'
366 if ($action == "edit") {
367 // Default is not limited
368 $urlData['limited_yes'] = "";
369 $urlData['limited_no'] = " checked=\"checked\"";
370 $urlData['limited'] = "false";
372 // Is this URL limited?
373 if ($urlData['views_max'] > 0) {
374 // Then rewrite form data
375 $urlData['limited_yes'] = " checked=\"checked\"";
376 $urlData['limited_no'] = "";
377 $urlData['limited'] = "true";
381 // Load the form and display it
382 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
384 // All fine by default ... ;-)
387 // Execute choosen action
388 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
389 // By default nothing is executed
392 // Is limitation "no" and "limit" is > 0?
393 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
394 // Set it to unlimited
395 $urlData[$action]['limit'] = 0;
398 // Construct function name
399 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
401 // Is 'userid' set and not 'uid' ?
402 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
404 $urlData['uid'] = $urlData['userid'];
407 // Is that function there?
408 if (function_exists($functionName)) {
409 // Execute the function
410 if (call_user_func_array($functionName, array($urlData)) == true) {
411 // Update status as well
412 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
416 ADD_FATAL(sprintf(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName));
422 // "Execute edit" function: Update changed data
423 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
424 // Default is nothing done
427 // Translate URLs for testing
428 $url1 = COMPILE_CODE($urlData['url']);
429 $url2 = COMPILE_CODE($urlData['edit']['url']);
431 // Has the URL or limit changed?
433 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
435 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",
436 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
445 // "Execute delete" function: Does nothing...
446 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
447 // Nothing special to do (see above function for such "special actions" to perform)
451 // -----------------------------------------------------------------------------
452 // Self-maintenance functions
453 // -----------------------------------------------------------------------------
456 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
457 // Handle URLs which limit has depleted so we can stop them
458 SURFBAR_HANDLE_DEPLETED_VIEWS();
460 // Handle low-points amounts
461 SURFBAR_HANDLE_LOW_POINTS();
463 // Handle URLs which limit has depleted
464 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
466 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND status='ACTIVE'");
468 // Do we have some entries?
469 if (count($urlArray) > 0) {
471 foreach ($urlArray as $id => $urlData) {
475 // Rewrite array for next call
476 $urlData[$id] = $data;
479 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
483 // Alert users which have URLs booked and are low on points amount
484 function SURFBAR_HANDLE_LOW_POINTS () {
488 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
490 // "Walk" through all URLs
491 foreach ($UIDs['uid'] as $uid => $dummy) {
492 // Is the last notification far enougth away to notify again?
493 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
497 'low' => TRANSLATE_COMMA(getConfig('surfbar_warn_low_points')),
498 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
499 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
500 'interval' => CREATE_FANCY_TIME(getConfig('surfbar_low_interval'))
504 SURFBAR_NOTIFY_USER("low_points", $content);
506 // Update last notified
507 SQL_QUERY_ESC("UPDATE `"._MYSQL_PREFIX."_user_data` SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
508 array($uid), __FILE__, __LINE__);
513 // -----------------------------------------------------------------------------
515 // -----------------------------------------------------------------------------
517 // Looks up by an URL
518 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
519 // Now lookup that given URL by itself
520 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
523 return (count($urlArray) > 0);
525 // Load URL data by given search term and column
526 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
529 // By default nothing is found
530 $lastUrlData = array();
532 // Is the column an id number?
533 if (($column == "id") || ($column == "userid")) {
534 // Extra secure input
535 $searchTerm = bigintval($searchTerm);
538 // If the column is "id" there can be only one entry
540 if ($column == "id") {
544 // Look up the record
545 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed, fixed_reload
546 FROM "._MYSQL_PREFIX."_surfbar_urls
547 WHERE %s='%s'".$add."
550 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
552 // Is there at least one record?
553 if (SQL_NUMROWS($result) > 0) {
555 while ($dataRow = SQL_FETCHARRAY($result)) {
556 // Shall we group these results?
557 if ($group == "id") {
558 // Add the row by id as index
559 $lastUrlData[$dataRow['id']] = $dataRow;
562 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
568 SQL_FREERESULT($result);
573 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
574 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
577 // Make sure by the user registered URLs are always pending
578 if ($addMode == "reg") $status = "PENDING";
581 $content = merge_array($extraFields, array(
583 'frametester' => FRAMETESTER($url),
588 // Is limit/reload set?
589 if (!isset($config['limit'])) $content['limit'] = 0;
590 if (!isset($config['reload'])) $content['reload'] = 0;
592 // Insert the URL into database
593 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
596 if ($content['insert_id'] == 0) {
597 // INSERT did not insert any data!
601 // Translate status and limit
602 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
604 // If in reg-mode we notify admin
605 if (($addMode == "reg") || (getConfig('surfbar_notify_admin_unlock') == "Y")) {
606 // Notify admin even when he as unlocked an email
607 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
611 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
613 // Return the insert id
614 return $content['insert_id'];
616 // Inserts an url by given data array and return the insert id
617 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
619 $uid = bigintval($urlData['uid']);
622 if (empty($uid)) $uid = 0;
624 // Just run the insert query for now
625 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid,url,status,views_max,views_allowed,fixed_reload) VALUES (%s,'%s','%s',%s,%s,%s)",
633 ), __FILE__, __LINE__
637 return SQL_INSERTID();
639 // Notify admin(s) with a selected message and content
640 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
641 // Prepare template name
642 $templateName = sprintf("admin_surfbar_%s", $messageType);
644 // Set default subject if following eval() wents wrong
645 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
647 // Create constant name
648 $constantName = sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
649 strtoupper($messageType)
653 if (defined($constantName)) {
654 $subject = constant($constantName);
656 ADD_FATAL(ADMIN_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
659 // Translate some data if present
660 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
661 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
662 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
663 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
664 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
665 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
667 // Send the notification out
668 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
670 // Notify the user about the performed action
671 function SURFBAR_NOTIFY_USER ($messageType, $content) {
672 // Skip notification if userid is zero
673 if ($content['uid'] == 0) {
677 // Prepare template name
678 $templateName = sprintf("member_surfbar_%s", $messageType);
680 // Set default subject if following eval() wents wrong
681 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
683 // Create constant name
684 $constantName = sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
685 strtoupper($messageType)
689 if (defined($constantName)) {
690 $subject = constant($constantName);
692 ADD_FATAL(MEMBER_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
695 // Translate some data if present
696 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
697 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
698 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
699 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
700 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
701 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
704 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
707 return SEND_EMAIL($content['uid'], $subject, $mailText);
709 // Translates the limit
710 function SURFBAR_TRANSLATE_LIMIT ($limit) {
714 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
717 $return = TRANSLATE_COMMA($limit);
723 // Translate the URL status
724 function SURFBAR_TRANSLATE_STATUS ($status) {
725 // Create constant name
726 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
728 // Set default translated status
729 $statusTranslated = "!".$constantName."!";
731 // Is the constant there?
732 if (defined($constantName)) {
733 // Then get it's value
734 $statusTranslated = constant($constantName);
738 return $statusTranslated;
741 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
744 // Static values are default
745 $reward = getConfig('surfbar_static_reward');
747 // Do we have static or dynamic?
748 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
749 // "Calculate" dynamic reward
751 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
753 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
761 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
764 // Static costs is default
765 $costs = getConfig('surfbar_static_costs');
767 // Do we have static or dynamic?
768 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
769 // "Calculate" dynamic costs
771 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
773 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
780 // "Calculate" dynamic add
781 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
782 // Get min/max values
783 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
784 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
786 // "Calculate" dynamic part and return it
787 return mt_rand($min, $max);
789 // Determine right template name
790 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
791 // Default is the frameset
792 $templateName = "surfbar_frameset";
794 // Any frame set? ;-)
795 if (isset($_GET['frame'])) {
796 // Use the frame as a template name part... ;-)
797 $templateName = sprintf("surfbar_frame_%s",
798 SQL_ESCAPE($_GET['frame'])
803 return $templateName;
805 // Check if the "reload lock" of the current user is full, call this function
806 // before you call SURFBAR_CHECK_RELOAD_LOCK().
807 function SURFBAR_CHECK_RELOAD_FULL() {
808 global $SURFBAR_CACHE, $_CONFIG;
813 // Cache static reload lock
814 $SURFBAR_CACHE['surf_lock'] = getConfig('surfbar_static_lock');
815 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
817 // Do we have dynamic model?
818 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
819 // "Calculate" dynamic lock
820 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
824 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks AS l
825 INNER JOIN "._MYSQL_PREFIX."_surfbar_urls AS u
827 WHERE l.userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND (((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR u.fixed_reload = 0)
829 array($GLOBALS['userid']), __FILE__, __LINE__
833 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
836 if (is_null($SURFBAR_CACHE['user_locks'])) {
837 // Then fix it to zero!
838 $SURFBAR_CACHE['user_locks'] = 0;
842 SQL_FREERESULT($result);
845 $total = SURFBAR_GET_TOTAL_URLS();
847 // Do we have some URLs in lock? Admins can always surf on own URLs!
848 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
849 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
854 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
855 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
856 // Determine depleted user account
857 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
859 // Is the exlude userid set?
860 if ($excludeUserId > 0) {
862 $UIDs['uid'][$excludeUserId] = $excludeUserId;
865 // Get amount from database
866 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
867 FROM "._MYSQL_PREFIX."_surfbar_urls
868 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
869 array($status), __FILE__, __LINE__
873 list($cnt) = SQL_FETCHROW($result);
876 SQL_FREERESULT($result);
881 // Check wether the user is allowed to book more URLs
882 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
885 // Is this admin and userid is zero or does the user has some URLs left to book?
886 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < getConfig('surfbar_max_order')));
888 // Get total amount of URLs of given status for current user
889 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
892 // Is the user 0 and user is logged in?
893 if (($uid == 0) && (IS_MEMBER())) {
894 // Then use this userid
895 $uid = $GLOBALS['userid'];
896 } elseif ($uid == 0) {
898 return (getConfig('surfbar_max_order') + 1);
901 // Default is all URLs
904 // Is the status set?
905 if (is_array($status)) {
906 // Only URLs with these status
907 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
908 } elseif (!empty($status)) {
909 // Only URLs with this status
910 $ADD = sprintf(" AND status='%s'", $status);
911 } elseif (is_array($exclude)) {
912 // Exclude URLs with these status
913 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
914 } elseif (!empty($exclude)) {
915 // Exclude URLs with this status
916 $ADD = sprintf(" AND status != '%s'", $exclude);
919 // Get amount from database
920 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
921 FROM "._MYSQL_PREFIX."_surfbar_urls
922 WHERE userid=%s".$ADD."
924 array($uid, getConfig('surfbar_max_order')), __FILE__, __LINE__
928 list($cnt) = SQL_FETCHROW($result);
931 SQL_FREERESULT($result);
936 // Generate a validation code for the given id number
937 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
938 global $_CONFIG, $SURFBAR_CACHE;
940 // @TODO Invalid salt should be refused
941 $SURFBAR_CACHE['salt'] = "INVALID";
943 // Get code length from config
944 $length = getConfig('code_length');
947 if ($length == 0) $length = 10;
949 // Generate a code until the length matches
951 while (strlen($valCode) != $length) {
954 // Generate random hashed string
955 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
956 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
959 $SURFBAR_CACHE['salt'] = $salt;
960 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
963 // ... and now the validation code
964 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
965 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
968 // Hash it with md5() and salt it with the random string
969 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
971 // Finally encrypt it PGP-like and return it
972 $valHashedCode = generatePassString($hashedCode);
974 // Return hashed value
975 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
976 return $valHashedCode;
978 // Check validation code
979 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
980 global $SURFBAR_CACHE;
983 $urlId = bigintval($urlId);
985 // Now generate the code again
986 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
988 // Return result of checking hashes and salts
989 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
990 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
991 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
993 // Lockdown the userid/id combination (reload lock)
994 function SURFBAR_LOCKDOWN_ID ($urlId) {
995 //* DEBUG: */ print "LOCK!");
996 ///* DEBUG: */ return;
997 // Just add it to the database
998 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES (%s, %s)",
999 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
1001 // Remove the salt from database
1002 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
1003 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
1005 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1006 function SURFBAR_PAY_POINTS () {
1009 // Remove it from the URL owner
1010 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1011 if (SURFBAR_GET_USERID() > 0) {
1012 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1015 // Book it to the user
1016 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
1017 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
1019 // Updates the statistics of current URL/userid
1020 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1026 // Get allowed views
1027 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1029 // Do we have a limit?
1031 // Then count views_max down!
1032 $ADD .= ",views_max=views_max-1";
1036 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1037 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1039 // Update the stats entry
1040 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1041 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1043 // Was that update okay?
1044 if (SQL_AFFECTEDROWS() < 1) {
1045 // No, then insert entry
1046 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES (%s,%s,1)",
1047 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1050 // Update total/daily/weekly/monthly counter
1051 $_CONFIG['surfbar_total_counter']++;
1052 $_CONFIG['surfbar_daily_counter']++;
1053 $_CONFIG['surfbar_weekly_counter']++;
1054 $_CONFIG['surfbar_monthly_counter']++;
1056 // Update config as well
1057 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1059 // Update the salt for validation and statistics
1060 function SURFBAR_UPDATE_SALT_STATS () {
1061 // Update statistics record
1062 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1064 // Simply store the salt from cache away in database...
1065 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1066 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1069 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1072 if (SQL_AFFECTEDROWS() < 1) {
1073 // Insert missing entry!
1074 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1075 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1079 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1081 // Return if the update was okay
1082 return (SQL_AFFECTEDROWS() == 1);
1084 // Check if the reload lock is active for given id
1085 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1086 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1088 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1089 FROM "._MYSQL_PREFIX."_surfbar_locks
1090 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1091 ORDER BY last_surfed ASC
1093 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1097 list($cnt) = SQL_FETCHROW($result);
1100 SQL_FREERESULT($result);
1103 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1106 // Determine which user hash no more points left
1107 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1111 'points' => array(),
1112 'notified' => array(),
1115 // Do we have a current user id?
1116 if ((IS_MEMBER()) && ($limit == 0)) {
1117 // Then add this as well
1118 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1119 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1120 $UIDs['notified'][$GLOBALS['userid']] = 0;
1122 // Get all userid except logged in one
1123 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1124 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1125 INNER JOIN `"._MYSQL_PREFIX."_user_data` AS d
1126 ON u.userid=d.userid
1127 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
1129 ORDER BY u.userid ASC",
1130 array($GLOBALS['userid']), __FILE__, __LINE__);
1133 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1134 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1135 INNER JOIN `"._MYSQL_PREFIX."_user_data` AS d
1136 ON u.userid=d.userid
1137 WHERE u.status='ACTIVE'
1139 ORDER BY u.userid ASC", __FILE__, __LINE__);
1143 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1145 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1146 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1148 // Shall we add this to ignore?
1149 if ($points <= $limit) {
1151 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1152 $UIDs['uid'][$uid] = $uid;
1153 $UIDs['points'][$uid] = $points;
1154 $UIDs['notified'][$uid] = $notified;
1159 SQL_FREERESULT($result);
1162 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1167 // Determine how many users are Online in surfbar
1168 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1171 // Count all users in surfbar modue and return the value
1172 $result = SQL_QUERY_ESC("SELECT id
1173 FROM "._MYSQL_PREFIX."_surfbar_stats
1174 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1176 array(getConfig('online_timeout')), __FILE__, __LINE__);
1179 $cnt = SQL_NUMROWS($result);
1182 SQL_FREERESULT($result);
1187 // Determine waiting time for one URL
1188 function SURFBAR_DETERMINE_WAIT_TIME () {
1189 // Get fixed reload lock
1190 $fixed = SURFBAR_GET_FIXED_RELOAD();
1192 // Is the fixed reload time set?
1198 // Static time is default
1199 $time = getConfig('surfbar_static_time');
1201 // Which payment model do we have?
1202 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1203 // "Calculate" dynamic time
1204 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1210 // Changes the status of an URL from given to other
1211 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1214 // Make new status always lower-case
1215 $newStatus = strtolower($newStatus);
1217 // Get URL data for status comparison if missing
1218 if ((!is_array($data)) || (count($data) == 0)) {
1219 // Fetch missing URL data
1220 $data = SURFBAR_GET_URL_DATA($urlId);
1223 // Is the new status set?
1224 if ((!is_string($newStatus)) || (empty($newStatus))) {
1225 // Abort here, but fine!
1229 // Is the status like prevStatus is saying?
1230 if ($data[$urlId]['status'] != $prevStatus) {
1231 // No, then abort here
1236 // Update the status now
1237 // ---------- Comment out for debugging/developing member actions! ---------
1238 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1239 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1240 // ---------- Comment out for debugging/developing member actions! ---------
1243 //if (SQL_AFFECTEDROWS() != 1) {
1244 // // No, something went wrong
1248 // Prepare content for notification routines
1249 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1250 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1251 $data[$urlId]['reward'] = TRANSLATE_COMMA(getConfig('surfbar_static_reward'));
1252 $data[$urlId]['costs'] = TRANSLATE_COMMA(getConfig('surfbar_static_costs'));
1254 // Do some dirty fixing here:
1255 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1256 // Fix for template change
1257 $newStatus = "continued";
1260 // Send admin notification
1261 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1263 // Send user notification
1264 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1269 // Calculate minimum value for dynamic payment model
1270 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1273 // Addon is zero by default
1277 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1280 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1283 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1286 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1289 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1291 // Get user's total URLs
1292 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1295 if ($totalUrls > 0) {
1296 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1298 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1304 // Calculate maximum value for dynamic payment model
1305 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1308 // Addon is zero by default
1315 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1318 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1321 $addon += abs($max * $percent * $totalUsers);
1324 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1327 $addon += abs($max * $percent * $totalUrls);
1332 // Calculate dynamic lock
1333 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1336 // Default lock is 30 seconds
1340 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1343 $addon = abs(log($onlineUsers / $addon + 1));
1348 // "Getter" for lock ids array
1349 function SURFBAR_GET_LOCK_IDS () {
1350 // Prepare some arrays
1355 // Get all id from locks within the timestamp
1356 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1358 "._MYSQL_PREFIX."_surfbar_locks
1362 id ASC", array($GLOBALS['userid']),
1363 __FILE__, __LINE__);
1366 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1368 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_SURF_LOCK()."", false);
1370 // Skip entries that are too old
1371 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($url, $ignored))) {
1373 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1375 // Add only if missing or bigger
1376 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1378 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1386 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1388 // Ignore these old entries!
1396 SQL_FREERESULT($result);
1401 // "Getter" for maximum random number
1402 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1404 // Count max availabe entries
1405 $result = SQL_QUERY("SELECT sbu.id AS cnt
1406 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1407 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1408 ON sbu.id=sbs.url_id
1409 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1411 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."
1412 GROUP BY sbu.id", __FILE__, __LINE__);
1415 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1418 $maxRand = SQL_NUMROWS($result);
1421 SQL_FREERESULT($result);
1426 // Load all URLs of the current user and return it as an array
1427 function SURFBAR_GET_USER_URLS () {
1432 $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
1433 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1434 WHERE u.userid=%s AND u.status != 'DELETED'
1436 array($GLOBALS['userid']), __FILE__, __LINE__);
1438 // Are there entries?
1439 if (SQL_NUMROWS($result) > 0) {
1441 while ($row = SQL_FETCHARRAY($result)) {
1443 $URLs[$row['id']] = $row;
1448 SQL_FREERESULT($result);
1453 // "Getter" for member action array for given status
1454 function SURFBAR_GET_ACTION_ARRAY ($status) {
1456 $returnArray = array();
1458 // Get all assigned actions
1459 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1460 array($status), __FILE__, __LINE__);
1462 // Some entries there?
1463 if (SQL_NUMROWS($result) > 0) {
1465 while (list($action) = SQL_FETCHROW($result)) {
1466 $returnArray[] = $action;
1471 SQL_FREERESULT($result);
1474 return $returnArray;
1476 // Reload to configured stop page
1477 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1478 // Internal or external?
1479 if ((getConfig('surfbar_pause_mode') == "INTERNAL") || (getConfig('surfbar_pause_url') == "")) {
1480 // Reload to internal page
1481 LOAD_URL("surfbar.php?frame=".$page);
1483 // Reload to external page
1484 LOAD_URL(getConfig('surfbar_pause_url'));
1488 // Determine next id for surfbar or get data for given id, always call this before you call other
1489 // getters below this function!!!
1490 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1491 global $SURFBAR_CACHE, $_CONFIG;
1493 // Default is no id and no random number
1499 // Get array with lock ids
1500 $USE = SURFBAR_GET_LOCK_IDS();
1502 // Shall we add some URL ids to ignore?
1504 if (count($USE) > 0) {
1506 $ADD = " AND sbu.id NOT IN (";
1507 foreach ($USE as $url_id => $lid) {
1509 $ADD .= $url_id.",";
1512 // Add closing bracket
1513 $ADD = substr($ADD, 0, -1) . ")";
1516 // Determine depleted user account
1517 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1519 // Get maximum randomness factor
1520 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1522 // If more than one URL can be called generate the random number!
1524 // Generate random number
1525 $randNum = mt_rand(0, ($maxRand - 1));
1528 // And query the database
1529 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1530 $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, sbu.fixed_reload
1531 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1532 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1533 ON sbu.id=sbs.url_id
1534 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1536 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."
1538 ORDER BY l.last_surfed ASC, sbu.id ASC
1540 array($randNum), __FILE__, __LINE__
1543 // Get data from specified id number
1544 $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, sbu.fixed_reload
1545 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1546 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1547 ON sbu.id=sbs.url_id
1548 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1550 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))
1552 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1556 // Is there an id number?
1557 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1558 if (SQL_NUMROWS($result) == 1) {
1560 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1561 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1562 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1564 // Determine waiting time
1565 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1567 // Is the last salt there?
1568 if (is_null($SURFBAR_CACHE['last_salt'])) {
1569 // Then repair it wit the static!
1570 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1571 $SURFBAR_CACHE['last_salt'] = "";
1574 // Fix missing last_surfed
1575 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1577 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1578 $SURFBAR_CACHE['last_surfed'] = 0;
1581 // Get base/fixed reward and costs
1582 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1583 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1584 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1586 // Only in dynamic model add the dynamic bonus!
1587 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1588 // Calculate dynamic reward/costs and add it
1589 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1590 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1591 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1595 $nextId = SURFBAR_GET_ID();
1599 SQL_FREERESULT($result);
1602 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1605 // -----------------------------------------------------------------------------
1606 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1607 // $SURFBAR_CACHE ARRAY!
1608 // -----------------------------------------------------------------------------
1609 // Private getter for data elements
1610 function SURFBAR_GET_DATA ($element) {
1611 global $SURFBAR_CACHE;
1612 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1617 // Is the entry there?
1618 if (isset($SURFBAR_CACHE[$element])) {
1620 $data = $SURFBAR_CACHE[$element];
1621 } else { // END - if
1623 print_r($SURFBAR_CACHE);
1624 debug_print_backtrace();
1629 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1632 // Getter for reward from cache
1633 function SURFBAR_GET_REWARD () {
1634 // Get data element and return its contents
1635 return SURFBAR_GET_DATA('reward');
1637 // Getter for costs from cache
1638 function SURFBAR_GET_COSTS () {
1639 // Get data element and return its contents
1640 return SURFBAR_GET_DATA('costs');
1642 // Getter for URL from cache
1643 function SURFBAR_GET_URL () {
1644 // Get data element and return its contents
1645 return SURFBAR_GET_DATA('url');
1647 // Getter for salt from cache
1648 function SURFBAR_GET_SALT () {
1649 // Get data element and return its contents
1650 return SURFBAR_GET_DATA('salt');
1652 // Getter for id from cache
1653 function SURFBAR_GET_ID () {
1654 // Get data element and return its contents
1655 return SURFBAR_GET_DATA('id');
1657 // Getter for userid from cache
1658 function SURFBAR_GET_USERID () {
1659 // Get data element and return its contents
1660 return SURFBAR_GET_DATA('userid');
1662 // Getter for user reload locks
1663 function SURFBAR_GET_USER_LOCKS () {
1664 // Get data element and return its contents
1665 return SURFBAR_GET_DATA('user_locks');
1667 // Getter for reload time
1668 function SURFBAR_GET_RELOAD_TIME () {
1669 // Get data element and return its contents
1670 return SURFBAR_GET_DATA('time');
1672 // Getter for allowed views
1673 function SURFBAR_GET_VIEWS_ALLOWED () {
1674 // Get data element and return its contents
1675 return SURFBAR_GET_DATA('views_allowed');
1677 // Getter for fixed reload
1678 function SURFBAR_GET_FIXED_RELOAD () {
1679 // Get data element and return its contents
1680 return SURFBAR_GET_DATA('fixed_reload');
1682 // Getter for surf lock
1683 function SURFBAR_GET_SURF_LOCK () {
1684 // Get data element and return its contents
1685 return SURFBAR_GET_DATA('surf_lock');