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) {
149 // Do some pre-checks
153 } elseif (!VALIDATE_URL($url)) {
156 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
157 // URL already found in surfbar!
159 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
162 } elseif ("".($limit + 0)."" != "".$limit."") {
163 // Invalid amount entered
167 // Register the new URL
168 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", array('limit' => $limit));
170 // Create list of actions depending on status for the user
171 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
172 // Load all actions in an array for given status
173 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
176 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
180 $width = round(100 / count($actionArray));
182 // "Walk" through all actions and create forms
183 foreach ($actionArray as $actionId=>$action) {
184 // Add form for this action
185 $OUT .= sprintf(LOAD_TEMPLATE("member_surfbar_list_form", true),
201 // Do the member form request
202 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
203 global $SURFBAR_CACHE;
205 // By default no action is performed
212 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
213 // Important form elements are missing!
215 } elseif (!isset($URLs[$formData['id']])) {
216 // ID not found in cache
218 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
219 // Action not allowed for current URL status
224 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
227 if ($action != $formData['action']) {
228 // Invalid data in action found
232 // Create the function name for selected action
233 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
235 // Is the function there?
236 if (function_exists($functionName)) {
238 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
240 // Extract URL data for call-back
241 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
243 // Action found so execute it
244 $performed = call_user_func_array($functionName, $urlData);
246 // Log invalid request
247 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
248 addFatalMessage("Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
254 // Validate if the requested action can be performed on current URL status
255 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
256 global $SURFBAR_CACHE;
258 // Search for the requested action/status combination in database
259 $result = SQL_QUERY_ESC("SELECT new_status FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
260 array($action, $status), __FILE__, __LINE__);
262 // Is the entry there?
263 $isValid = (SQL_NUMROWS($result) == 1);
265 // Fetch the new status if found
268 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
272 SQL_FREERESULT($result);
278 // -----------------------------------------------------------------------------
280 // -----------------------------------------------------------------------------
282 // Retreat a booked URL
283 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
284 // Create the data array for next function call
286 $urlData['id'] => $urlData
289 // Simply change the status here
290 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
292 // Book an URL now (from migration)
293 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
294 // Create the data array for next function call
296 $urlData['id'] => $urlData
299 // Simply change the status here
300 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
302 // Show edit form or do the changes
303 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
304 // Is the "execute" flag there?
305 if (isset($urlData['edit']['execute'])) {
306 // Execute the changes
307 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
311 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
313 // Show delete form or do the changes
314 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
315 // Is the "execute" flag there?
316 if (isset($urlData['delete']['execute'])) {
317 // Execute the changes
318 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
322 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
324 // Pause active banner
325 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
326 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
328 // Unpause stopped banner
329 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
330 // Fix missing entry for template
331 $urlData['edit'] = $urlData['unpause'];
332 $urlData['edit']['url'] = $urlData['url'];
333 $urlData['edit']['limit'] = $urlData['views_max'];
335 // Return status change
336 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
338 // Resubmit locked URL
339 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
340 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
342 // Display selected "action form"
343 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
344 // Translate some data
345 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
346 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
347 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
348 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
349 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
351 // Is the lock reason empty?
352 if (empty($urlData['lock_reason'])) {
353 // Fix it to three dashes
354 $urlData['lock_reason'] = "---";
357 // Include fields only for action 'edit'
358 if ($action == "edit") {
359 // Default is not limited
360 $urlData['limited_yes'] = "";
361 $urlData['limited_no'] = " checked=\"checked\"";
362 $urlData['limited'] = "false";
364 // Is this URL limited?
365 if ($urlData['views_max'] > 0) {
366 // Then rewrite form data
367 $urlData['limited_yes'] = " checked=\"checked\"";
368 $urlData['limited_no'] = "";
369 $urlData['limited'] = "true";
373 // Load the form and display it
374 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
376 // All fine by default ... ;-)
379 // Execute choosen action
380 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
381 // By default nothing is executed
384 // Is limitation "no" and "limit" is > 0?
385 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
386 // Set it to unlimited
387 $urlData[$action]['limit'] = 0;
390 // Construct function name
391 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
393 // Is 'userid' set and not 'uid' ?
394 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
396 $urlData['uid'] = $urlData['userid'];
399 // Is that function there?
400 if (function_exists($functionName)) {
401 // Execute the function
402 if (call_user_func_array($functionName, array($urlData)) == true) {
403 // Update status as well
404 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
408 addFatalMessage(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName);
414 // "Execute edit" function: Update changed data
415 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
416 // Default is nothing done
419 // Translate URLs for testing
420 $url1 = COMPILE_CODE($urlData['url']);
421 $url2 = COMPILE_CODE($urlData['edit']['url']);
423 // Has the URL or limit changed?
425 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
427 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",
428 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
437 // "Execute delete" function: Does nothing...
438 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
439 // Nothing special to do (see above function for such "special actions" to perform)
443 // -----------------------------------------------------------------------------
444 // Self-maintenance functions
445 // -----------------------------------------------------------------------------
448 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
449 // Handle URLs which limit has depleted so we can stop them
450 SURFBAR_HANDLE_DEPLETED_VIEWS();
452 // Handle low-points amounts
453 SURFBAR_HANDLE_LOW_POINTS();
455 // Handle URLs which limit has depleted
456 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
458 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND `status`='ACTIVE'");
460 // Do we have some entries?
461 if (count($urlArray) > 0) {
463 foreach ($urlArray as $id => $urlData) {
467 // Rewrite array for next call
468 $urlData[$id] = $data;
471 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
476 // Alert users which have URLs booked and are low on points amount
477 function SURFBAR_HANDLE_LOW_POINTS () {
479 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
481 // "Walk" through all URLs
482 foreach ($UIDs['uid'] as $uid => $dummy) {
483 // Is the last notification far enougth away to notify again?
484 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
488 'low' => TRANSLATE_COMMA(getConfig('surfbar_warn_low_points')),
489 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
490 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
491 'interval' => CREATE_FANCY_TIME(getConfig('surfbar_low_interval'))
495 SURFBAR_NOTIFY_USER("low_points", $content);
497 // Update last notified
498 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
499 array($uid), __FILE__, __LINE__);
505 // -----------------------------------------------------------------------------
507 // -----------------------------------------------------------------------------
510 // Looks up by an URL
511 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
512 // Now lookup that given URL by itself
513 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
516 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);
568 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
569 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
570 // Make sure by the user registered URLs are always pending
571 if ($addMode == "reg") $status = "PENDING";
574 $content = merge_array($extraFields, array(
576 'frametester' => FRAMETESTER($url),
581 // Is limit/reload set?
582 if (!isset($config['limit'])) $content['limit'] = 0;
583 if (!isset($config['reload'])) $content['reload'] = 0;
585 // Insert the URL into database
586 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
589 if ($content['insert_id'] == 0) {
590 // INSERT did not insert any data!
594 // Translate status and limit
595 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
597 // If in reg-mode we notify admin
598 if (($addMode == "reg") || (getConfig('surfbar_notify_admin_unlock') == "Y")) {
599 // Notify admin even when he as unlocked an email
600 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
604 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
606 // Return the insert id
607 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();
634 // Notify admin(s) with a selected message and content
635 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
636 // Prepare template name
637 $templateName = sprintf("admin_surfbar_%s", $messageType);
640 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
641 strtoupper($messageType)
644 // Is the subject line there?
645 if ((substr($subject, 0, 1) == "!") && (substr($subject, -1, 1) == "!")) {
646 // Set default subject if following eval() wents wrong
647 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
650 // Translate some data if present
651 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
652 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
653 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
654 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
655 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
656 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
658 // Send the notification out
659 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
662 // Notify the user about the performed action
663 function SURFBAR_NOTIFY_USER ($messageType, $content) {
664 // Skip notification if userid is zero
665 if ($content['uid'] == 0) {
669 // Prepare template name
670 $templateName = sprintf("member_surfbar_%s", $messageType);
673 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
674 strtoupper($messageType)
677 // Is the subject line there?
678 if ((substr($subject, 0, 1) == "!") && (substr($subject, -1, 1) == "!")) {
679 // Set default subject if following eval() wents wrong
680 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
683 // Translate some data if present
684 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
685 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
686 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
687 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
688 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
689 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
692 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
695 return SEND_EMAIL($content['uid'], $subject, $mailText);
697 // Translates the limit
698 function SURFBAR_TRANSLATE_LIMIT ($limit) {
702 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
705 $return = TRANSLATE_COMMA($limit);
711 // Translate the URL status
712 function SURFBAR_TRANSLATE_STATUS ($status) {
713 // Create constant name
714 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
716 // Set default translated status
717 $statusTranslated = "!".$constantName."!";
719 // Is the constant there?
720 if (defined($constantName)) {
721 // Then get it's value
722 $statusTranslated = constant($constantName);
726 return $statusTranslated;
729 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
730 // Static values are default
731 $reward = getConfig('surfbar_static_reward');
733 // Do we have static or dynamic?
734 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
735 // "Calculate" dynamic reward
737 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
739 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
747 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
748 // Static costs is default
749 $costs = getConfig('surfbar_static_costs');
751 // Do we have static or dynamic?
752 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
753 // "Calculate" dynamic costs
755 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
757 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
764 // "Calculate" dynamic add
765 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
766 // Get min/max values
767 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
768 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
770 // "Calculate" dynamic part and return it
771 return mt_rand($min, $max);
773 // Determine right template name
774 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
775 // Default is the frameset
776 $templateName = "surfbar_frameset";
778 // Any frame set? ;-)
779 if (isset($_GET['frame'])) {
780 // Use the frame as a template name part... ;-)
781 $templateName = sprintf("surfbar_frame_%s",
782 SQL_ESCAPE($_GET['frame'])
787 return $templateName;
789 // Check if the "reload lock" of the current user is full, call this function
790 // before you call SURFBAR_CHECK_RELOAD_LOCK().
791 function SURFBAR_CHECK_RELOAD_FULL() {
792 global $SURFBAR_CACHE;
797 // Cache static reload lock
798 $SURFBAR_CACHE['surf_lock'] = getConfig('surfbar_static_lock');
799 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
801 // Do we have dynamic model?
802 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
803 // "Calculate" dynamic lock
804 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
808 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
809 INNER JOIN `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
811 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)
813 array($GLOBALS['userid']), __FILE__, __LINE__
817 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
820 if (is_null($SURFBAR_CACHE['user_locks'])) {
821 // Then fix it to zero!
822 $SURFBAR_CACHE['user_locks'] = 0;
826 SQL_FREERESULT($result);
829 $total = SURFBAR_GET_TOTAL_URLS();
831 // Do we have some URLs in lock? Admins can always surf on own URLs!
832 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
833 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
838 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
839 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
840 // Determine depleted user account
841 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
843 // Is the exlude userid set?
844 if ($excludeUserId > 0) {
846 $UIDs['uid'][$excludeUserId] = $excludeUserId;
849 // Get amount from database
850 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
851 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
852 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND `status`='%s'",
853 array($status), __FILE__, __LINE__
857 list($cnt) = SQL_FETCHROW($result);
860 SQL_FREERESULT($result);
865 // Check wether the user is allowed to book more URLs
866 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
867 // Is this admin and userid is zero or does the user has some URLs left to book?
868 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < getConfig('surfbar_max_order')));
870 // Get total amount of URLs of given status for current user
871 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
872 // Is the user 0 and user is logged in?
873 if (($uid == 0) && (IS_MEMBER())) {
874 // Then use this userid
875 $uid = $GLOBALS['userid'];
876 } elseif ($uid == 0) {
878 return (getConfig('surfbar_max_order') + 1);
881 // Default is all URLs
884 // Is the status set?
885 if (is_array($status)) {
886 // Only URLs with these status
887 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
888 } elseif (!empty($status)) {
889 // Only URLs with this status
890 $ADD = sprintf(" AND `status`='%s'", $status);
891 } elseif (is_array($exclude)) {
892 // Exclude URLs with these status
893 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
894 } elseif (!empty($exclude)) {
895 // Exclude URLs with this status
896 $ADD = sprintf(" AND status != '%s'", $exclude);
899 // Get amount from database
900 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
901 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
902 WHERE userid=%s".$ADD."
904 array($uid, getConfig('surfbar_max_order')), __FILE__, __LINE__
908 list($cnt) = SQL_FETCHROW($result);
911 SQL_FREERESULT($result);
916 // Generate a validation code for the given id number
917 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
918 global $SURFBAR_CACHE;
920 // @TODO Invalid salt should be refused
921 $SURFBAR_CACHE['salt'] = "INVALID";
923 // Get code length from config
924 $length = getConfig('code_length');
927 if ($length == 0) $length = 10;
929 // Generate a code until the length matches
931 while (strlen($valCode) != $length) {
934 // Generate random hashed string
935 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
936 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
939 $SURFBAR_CACHE['salt'] = $salt;
940 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
943 // ... and now the validation code
944 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
945 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
948 // Hash it with md5() and salt it with the random string
949 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
951 // Finally encrypt it PGP-like and return it
952 $valHashedCode = generatePassString($hashedCode);
954 // Return hashed value
955 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
956 return $valHashedCode;
958 // Check validation code
959 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
960 global $SURFBAR_CACHE;
963 $urlId = bigintval($urlId);
965 // Now generate the code again
966 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
968 // Return result of checking hashes and salts
969 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
970 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
971 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
973 // Lockdown the userid/id combination (reload lock)
974 function SURFBAR_LOCKDOWN_ID ($urlId) {
975 //* DEBUG: */ print "LOCK!");
976 ///* DEBUG: */ return;
977 // Just add it to the database
978 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (userid, url_id) VALUES (%s, %s)",
979 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
981 // Remove the salt from database
982 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE url_id=%s AND userid=%s LIMIT 1",
983 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
985 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
986 function SURFBAR_PAY_POINTS () {
987 // Remove it from the URL owner
988 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
989 if (SURFBAR_GET_USERID() > 0) {
990 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
993 // Book it to the user
994 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
995 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
997 // Updates the statistics of current URL/userid
998 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1002 // Get allowed views
1003 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1005 // Do we have a limit?
1007 // Then count views_max down!
1008 $ADD .= ",views_max=views_max-1";
1012 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1013 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1015 // Update the stats entry
1016 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1017 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1019 // Was that update okay?
1020 if (SQL_AFFECTEDROWS() < 1) {
1021 // No, then insert entry
1022 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1023 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1026 // Update total/daily/weekly/monthly counter
1027 incrementConfigEntry('surfbar_total_counter');
1028 incrementConfigEntry('surfbar_daily_counter');
1029 incrementConfigEntry('surfbar_weekly_counter');
1030 incrementConfigEntry('surfbar_monthly_counter');
1032 // Update config as well
1033 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1035 // Update the salt for validation and statistics
1036 function SURFBAR_UPDATE_SALT_STATS () {
1037 // Update statistics record
1038 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1040 // Simply store the salt from cache away in database...
1041 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1042 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1045 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1048 if (SQL_AFFECTEDROWS() < 1) {
1049 // Insert missing entry!
1050 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1051 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1055 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1057 // Return if the update was okay
1058 return (SQL_AFFECTEDROWS() == 1);
1060 // Check if the reload lock is active for given id
1061 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1062 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1064 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1065 FROM `{!_MYSQL_PREFIX!}_surfbar_locks`
1066 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1067 ORDER BY last_surfed ASC
1069 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1073 list($cnt) = SQL_FETCHROW($result);
1076 SQL_FREERESULT($result);
1079 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1082 // Determine which user hash no more points left
1083 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1087 'points' => array(),
1088 'notified' => array(),
1091 // Do we have a current user id?
1092 if ((IS_MEMBER()) && ($limit == 0)) {
1093 // Then add this as well
1094 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1095 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1096 $UIDs['notified'][$GLOBALS['userid']] = 0;
1098 // Get all userid except logged in one
1099 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1100 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1101 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1102 ON u.userid=d.userid
1103 WHERE u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1105 ORDER BY u.userid ASC",
1106 array($GLOBALS['userid']), __FILE__, __LINE__);
1109 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1110 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1111 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1112 ON u.userid=d.userid
1113 WHERE u.`status`='ACTIVE'
1115 ORDER BY u.userid ASC", __FILE__, __LINE__);
1119 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1121 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1122 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1124 // Shall we add this to ignore?
1125 if ($points <= $limit) {
1127 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1128 $UIDs['uid'][$uid] = $uid;
1129 $UIDs['points'][$uid] = $points;
1130 $UIDs['notified'][$uid] = $notified;
1135 SQL_FREERESULT($result);
1138 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1143 // Determine how many users are Online in surfbar
1144 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1145 // Count all users in surfbar modue and return the value
1146 $result = SQL_QUERY_ESC("SELECT id
1147 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1148 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1150 array(getConfig('online_timeout')), __FILE__, __LINE__);
1153 $cnt = SQL_NUMROWS($result);
1156 SQL_FREERESULT($result);
1161 // Determine waiting time for one URL
1162 function SURFBAR_DETERMINE_WAIT_TIME () {
1163 // Get fixed reload lock
1164 $fixed = SURFBAR_GET_FIXED_RELOAD();
1166 // Is the fixed reload time set?
1172 // Static time is default
1173 $time = getConfig('surfbar_static_time');
1175 // Which payment model do we have?
1176 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1177 // "Calculate" dynamic time
1178 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1184 // Changes the status of an URL from given to other
1185 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1186 // Make new status always lower-case
1187 $newStatus = strtolower($newStatus);
1189 // Get URL data for status comparison if missing
1190 if ((!is_array($data)) || (count($data) == 0)) {
1191 // Fetch missing URL data
1192 $data = SURFBAR_GET_URL_DATA($urlId);
1195 // Is the new status set?
1196 if ((!is_string($newStatus)) || (empty($newStatus))) {
1197 // Abort here, but fine!
1201 // Is the status like prevStatus is saying?
1202 if ($data[$urlId]['status'] != $prevStatus) {
1203 // No, then abort here
1208 // Update the status now
1209 // ---------- Comment out for debugging/developing member actions! ---------
1210 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE id=%s LIMIT 1",
1211 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1212 // ---------- Comment out for debugging/developing member actions! ---------
1215 //if (SQL_AFFECTEDROWS() != 1) {
1216 // // No, something went wrong
1220 // Prepare content for notification routines
1221 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1222 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1223 $data[$urlId]['reward'] = TRANSLATE_COMMA(getConfig('surfbar_static_reward'));
1224 $data[$urlId]['costs'] = TRANSLATE_COMMA(getConfig('surfbar_static_costs'));
1226 // Do some dirty fixing here:
1227 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1228 // Fix for template change
1229 $newStatus = "continued";
1232 // Send admin notification
1233 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1235 // Send user notification
1236 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1241 // Calculate minimum value for dynamic payment model
1242 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1243 // Addon is zero by default
1247 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1250 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1253 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1256 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1259 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1261 // Get user's total URLs
1262 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1265 if ($totalUrls > 0) {
1266 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1268 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1274 // Calculate maximum value for dynamic payment model
1275 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1276 // Addon is zero by default
1283 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1286 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1289 $addon += abs($max * $percent * $totalUsers);
1292 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1295 $addon += abs($max * $percent * $totalUrls);
1300 // Calculate dynamic lock
1301 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1302 // Default lock is 30 seconds
1306 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1309 $addon = abs(log($onlineUsers / $addon + 1));
1314 // "Getter" for lock ids array
1315 function SURFBAR_GET_LOCK_IDS () {
1316 // Prepare some arrays
1321 // Get all id from locks within the timestamp
1322 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1324 {!_MYSQL_PREFIX!}_surfbar_locks
1328 id ASC", array($GLOBALS['userid']),
1329 __FILE__, __LINE__);
1332 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1334 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_SURF_LOCK()."", false);
1336 // Skip entries that are too old
1337 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($url, $ignored))) {
1339 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1341 // Add only if missing or bigger
1342 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1344 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1352 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1354 // Ignore these old entries!
1362 SQL_FREERESULT($result);
1367 // "Getter" for maximum random number
1368 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1369 // Count max availabe entries
1370 $result = SQL_QUERY("SELECT sbu.id AS cnt
1371 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1372 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1373 ON sbu.id=sbs.url_id
1374 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1376 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."
1377 GROUP BY sbu.id", __FILE__, __LINE__);
1380 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1383 $maxRand = SQL_NUMROWS($result);
1386 SQL_FREERESULT($result);
1391 // Load all URLs of the current user and return it as an array
1392 function SURFBAR_GET_USER_URLS () {
1397 $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
1398 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1399 WHERE u.userid=%s AND u.status != 'DELETED'
1401 array($GLOBALS['userid']), __FILE__, __LINE__);
1403 // Are there entries?
1404 if (SQL_NUMROWS($result) > 0) {
1406 while ($row = SQL_FETCHARRAY($result)) {
1408 $URLs[$row['id']] = $row;
1413 SQL_FREERESULT($result);
1418 // "Getter" for member action array for given status
1419 function SURFBAR_GET_ACTION_ARRAY ($status) {
1421 $returnArray = array();
1423 // Get all assigned actions
1424 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1425 array($status), __FILE__, __LINE__);
1427 // Some entries there?
1428 if (SQL_NUMROWS($result) > 0) {
1430 while (list($action) = SQL_FETCHROW($result)) {
1431 $returnArray[] = $action;
1436 SQL_FREERESULT($result);
1439 return $returnArray;
1441 // Reload to configured stop page
1442 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1443 // Internal or external?
1444 if ((getConfig('surfbar_pause_mode') == "INTERNAL") || (getConfig('surfbar_pause_url') == "")) {
1445 // Reload to internal page
1446 LOAD_URL("surfbar.php?frame=".$page);
1448 // Reload to external page
1449 LOAD_CONFIGURED_URL('surfbar_pause_url');
1453 // Determine next id for surfbar or get data for given id, always call this before you call other
1454 // getters below this function!!!
1455 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1456 global $SURFBAR_CACHE;
1458 // Default is no id and no random number
1464 // Get array with lock ids
1465 $USE = SURFBAR_GET_LOCK_IDS();
1467 // Shall we add some URL ids to ignore?
1469 if (count($USE) > 0) {
1471 $ADD = " AND sbu.id NOT IN (";
1472 foreach ($USE as $url_id => $lid) {
1474 $ADD .= $url_id.",";
1477 // Add closing bracket
1478 $ADD = substr($ADD, 0, -1) . ")";
1481 // Determine depleted user account
1482 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1484 // Get maximum randomness factor
1485 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1487 // If more than one URL can be called generate the random number!
1489 // Generate random number
1490 $randNum = mt_rand(0, ($maxRand - 1));
1493 // And query the database
1494 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1495 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed, sbu.fixed_reload
1496 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1497 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1498 ON sbu.id=sbs.url_id
1499 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1501 WHERE sbu.userid 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."
1503 ORDER BY l.last_surfed ASC, sbu.id ASC
1505 array($randNum), __FILE__, __LINE__
1508 // Get data from specified id number
1509 $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
1510 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1511 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1512 ON sbu.id=sbs.url_id
1513 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1515 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))
1517 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1521 // Is there an id number?
1522 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1523 if (SQL_NUMROWS($result) == 1) {
1525 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1526 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1527 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1529 // Determine waiting time
1530 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1532 // Is the last salt there?
1533 if (is_null($SURFBAR_CACHE['last_salt'])) {
1534 // Then repair it wit the static!
1535 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1536 $SURFBAR_CACHE['last_salt'] = "";
1539 // Fix missing last_surfed
1540 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1542 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1543 $SURFBAR_CACHE['last_surfed'] = 0;
1546 // Get base/fixed reward and costs
1547 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1548 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1549 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1551 // Only in dynamic model add the dynamic bonus!
1552 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1553 // Calculate dynamic reward/costs and add it
1554 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1555 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1556 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1560 $nextId = SURFBAR_GET_ID();
1564 SQL_FREERESULT($result);
1567 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1570 // -----------------------------------------------------------------------------
1571 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1572 // $SURFBAR_CACHE ARRAY!
1573 // -----------------------------------------------------------------------------
1574 // Private getter for data elements
1575 function SURFBAR_GET_DATA ($element) {
1576 global $SURFBAR_CACHE;
1577 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1582 // Is the entry there?
1583 if (isset($SURFBAR_CACHE[$element])) {
1585 $data = $SURFBAR_CACHE[$element];
1586 } else { // END - if
1588 print_r($SURFBAR_CACHE);
1594 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1597 // Getter for reward from cache
1598 function SURFBAR_GET_REWARD () {
1599 // Get data element and return its contents
1600 return SURFBAR_GET_DATA('reward');
1602 // Getter for costs from cache
1603 function SURFBAR_GET_COSTS () {
1604 // Get data element and return its contents
1605 return SURFBAR_GET_DATA('costs');
1607 // Getter for URL from cache
1608 function SURFBAR_GET_URL () {
1609 // Get data element and return its contents
1610 return SURFBAR_GET_DATA('url');
1612 // Getter for salt from cache
1613 function SURFBAR_GET_SALT () {
1614 // Get data element and return its contents
1615 return SURFBAR_GET_DATA('salt');
1617 // Getter for id from cache
1618 function SURFBAR_GET_ID () {
1619 // Get data element and return its contents
1620 return SURFBAR_GET_DATA('id');
1622 // Getter for userid from cache
1623 function SURFBAR_GET_USERID () {
1624 // Get data element and return its contents
1625 return SURFBAR_GET_DATA('userid');
1627 // Getter for user reload locks
1628 function SURFBAR_GET_USER_LOCKS () {
1629 // Get data element and return its contents
1630 return SURFBAR_GET_DATA('user_locks');
1632 // Getter for reload time
1633 function SURFBAR_GET_RELOAD_TIME () {
1634 // Get data element and return its contents
1635 return SURFBAR_GET_DATA('time');
1637 // Getter for allowed views
1638 function SURFBAR_GET_VIEWS_ALLOWED () {
1639 // Get data element and return its contents
1640 return SURFBAR_GET_DATA('views_allowed');
1642 // Getter for fixed reload
1643 function SURFBAR_GET_FIXED_RELOAD () {
1644 // Get data element and return its contents
1645 return SURFBAR_GET_DATA('fixed_reload');
1647 // Getter for surf lock
1648 function SURFBAR_GET_SURF_LOCK () {
1649 // Get data element and return its contents
1650 return SURFBAR_GET_DATA('surf_lock');