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(LOAD_TEMPLATE("member_surfbar_list_form", true),
203 // Do the member form request
204 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
205 global $SURFBAR_CACHE;
207 // By default no action is performed
214 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
215 // Important form elements are missing!
217 } elseif (!isset($URLs[$formData['id']])) {
218 // ID not found in cache
220 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
221 // Action not allowed for current URL status
226 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
229 if ($action != $formData['action']) {
230 // Invalid data in action found
234 // Create the function name for selected action
235 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
237 // Is the function there?
238 if (function_exists($functionName)) {
240 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
242 // Extract URL data for call-back
243 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
245 // Action found so execute it
246 $performed = call_user_func_array($functionName, $urlData);
248 // Log invalid request
249 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
250 addFatalMessage("Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
256 // Validate if the requested action can be performed on current URL status
257 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
258 global $SURFBAR_CACHE;
260 // Search for the requested action/status combination in database
261 $result = SQL_QUERY_ESC("SELECT new_status FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
262 array($action, $status), __FILE__, __LINE__);
264 // Is the entry there?
265 $isValid = (SQL_NUMROWS($result) == 1);
267 // Fetch the new status if found
270 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
274 SQL_FREERESULT($result);
280 // -----------------------------------------------------------------------------
282 // -----------------------------------------------------------------------------
284 // Retreat a booked URL
285 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
286 // Create the data array for next function call
288 $urlData['id'] => $urlData
291 // Simply change the status here
292 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
294 // Book an URL now (from migration)
295 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
296 // Create the data array for next function call
298 $urlData['id'] => $urlData
301 // Simply change the status here
302 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
304 // Show edit form or do the changes
305 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
306 // Is the "execute" flag there?
307 if (isset($urlData['edit']['execute'])) {
308 // Execute the changes
309 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
313 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
315 // Show delete form or do the changes
316 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
317 // Is the "execute" flag there?
318 if (isset($urlData['delete']['execute'])) {
319 // Execute the changes
320 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
324 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
326 // Pause active banner
327 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
328 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
330 // Unpause stopped banner
331 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
332 // Fix missing entry for template
333 $urlData['edit'] = $urlData['unpause'];
334 $urlData['edit']['url'] = $urlData['url'];
335 $urlData['edit']['limit'] = $urlData['views_max'];
337 // Return status change
338 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
340 // Resubmit locked URL
341 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
342 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
344 // Display selected "action form"
345 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
346 // Translate some data
347 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
348 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
349 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
350 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
351 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
353 // Is the lock reason empty?
354 if (empty($urlData['lock_reason'])) {
355 // Fix it to three dashes
356 $urlData['lock_reason'] = "---";
359 // Include fields only for action 'edit'
360 if ($action == "edit") {
361 // Default is not limited
362 $urlData['limited_yes'] = "";
363 $urlData['limited_no'] = " checked=\"checked\"";
364 $urlData['limited'] = "false";
366 // Is this URL limited?
367 if ($urlData['views_max'] > 0) {
368 // Then rewrite form data
369 $urlData['limited_yes'] = " checked=\"checked\"";
370 $urlData['limited_no'] = "";
371 $urlData['limited'] = "true";
375 // Load the form and display it
376 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
378 // All fine by default ... ;-)
381 // Execute choosen action
382 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
383 // By default nothing is executed
386 // Is limitation "no" and "limit" is > 0?
387 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
388 // Set it to unlimited
389 $urlData[$action]['limit'] = 0;
392 // Construct function name
393 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
395 // Is 'userid' set and not 'uid' ?
396 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
398 $urlData['uid'] = $urlData['userid'];
401 // Is that function there?
402 if (function_exists($functionName)) {
403 // Execute the function
404 if (call_user_func_array($functionName, array($urlData)) == true) {
405 // Update status as well
406 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
410 addFatalMessage(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName);
416 // "Execute edit" function: Update changed data
417 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
418 // Default is nothing done
421 // Translate URLs for testing
422 $url1 = COMPILE_CODE($urlData['url']);
423 $url2 = COMPILE_CODE($urlData['edit']['url']);
425 // Has the URL or limit changed?
427 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
429 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",
430 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
439 // "Execute delete" function: Does nothing...
440 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
441 // Nothing special to do (see above function for such "special actions" to perform)
445 // -----------------------------------------------------------------------------
446 // Self-maintenance functions
447 // -----------------------------------------------------------------------------
450 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
451 // Handle URLs which limit has depleted so we can stop them
452 SURFBAR_HANDLE_DEPLETED_VIEWS();
454 // Handle low-points amounts
455 SURFBAR_HANDLE_LOW_POINTS();
457 // Handle URLs which limit has depleted
458 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
460 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND `status`='ACTIVE'");
462 // Do we have some entries?
463 if (count($urlArray) > 0) {
465 foreach ($urlArray as $id => $urlData) {
469 // Rewrite array for next call
470 $urlData[$id] = $data;
473 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
477 // Alert users which have URLs booked and are low on points amount
478 function SURFBAR_HANDLE_LOW_POINTS () {
482 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
484 // "Walk" through all URLs
485 foreach ($UIDs['uid'] as $uid => $dummy) {
486 // Is the last notification far enougth away to notify again?
487 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
491 'low' => TRANSLATE_COMMA(getConfig('surfbar_warn_low_points')),
492 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
493 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
494 'interval' => CREATE_FANCY_TIME(getConfig('surfbar_low_interval'))
498 SURFBAR_NOTIFY_USER("low_points", $content);
500 // Update last notified
501 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
502 array($uid), __FILE__, __LINE__);
507 // -----------------------------------------------------------------------------
509 // -----------------------------------------------------------------------------
511 // Looks up by an URL
512 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
513 // Now lookup that given URL by itself
514 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
517 return (count($urlArray) > 0);
519 // Load URL data by given search term and column
520 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
523 // By default nothing is found
524 $lastUrlData = array();
526 // Is the column an id number?
527 if (($column == "id") || ($column == "userid")) {
528 // Extra secure input
529 $searchTerm = bigintval($searchTerm);
532 // If the column is "id" there can be only one entry
534 if ($column == "id") {
538 // Look up the record
539 $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
540 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
541 WHERE %s='%s'".$add."
544 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
546 // Is there at least one record?
547 if (SQL_NUMROWS($result) > 0) {
549 while ($dataRow = SQL_FETCHARRAY($result)) {
550 // Shall we group these results?
551 if ($group == "id") {
552 // Add the row by id as index
553 $lastUrlData[$dataRow['id']] = $dataRow;
556 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
562 SQL_FREERESULT($result);
567 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
568 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
571 // Make sure by the user registered URLs are always pending
572 if ($addMode == "reg") $status = "PENDING";
575 $content = merge_array($extraFields, array(
577 'frametester' => FRAMETESTER($url),
582 // Is limit/reload set?
583 if (!isset($config['limit'])) $content['limit'] = 0;
584 if (!isset($config['reload'])) $content['reload'] = 0;
586 // Insert the URL into database
587 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
590 if ($content['insert_id'] == 0) {
591 // INSERT did not insert any data!
595 // Translate status and limit
596 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
598 // If in reg-mode we notify admin
599 if (($addMode == "reg") || (getConfig('surfbar_notify_admin_unlock') == "Y")) {
600 // Notify admin even when he as unlocked an email
601 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
605 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
607 // Return the insert id
608 return $content['insert_id'];
610 // Inserts an url by given data array and return the insert id
611 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
613 $uid = bigintval($urlData['uid']);
616 if (empty($uid)) $uid = 0;
618 // Just run the insert query for now
619 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)",
627 ), __FILE__, __LINE__
631 return SQL_INSERTID();
633 // Notify admin(s) with a selected message and content
634 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
635 // Prepare template name
636 $templateName = sprintf("admin_surfbar_%s", $messageType);
638 // Set default subject if following eval() wents wrong
639 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
641 // Create constant name
642 $constantName = sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
643 strtoupper($messageType)
647 if (defined($constantName)) {
648 $subject = constant($constantName);
650 addFatalMessage(getMessage('ADMIN_SURFBAR_NOTIFY_SUBJECT_404'), $constantName);
653 // Translate some data if present
654 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
655 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
656 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
657 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
658 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
659 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
661 // Send the notification out
662 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
664 // Notify the user about the performed action
665 function SURFBAR_NOTIFY_USER ($messageType, $content) {
666 // Skip notification if userid is zero
667 if ($content['uid'] == 0) {
671 // Prepare template name
672 $templateName = sprintf("member_surfbar_%s", $messageType);
674 // Set default subject if following eval() wents wrong
675 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
677 // Create constant name
678 $constantName = sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
679 strtoupper($messageType)
683 if (defined($constantName)) {
684 $subject = constant($constantName);
686 addFatalMessage(getMessage('MEMBER_SURFBAR_NOTIFY_SUBJECT_404'), $constantName);
689 // Translate some data if present
690 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
691 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
692 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
693 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
694 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
695 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
698 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
701 return SEND_EMAIL($content['uid'], $subject, $mailText);
703 // Translates the limit
704 function SURFBAR_TRANSLATE_LIMIT ($limit) {
708 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
711 $return = TRANSLATE_COMMA($limit);
717 // Translate the URL status
718 function SURFBAR_TRANSLATE_STATUS ($status) {
719 // Create constant name
720 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
722 // Set default translated status
723 $statusTranslated = "!".$constantName."!";
725 // Is the constant there?
726 if (defined($constantName)) {
727 // Then get it's value
728 $statusTranslated = constant($constantName);
732 return $statusTranslated;
735 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
738 // Static values are default
739 $reward = getConfig('surfbar_static_reward');
741 // Do we have static or dynamic?
742 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
743 // "Calculate" dynamic reward
745 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
747 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
755 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
758 // Static costs is default
759 $costs = getConfig('surfbar_static_costs');
761 // Do we have static or dynamic?
762 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
763 // "Calculate" dynamic costs
765 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
767 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
774 // "Calculate" dynamic add
775 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
776 // Get min/max values
777 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
778 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
780 // "Calculate" dynamic part and return it
781 return mt_rand($min, $max);
783 // Determine right template name
784 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
785 // Default is the frameset
786 $templateName = "surfbar_frameset";
788 // Any frame set? ;-)
789 if (isset($_GET['frame'])) {
790 // Use the frame as a template name part... ;-)
791 $templateName = sprintf("surfbar_frame_%s",
792 SQL_ESCAPE($_GET['frame'])
797 return $templateName;
799 // Check if the "reload lock" of the current user is full, call this function
800 // before you call SURFBAR_CHECK_RELOAD_LOCK().
801 function SURFBAR_CHECK_RELOAD_FULL() {
802 global $SURFBAR_CACHE, $_CONFIG;
807 // Cache static reload lock
808 $SURFBAR_CACHE['surf_lock'] = getConfig('surfbar_static_lock');
809 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
811 // Do we have dynamic model?
812 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
813 // "Calculate" dynamic lock
814 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
818 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
819 INNER JOIN `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
821 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)
823 array($GLOBALS['userid']), __FILE__, __LINE__
827 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
830 if (is_null($SURFBAR_CACHE['user_locks'])) {
831 // Then fix it to zero!
832 $SURFBAR_CACHE['user_locks'] = 0;
836 SQL_FREERESULT($result);
839 $total = SURFBAR_GET_TOTAL_URLS();
841 // Do we have some URLs in lock? Admins can always surf on own URLs!
842 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
843 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
848 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
849 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
850 // Determine depleted user account
851 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
853 // Is the exlude userid set?
854 if ($excludeUserId > 0) {
856 $UIDs['uid'][$excludeUserId] = $excludeUserId;
859 // Get amount from database
860 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
861 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
862 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND `status`='%s'",
863 array($status), __FILE__, __LINE__
867 list($cnt) = SQL_FETCHROW($result);
870 SQL_FREERESULT($result);
875 // Check wether the user is allowed to book more URLs
876 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
879 // Is this admin and userid is zero or does the user has some URLs left to book?
880 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < getConfig('surfbar_max_order')));
882 // Get total amount of URLs of given status for current user
883 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
886 // Is the user 0 and user is logged in?
887 if (($uid == 0) && (IS_MEMBER())) {
888 // Then use this userid
889 $uid = $GLOBALS['userid'];
890 } elseif ($uid == 0) {
892 return (getConfig('surfbar_max_order') + 1);
895 // Default is all URLs
898 // Is the status set?
899 if (is_array($status)) {
900 // Only URLs with these status
901 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
902 } elseif (!empty($status)) {
903 // Only URLs with this status
904 $ADD = sprintf(" AND `status`='%s'", $status);
905 } elseif (is_array($exclude)) {
906 // Exclude URLs with these status
907 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
908 } elseif (!empty($exclude)) {
909 // Exclude URLs with this status
910 $ADD = sprintf(" AND status != '%s'", $exclude);
913 // Get amount from database
914 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
915 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
916 WHERE userid=%s".$ADD."
918 array($uid, getConfig('surfbar_max_order')), __FILE__, __LINE__
922 list($cnt) = SQL_FETCHROW($result);
925 SQL_FREERESULT($result);
930 // Generate a validation code for the given id number
931 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
932 global $_CONFIG, $SURFBAR_CACHE;
934 // @TODO Invalid salt should be refused
935 $SURFBAR_CACHE['salt'] = "INVALID";
937 // Get code length from config
938 $length = getConfig('code_length');
941 if ($length == 0) $length = 10;
943 // Generate a code until the length matches
945 while (strlen($valCode) != $length) {
948 // Generate random hashed string
949 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
950 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
953 $SURFBAR_CACHE['salt'] = $salt;
954 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
957 // ... and now the validation code
958 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
959 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
962 // Hash it with md5() and salt it with the random string
963 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
965 // Finally encrypt it PGP-like and return it
966 $valHashedCode = generatePassString($hashedCode);
968 // Return hashed value
969 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
970 return $valHashedCode;
972 // Check validation code
973 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
974 global $SURFBAR_CACHE;
977 $urlId = bigintval($urlId);
979 // Now generate the code again
980 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
982 // Return result of checking hashes and salts
983 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
984 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
985 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
987 // Lockdown the userid/id combination (reload lock)
988 function SURFBAR_LOCKDOWN_ID ($urlId) {
989 //* DEBUG: */ print "LOCK!");
990 ///* DEBUG: */ return;
991 // Just add it to the database
992 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (userid, url_id) VALUES (%s, %s)",
993 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
995 // Remove the salt from database
996 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE url_id=%s AND userid=%s LIMIT 1",
997 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
999 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1000 function SURFBAR_PAY_POINTS () {
1003 // Remove it from the URL owner
1004 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1005 if (SURFBAR_GET_USERID() > 0) {
1006 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1009 // Book it to the user
1010 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
1011 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
1013 // Updates the statistics of current URL/userid
1014 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1020 // Get allowed views
1021 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1023 // Do we have a limit?
1025 // Then count views_max down!
1026 $ADD .= ",views_max=views_max-1";
1030 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1031 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1033 // Update the stats entry
1034 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1035 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1037 // Was that update okay?
1038 if (SQL_AFFECTEDROWS() < 1) {
1039 // No, then insert entry
1040 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1041 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1044 // Update total/daily/weekly/monthly counter
1045 incrementConfigEntry('surfbar_total_counter');
1046 incrementConfigEntry('surfbar_daily_counter');
1047 incrementConfigEntry('surfbar_weekly_counter');
1048 incrementConfigEntry('surfbar_monthly_counter');
1050 // Update config as well
1051 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1053 // Update the salt for validation and statistics
1054 function SURFBAR_UPDATE_SALT_STATS () {
1055 // Update statistics record
1056 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1058 // Simply store the salt from cache away in database...
1059 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1060 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1063 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1066 if (SQL_AFFECTEDROWS() < 1) {
1067 // Insert missing entry!
1068 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1069 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1073 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1075 // Return if the update was okay
1076 return (SQL_AFFECTEDROWS() == 1);
1078 // Check if the reload lock is active for given id
1079 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1080 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1082 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1083 FROM `{!_MYSQL_PREFIX!}_surfbar_locks`
1084 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1085 ORDER BY last_surfed ASC
1087 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1091 list($cnt) = SQL_FETCHROW($result);
1094 SQL_FREERESULT($result);
1097 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1100 // Determine which user hash no more points left
1101 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1105 'points' => array(),
1106 'notified' => array(),
1109 // Do we have a current user id?
1110 if ((IS_MEMBER()) && ($limit == 0)) {
1111 // Then add this as well
1112 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1113 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1114 $UIDs['notified'][$GLOBALS['userid']] = 0;
1116 // Get all userid except logged in one
1117 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1118 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1119 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1120 ON u.userid=d.userid
1121 WHERE u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1123 ORDER BY u.userid ASC",
1124 array($GLOBALS['userid']), __FILE__, __LINE__);
1127 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1128 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1129 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1130 ON u.userid=d.userid
1131 WHERE u.`status`='ACTIVE'
1133 ORDER BY u.userid ASC", __FILE__, __LINE__);
1137 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1139 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1140 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1142 // Shall we add this to ignore?
1143 if ($points <= $limit) {
1145 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1146 $UIDs['uid'][$uid] = $uid;
1147 $UIDs['points'][$uid] = $points;
1148 $UIDs['notified'][$uid] = $notified;
1153 SQL_FREERESULT($result);
1156 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1161 // Determine how many users are Online in surfbar
1162 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1165 // Count all users in surfbar modue and return the value
1166 $result = SQL_QUERY_ESC("SELECT id
1167 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1168 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1170 array(getConfig('online_timeout')), __FILE__, __LINE__);
1173 $cnt = SQL_NUMROWS($result);
1176 SQL_FREERESULT($result);
1181 // Determine waiting time for one URL
1182 function SURFBAR_DETERMINE_WAIT_TIME () {
1183 // Get fixed reload lock
1184 $fixed = SURFBAR_GET_FIXED_RELOAD();
1186 // Is the fixed reload time set?
1192 // Static time is default
1193 $time = getConfig('surfbar_static_time');
1195 // Which payment model do we have?
1196 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1197 // "Calculate" dynamic time
1198 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1204 // Changes the status of an URL from given to other
1205 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1208 // Make new status always lower-case
1209 $newStatus = strtolower($newStatus);
1211 // Get URL data for status comparison if missing
1212 if ((!is_array($data)) || (count($data) == 0)) {
1213 // Fetch missing URL data
1214 $data = SURFBAR_GET_URL_DATA($urlId);
1217 // Is the new status set?
1218 if ((!is_string($newStatus)) || (empty($newStatus))) {
1219 // Abort here, but fine!
1223 // Is the status like prevStatus is saying?
1224 if ($data[$urlId]['status'] != $prevStatus) {
1225 // No, then abort here
1230 // Update the status now
1231 // ---------- Comment out for debugging/developing member actions! ---------
1232 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE id=%s LIMIT 1",
1233 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1234 // ---------- Comment out for debugging/developing member actions! ---------
1237 //if (SQL_AFFECTEDROWS() != 1) {
1238 // // No, something went wrong
1242 // Prepare content for notification routines
1243 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1244 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1245 $data[$urlId]['reward'] = TRANSLATE_COMMA(getConfig('surfbar_static_reward'));
1246 $data[$urlId]['costs'] = TRANSLATE_COMMA(getConfig('surfbar_static_costs'));
1248 // Do some dirty fixing here:
1249 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1250 // Fix for template change
1251 $newStatus = "continued";
1254 // Send admin notification
1255 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1257 // Send user notification
1258 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1263 // Calculate minimum value for dynamic payment model
1264 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1267 // Addon is zero by default
1271 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1274 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1277 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1280 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1283 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1285 // Get user's total URLs
1286 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1289 if ($totalUrls > 0) {
1290 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1292 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1298 // Calculate maximum value for dynamic payment model
1299 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1302 // Addon is zero by default
1309 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1312 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1315 $addon += abs($max * $percent * $totalUsers);
1318 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1321 $addon += abs($max * $percent * $totalUrls);
1326 // Calculate dynamic lock
1327 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1330 // Default lock is 30 seconds
1334 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1337 $addon = abs(log($onlineUsers / $addon + 1));
1342 // "Getter" for lock ids array
1343 function SURFBAR_GET_LOCK_IDS () {
1344 // Prepare some arrays
1349 // Get all id from locks within the timestamp
1350 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1352 {!_MYSQL_PREFIX!}_surfbar_locks
1356 id ASC", array($GLOBALS['userid']),
1357 __FILE__, __LINE__);
1360 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1362 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_SURF_LOCK()."", false);
1364 // Skip entries that are too old
1365 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($url, $ignored))) {
1367 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1369 // Add only if missing or bigger
1370 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1372 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1380 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1382 // Ignore these old entries!
1390 SQL_FREERESULT($result);
1395 // "Getter" for maximum random number
1396 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1398 // Count max availabe entries
1399 $result = SQL_QUERY("SELECT sbu.id AS cnt
1400 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1401 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1402 ON sbu.id=sbs.url_id
1403 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1405 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."
1406 GROUP BY sbu.id", __FILE__, __LINE__);
1409 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1412 $maxRand = SQL_NUMROWS($result);
1415 SQL_FREERESULT($result);
1420 // Load all URLs of the current user and return it as an array
1421 function SURFBAR_GET_USER_URLS () {
1426 $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
1427 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1428 WHERE u.userid=%s AND u.status != 'DELETED'
1430 array($GLOBALS['userid']), __FILE__, __LINE__);
1432 // Are there entries?
1433 if (SQL_NUMROWS($result) > 0) {
1435 while ($row = SQL_FETCHARRAY($result)) {
1437 $URLs[$row['id']] = $row;
1442 SQL_FREERESULT($result);
1447 // "Getter" for member action array for given status
1448 function SURFBAR_GET_ACTION_ARRAY ($status) {
1450 $returnArray = array();
1452 // Get all assigned actions
1453 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1454 array($status), __FILE__, __LINE__);
1456 // Some entries there?
1457 if (SQL_NUMROWS($result) > 0) {
1459 while (list($action) = SQL_FETCHROW($result)) {
1460 $returnArray[] = $action;
1465 SQL_FREERESULT($result);
1468 return $returnArray;
1470 // Reload to configured stop page
1471 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1472 // Internal or external?
1473 if ((getConfig('surfbar_pause_mode') == "INTERNAL") || (getConfig('surfbar_pause_url') == "")) {
1474 // Reload to internal page
1475 LOAD_URL("surfbar.php?frame=".$page);
1477 // Reload to external page
1478 LOAD_CONFIGURED_URL('surfbar_pause_url');
1482 // Determine next id for surfbar or get data for given id, always call this before you call other
1483 // getters below this function!!!
1484 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1485 global $SURFBAR_CACHE, $_CONFIG;
1487 // Default is no id and no random number
1493 // Get array with lock ids
1494 $USE = SURFBAR_GET_LOCK_IDS();
1496 // Shall we add some URL ids to ignore?
1498 if (count($USE) > 0) {
1500 $ADD = " AND sbu.id NOT IN (";
1501 foreach ($USE as $url_id => $lid) {
1503 $ADD .= $url_id.",";
1506 // Add closing bracket
1507 $ADD = substr($ADD, 0, -1) . ")";
1510 // Determine depleted user account
1511 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1513 // Get maximum randomness factor
1514 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1516 // If more than one URL can be called generate the random number!
1518 // Generate random number
1519 $randNum = mt_rand(0, ($maxRand - 1));
1522 // And query the database
1523 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1524 $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
1525 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1526 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1527 ON sbu.id=sbs.url_id
1528 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1530 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."
1532 ORDER BY l.last_surfed ASC, sbu.id ASC
1534 array($randNum), __FILE__, __LINE__
1537 // Get data from specified id number
1538 $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
1539 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1540 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1541 ON sbu.id=sbs.url_id
1542 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1544 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))
1546 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1550 // Is there an id number?
1551 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1552 if (SQL_NUMROWS($result) == 1) {
1554 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1555 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1556 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1558 // Determine waiting time
1559 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1561 // Is the last salt there?
1562 if (is_null($SURFBAR_CACHE['last_salt'])) {
1563 // Then repair it wit the static!
1564 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1565 $SURFBAR_CACHE['last_salt'] = "";
1568 // Fix missing last_surfed
1569 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1571 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1572 $SURFBAR_CACHE['last_surfed'] = 0;
1575 // Get base/fixed reward and costs
1576 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1577 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1578 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1580 // Only in dynamic model add the dynamic bonus!
1581 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1582 // Calculate dynamic reward/costs and add it
1583 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1584 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1585 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1589 $nextId = SURFBAR_GET_ID();
1593 SQL_FREERESULT($result);
1596 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1599 // -----------------------------------------------------------------------------
1600 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1601 // $SURFBAR_CACHE ARRAY!
1602 // -----------------------------------------------------------------------------
1603 // Private getter for data elements
1604 function SURFBAR_GET_DATA ($element) {
1605 global $SURFBAR_CACHE;
1606 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1611 // Is the entry there?
1612 if (isset($SURFBAR_CACHE[$element])) {
1614 $data = $SURFBAR_CACHE[$element];
1615 } else { // END - if
1617 print_r($SURFBAR_CACHE);
1623 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1626 // Getter for reward from cache
1627 function SURFBAR_GET_REWARD () {
1628 // Get data element and return its contents
1629 return SURFBAR_GET_DATA('reward');
1631 // Getter for costs from cache
1632 function SURFBAR_GET_COSTS () {
1633 // Get data element and return its contents
1634 return SURFBAR_GET_DATA('costs');
1636 // Getter for URL from cache
1637 function SURFBAR_GET_URL () {
1638 // Get data element and return its contents
1639 return SURFBAR_GET_DATA('url');
1641 // Getter for salt from cache
1642 function SURFBAR_GET_SALT () {
1643 // Get data element and return its contents
1644 return SURFBAR_GET_DATA('salt');
1646 // Getter for id from cache
1647 function SURFBAR_GET_ID () {
1648 // Get data element and return its contents
1649 return SURFBAR_GET_DATA('id');
1651 // Getter for userid from cache
1652 function SURFBAR_GET_USERID () {
1653 // Get data element and return its contents
1654 return SURFBAR_GET_DATA('userid');
1656 // Getter for user reload locks
1657 function SURFBAR_GET_USER_LOCKS () {
1658 // Get data element and return its contents
1659 return SURFBAR_GET_DATA('user_locks');
1661 // Getter for reload time
1662 function SURFBAR_GET_RELOAD_TIME () {
1663 // Get data element and return its contents
1664 return SURFBAR_GET_DATA('time');
1666 // Getter for allowed views
1667 function SURFBAR_GET_VIEWS_ALLOWED () {
1668 // Get data element and return its contents
1669 return SURFBAR_GET_DATA('views_allowed');
1671 // Getter for fixed reload
1672 function SURFBAR_GET_FIXED_RELOAD () {
1673 // Get data element and return its contents
1674 return SURFBAR_GET_DATA('fixed_reload');
1676 // Getter for surf lock
1677 function SURFBAR_GET_SURF_LOCK () {
1678 // Get data element and return its contents
1679 return SURFBAR_GET_DATA('surf_lock');