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 // By default no action is performed
210 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
211 // Important form elements are missing!
213 } elseif (!isset($URLs[$formData['id']])) {
214 // ID not found in cache
216 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
217 // Action not allowed for current URL status
222 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
225 if ($action != $formData['action']) {
226 // Invalid data in action found
230 // Create the function name for selected action
231 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
233 // Is the function there?
234 if (function_exists($functionName)) {
236 $URLs[$formData['id']]['new_status'] = $GLOBALS['cache_array']['surfbar']['new_status'];
238 // Extract URL data for call-back
239 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
241 // Action found so execute it
242 $performed = call_user_func_array($functionName, $urlData);
244 // Log invalid request
245 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
246 addFatalMessage("Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
252 // Validate if the requested action can be performed on current URL status
253 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
254 // Search for the requested action/status combination in database
255 $result = SQL_QUERY_ESC("SELECT new_status FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
256 array($action, $status), __FILE__, __LINE__);
258 // Is the entry there?
259 $isValid = (SQL_NUMROWS($result) == 1);
261 // Fetch the new status if found
264 list($GLOBALS['cache_array']['surfbar']['new_status']) = SQL_FETCHROW($result);
268 SQL_FREERESULT($result);
274 // -----------------------------------------------------------------------------
276 // -----------------------------------------------------------------------------
278 // Retreat a booked URL
279 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
280 // Create the data array for next function call
282 $urlData['id'] => $urlData
285 // Simply change the status here
286 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
288 // Book an URL now (from migration)
289 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
290 // Create the data array for next function call
292 $urlData['id'] => $urlData
295 // Simply change the status here
296 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
298 // Show edit form or do the changes
299 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
300 // Is the "execute" flag there?
301 if (isset($urlData['edit']['execute'])) {
302 // Execute the changes
303 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
307 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
309 // Show delete form or do the changes
310 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
311 // Is the "execute" flag there?
312 if (isset($urlData['delete']['execute'])) {
313 // Execute the changes
314 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
318 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
320 // Pause active banner
321 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
322 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
324 // Unpause stopped banner
325 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
326 // Fix missing entry for template
327 $urlData['edit'] = $urlData['unpause'];
328 $urlData['edit']['url'] = $urlData['url'];
329 $urlData['edit']['limit'] = $urlData['views_max'];
331 // Return status change
332 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
334 // Resubmit locked URL
335 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
336 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
338 // Display selected "action form"
339 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
340 // Translate some data
341 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
342 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
343 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
344 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
345 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
347 // Is the lock reason empty?
348 if (empty($urlData['lock_reason'])) {
349 // Fix it to three dashes
350 $urlData['lock_reason'] = "---";
353 // Include fields only for action 'edit'
354 if ($action == "edit") {
355 // Default is not limited
356 $urlData['limited_yes'] = "";
357 $urlData['limited_no'] = " checked=\"checked\"";
358 $urlData['limited'] = "false";
360 // Is this URL limited?
361 if ($urlData['views_max'] > 0) {
362 // Then rewrite form data
363 $urlData['limited_yes'] = " checked=\"checked\"";
364 $urlData['limited_no'] = "";
365 $urlData['limited'] = "true";
369 // Load the form and display it
370 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
372 // All fine by default ... ;-)
375 // Execute choosen action
376 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
377 // By default nothing is executed
380 // Is limitation "no" and "limit" is > 0?
381 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
382 // Set it to unlimited
383 $urlData[$action]['limit'] = 0;
386 // Construct function name
387 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
389 // Is 'userid' set and not 'uid' ?
390 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
392 $urlData['uid'] = $urlData['userid'];
395 // Is that function there?
396 if (function_exists($functionName)) {
397 // Execute the function
398 if (call_user_func_array($functionName, array($urlData)) == true) {
399 // Update status as well
400 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
404 addFatalMessage(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName);
410 // "Execute edit" function: Update changed data
411 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
412 // Default is nothing done
415 // Translate URLs for testing
416 $url1 = COMPILE_CODE($urlData['url']);
417 $url2 = COMPILE_CODE($urlData['edit']['url']);
419 // Has the URL or limit changed?
421 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
423 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",
424 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
433 // "Execute delete" function: Does nothing...
434 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
435 // Nothing special to do (see above function for such "special actions" to perform)
439 // -----------------------------------------------------------------------------
440 // Self-maintenance functions
441 // -----------------------------------------------------------------------------
444 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
445 // Handle URLs which limit has depleted so we can stop them
446 SURFBAR_HANDLE_DEPLETED_VIEWS();
448 // Handle low-points amounts
449 SURFBAR_HANDLE_LOW_POINTS();
451 // Handle URLs which limit has depleted
452 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
454 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND `status`='ACTIVE'");
456 // Do we have some entries?
457 if (count($urlArray) > 0) {
459 foreach ($urlArray as $id => $urlData) {
463 // Rewrite array for next call
464 $urlData[$id] = $data;
467 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
472 // Alert users which have URLs booked and are low on points amount
473 function SURFBAR_HANDLE_LOW_POINTS () {
475 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
477 // "Walk" through all URLs
478 foreach ($UIDs['uid'] as $uid => $dummy) {
479 // Is the last notification far enougth away to notify again?
480 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
484 'low' => TRANSLATE_COMMA(getConfig('surfbar_warn_low_points')),
485 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
486 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
487 'interval' => CREATE_FANCY_TIME(getConfig('surfbar_low_interval'))
491 SURFBAR_NOTIFY_USER("low_points", $content);
493 // Update last notified
494 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
495 array($uid), __FILE__, __LINE__);
501 // -----------------------------------------------------------------------------
503 // -----------------------------------------------------------------------------
506 // Looks up by an URL
507 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
508 // Now lookup that given URL by itself
509 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
512 return (count($urlArray) > 0);
515 // Load URL data by given search term and column
516 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
519 // By default nothing is found
520 $lastUrlData = array();
522 // Is the column an id number?
523 if (($column == "id") || ($column == "userid")) {
524 // Extra secure input
525 $searchTerm = bigintval($searchTerm);
528 // If the column is "id" there can be only one entry
530 if ($column == "id") {
534 // Look up the record
535 $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
536 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
537 WHERE %s='%s'".$add."
540 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
542 // Is there at least one record?
543 if (SQL_NUMROWS($result) > 0) {
545 while ($dataRow = SQL_FETCHARRAY($result)) {
546 // Shall we group these results?
547 if ($group == "id") {
548 // Add the row by id as index
549 $lastUrlData[$dataRow['id']] = $dataRow;
552 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
558 SQL_FREERESULT($result);
564 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
565 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
566 // Make sure by the user registered URLs are always pending
567 if ($addMode == "reg") $status = "PENDING";
570 $content = merge_array($extraFields, array(
572 'frametester' => FRAMETESTER($url),
577 // Is limit/reload set?
578 if (!isset($config['limit'])) $content['limit'] = 0;
579 if (!isset($config['reload'])) $content['reload'] = 0;
581 // Insert the URL into database
582 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
585 if ($content['insert_id'] == 0) {
586 // INSERT did not insert any data!
590 // Translate status and limit
591 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
593 // If in reg-mode we notify admin
594 if (($addMode == "reg") || (getConfig('surfbar_notify_admin_unlock') == "Y")) {
595 // Notify admin even when he as unlocked an email
596 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
600 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
602 // Return the insert id
603 return $content['insert_id'];
606 // Inserts an url by given data array and return the insert id
607 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
609 $uid = bigintval($urlData['uid']);
612 if (empty($uid)) $uid = 0;
614 // Just run the insert query for now
615 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)",
623 ), __FILE__, __LINE__
627 return SQL_INSERTID();
630 // Notify admin(s) with a selected message and content
631 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
632 // Prepare template name
633 $templateName = sprintf("admin_surfbar_%s", $messageType);
636 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
637 strtoupper($messageType)
640 // Is the subject line there?
641 if ((substr($subject, 0, 1) == "!") && (substr($subject, -1, 1) == "!")) {
642 // Set default subject if following eval() wents wrong
643 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
646 // Translate some data if present
647 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
648 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
649 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
650 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
651 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
652 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
654 // Send the notification out
655 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
658 // Notify the user about the performed action
659 function SURFBAR_NOTIFY_USER ($messageType, $content) {
660 // Skip notification if userid is zero
661 if ($content['uid'] == 0) {
665 // Prepare template name
666 $templateName = sprintf("member_surfbar_%s", $messageType);
669 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
670 strtoupper($messageType)
673 // Is the subject line there?
674 if ((substr($subject, 0, 1) == "!") && (substr($subject, -1, 1) == "!")) {
675 // Set default subject if following eval() wents wrong
676 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
679 // Translate some data if present
680 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
681 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
682 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
683 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
684 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
685 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
688 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
691 return SEND_EMAIL($content['uid'], $subject, $mailText);
693 // Translates the limit
694 function SURFBAR_TRANSLATE_LIMIT ($limit) {
698 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
701 $return = TRANSLATE_COMMA($limit);
707 // Translate the URL status
708 function SURFBAR_TRANSLATE_STATUS ($status) {
709 // Create constant name
710 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
712 // Set default translated status
713 $statusTranslated = "!".$constantName."!";
715 // Is the constant there?
716 if (defined($constantName)) {
717 // Then get it's value
718 $statusTranslated = constant($constantName);
722 return $statusTranslated;
725 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
726 // Static values are default
727 $reward = getConfig('surfbar_static_reward');
729 // Do we have static or dynamic?
730 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
731 // "Calculate" dynamic reward
733 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
735 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
743 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
744 // Static costs is default
745 $costs = getConfig('surfbar_static_costs');
747 // Do we have static or dynamic?
748 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
749 // "Calculate" dynamic costs
751 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
753 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
760 // "Calculate" dynamic add
761 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
762 // Get min/max values
763 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
764 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
766 // "Calculate" dynamic part and return it
767 return mt_rand($min, $max);
769 // Determine right template name
770 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
771 // Default is the frameset
772 $templateName = "surfbar_frameset";
774 // Any frame set? ;-)
775 if (REQUEST_ISSET_GET(('frame'))) {
776 // Use the frame as a template name part... ;-)
777 $templateName = sprintf("surfbar_frame_%s",
778 SQL_ESCAPE(REQUEST_GET('frame'))
783 return $templateName;
785 // Check if the "reload lock" of the current user is full, call this function
786 // before you call SURFBAR_CHECK_RELOAD_LOCK().
787 function SURFBAR_CHECK_RELOAD_FULL() {
791 // Cache static reload lock
792 $GLOBALS['cache_array']['surfbar']['surf_lock'] = getConfig('surfbar_static_lock');
793 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
795 // Do we have dynamic model?
796 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
797 // "Calculate" dynamic lock
798 $GLOBALS['cache_array']['surfbar']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
802 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
803 INNER JOIN `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
805 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)
807 array($GLOBALS['userid']), __FILE__, __LINE__
811 list($GLOBALS['cache_array']['surfbar']['user_locks']) = SQL_FETCHROW($result);
814 if (is_null($GLOBALS['cache_array']['surfbar']['user_locks'])) {
815 // Then fix it to zero!
816 $GLOBALS['cache_array']['surfbar']['user_locks'] = 0;
820 SQL_FREERESULT($result);
823 $total = SURFBAR_GET_TOTAL_URLS();
825 // Do we have some URLs in lock? Admins can always surf on own URLs!
826 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
827 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
832 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
833 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
834 // Determine depleted user account
835 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
837 // Is the exlude userid set?
838 if ($excludeUserId > 0) {
840 $UIDs['uid'][$excludeUserId] = $excludeUserId;
843 // Get amount from database
844 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
845 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
846 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND `status`='%s'",
847 array($status), __FILE__, __LINE__
851 list($cnt) = SQL_FETCHROW($result);
854 SQL_FREERESULT($result);
859 // Check wether the user is allowed to book more URLs
860 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
861 // Is this admin and userid is zero or does the user has some URLs left to book?
862 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < getConfig('surfbar_max_order')));
864 // Get total amount of URLs of given status for current user
865 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
866 // Is the user 0 and user is logged in?
867 if (($uid == 0) && (IS_MEMBER())) {
868 // Then use this userid
869 $uid = $GLOBALS['userid'];
870 } elseif ($uid == 0) {
872 return (getConfig('surfbar_max_order') + 1);
875 // Default is all URLs
878 // Is the status set?
879 if (is_array($status)) {
880 // Only URLs with these status
881 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
882 } elseif (!empty($status)) {
883 // Only URLs with this status
884 $ADD = sprintf(" AND `status`='%s'", $status);
885 } elseif (is_array($exclude)) {
886 // Exclude URLs with these status
887 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
888 } elseif (!empty($exclude)) {
889 // Exclude URLs with this status
890 $ADD = sprintf(" AND status != '%s'", $exclude);
893 // Get amount from database
894 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
895 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
896 WHERE userid=%s".$ADD."
898 array($uid, getConfig('surfbar_max_order')), __FILE__, __LINE__
902 list($cnt) = SQL_FETCHROW($result);
905 SQL_FREERESULT($result);
910 // Generate a validation code for the given id number
911 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
912 // @TODO Invalid salt should be refused
913 $GLOBALS['cache_array']['surfbar']['salt'] = "INVALID";
915 // Get code length from config
916 $length = getConfig('code_length');
919 if ($length == 0) $length = 10;
921 // Generate a code until the length matches
923 while (strlen($valCode) != $length) {
926 // Generate random hashed string
927 $GLOBALS['cache_array']['surfbar']['salt'] = sha1(GEN_PASS(255));
928 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
931 $GLOBALS['cache_array']['surfbar']['salt'] = $salt;
932 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
935 // ... and now the validation code
936 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
937 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
940 // Hash it with md5() and salt it with the random string
941 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
943 // Finally encrypt it PGP-like and return it
944 $valHashedCode = generatePassString($hashedCode);
946 // Return hashed value
947 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
948 return $valHashedCode;
950 // Check validation code
951 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
953 $urlId = bigintval($urlId);
955 // Now generate the code again
956 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
958 // Return result of checking hashes and salts
959 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
960 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
961 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
963 // Lockdown the userid/id combination (reload lock)
964 function SURFBAR_LOCKDOWN_ID ($urlId) {
965 //* DEBUG: */ print "LOCK!");
966 ///* DEBUG: */ return;
967 // Just add it to the database
968 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (userid, url_id) VALUES (%s, %s)",
969 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
971 // Remove the salt from database
972 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE url_id=%s AND userid=%s LIMIT 1",
973 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
975 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
976 function SURFBAR_PAY_POINTS () {
977 // Remove it from the URL owner
978 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
979 if (SURFBAR_GET_USERID() > 0) {
980 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
983 // Book it to the user
984 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
985 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
987 // Updates the statistics of current URL/userid
988 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
993 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
995 // Do we have a limit?
997 // Then count views_max down!
998 $ADD .= ",views_max=views_max-1";
1002 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1003 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1005 // Update the stats entry
1006 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1007 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1009 // Was that update okay?
1010 if (SQL_AFFECTEDROWS() < 1) {
1011 // No, then insert entry
1012 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1013 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1016 // Update total/daily/weekly/monthly counter
1017 incrementConfigEntry('surfbar_total_counter');
1018 incrementConfigEntry('surfbar_daily_counter');
1019 incrementConfigEntry('surfbar_weekly_counter');
1020 incrementConfigEntry('surfbar_monthly_counter');
1022 // Update config as well
1023 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1025 // Update the salt for validation and statistics
1026 function SURFBAR_UPDATE_SALT_STATS () {
1027 // Update statistics record
1028 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1030 // Simply store the salt from cache away in database...
1031 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1032 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1035 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1038 if (SQL_AFFECTEDROWS() < 1) {
1039 // Insert missing entry!
1040 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1041 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1045 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1047 // Return if the update was okay
1048 return (SQL_AFFECTEDROWS() == 1);
1050 // Check if the reload lock is active for given id
1051 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1052 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1054 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1055 FROM `{!_MYSQL_PREFIX!}_surfbar_locks`
1056 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1057 ORDER BY last_surfed ASC
1059 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1063 list($cnt) = SQL_FETCHROW($result);
1066 SQL_FREERESULT($result);
1069 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1072 // Determine which user hash no more points left
1073 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1077 'points' => array(),
1078 'notified' => array(),
1081 // Do we have a current user id?
1082 if ((IS_MEMBER()) && ($limit == 0)) {
1083 // Then add this as well
1084 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1085 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1086 $UIDs['notified'][$GLOBALS['userid']] = 0;
1088 // Get all userid except logged in one
1089 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1090 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1091 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1092 ON u.userid=d.userid
1093 WHERE u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1095 ORDER BY u.userid ASC",
1096 array($GLOBALS['userid']), __FILE__, __LINE__);
1099 $result = SQL_QUERY("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.`status`='ACTIVE'
1105 ORDER BY u.userid ASC", __FILE__, __LINE__);
1109 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1111 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1112 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1114 // Shall we add this to ignore?
1115 if ($points <= $limit) {
1117 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1118 $UIDs['uid'][$uid] = $uid;
1119 $UIDs['points'][$uid] = $points;
1120 $UIDs['notified'][$uid] = $notified;
1125 SQL_FREERESULT($result);
1128 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1133 // Determine how many users are Online in surfbar
1134 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1135 // Count all users in surfbar modue and return the value
1136 $result = SQL_QUERY_ESC("SELECT id
1137 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1138 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1140 array(getConfig('online_timeout')), __FILE__, __LINE__);
1143 $cnt = SQL_NUMROWS($result);
1146 SQL_FREERESULT($result);
1151 // Determine waiting time for one URL
1152 function SURFBAR_DETERMINE_WAIT_TIME () {
1153 // Get fixed reload lock
1154 $fixed = SURFBAR_GET_FIXED_RELOAD();
1156 // Is the fixed reload time set?
1162 // Static time is default
1163 $time = getConfig('surfbar_static_time');
1165 // Which payment model do we have?
1166 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1167 // "Calculate" dynamic time
1168 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1174 // Changes the status of an URL from given to other
1175 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1176 // Make new status always lower-case
1177 $newStatus = strtolower($newStatus);
1179 // Get URL data for status comparison if missing
1180 if ((!is_array($data)) || (count($data) == 0)) {
1181 // Fetch missing URL data
1182 $data = SURFBAR_GET_URL_DATA($urlId);
1185 // Is the new status set?
1186 if ((!is_string($newStatus)) || (empty($newStatus))) {
1187 // Abort here, but fine!
1191 // Is the status like prevStatus is saying?
1192 if ($data[$urlId]['status'] != $prevStatus) {
1193 // No, then abort here
1198 // Update the status now
1199 // ---------- Comment out for debugging/developing member actions! ---------
1200 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE id=%s LIMIT 1",
1201 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1202 // ---------- Comment out for debugging/developing member actions! ---------
1205 //if (SQL_AFFECTEDROWS() != 1) {
1206 // // No, something went wrong
1210 // Prepare content for notification routines
1211 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1212 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1213 $data[$urlId]['reward'] = TRANSLATE_COMMA(getConfig('surfbar_static_reward'));
1214 $data[$urlId]['costs'] = TRANSLATE_COMMA(getConfig('surfbar_static_costs'));
1216 // Do some dirty fixing here:
1217 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1218 // Fix for template change
1219 $newStatus = "continued";
1222 // Send admin notification
1223 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1225 // Send user notification
1226 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1231 // Calculate minimum value for dynamic payment model
1232 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1233 // Addon is zero by default
1237 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1240 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1243 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1246 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1249 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1251 // Get user's total URLs
1252 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1255 if ($totalUrls > 0) {
1256 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1258 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1264 // Calculate maximum value for dynamic payment model
1265 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1266 // Addon is zero by default
1273 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1276 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1279 $addon += abs($max * $percent * $totalUsers);
1282 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1285 $addon += abs($max * $percent * $totalUrls);
1290 // Calculate dynamic lock
1291 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1292 // Default lock is 30 seconds
1296 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1299 $addon = abs(log($onlineUsers / $addon + 1));
1304 // "Getter" for lock ids array
1305 function SURFBAR_GET_LOCK_IDS () {
1306 // Prepare some arrays
1311 // Get all id from locks within the timestamp
1312 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1314 {!_MYSQL_PREFIX!}_surfbar_locks
1318 id ASC", array($GLOBALS['userid']),
1319 __FILE__, __LINE__);
1322 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1324 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_SURF_LOCK()."", false);
1326 // Skip entries that are too old
1327 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($url, $ignored))) {
1329 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1331 // Add only if missing or bigger
1332 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1334 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1342 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1344 // Ignore these old entries!
1352 SQL_FREERESULT($result);
1357 // "Getter" for maximum random number
1358 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1359 // Count max availabe entries
1360 $result = SQL_QUERY("SELECT sbu.id AS cnt
1361 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1362 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1363 ON sbu.id=sbs.url_id
1364 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1366 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."
1367 GROUP BY sbu.id", __FILE__, __LINE__);
1370 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1373 $maxRand = SQL_NUMROWS($result);
1376 SQL_FREERESULT($result);
1381 // Load all URLs of the current user and return it as an array
1382 function SURFBAR_GET_USER_URLS () {
1387 $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
1388 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1389 WHERE u.userid=%s AND u.status != 'DELETED'
1391 array($GLOBALS['userid']), __FILE__, __LINE__);
1393 // Are there entries?
1394 if (SQL_NUMROWS($result) > 0) {
1396 while ($row = SQL_FETCHARRAY($result)) {
1398 $URLs[$row['id']] = $row;
1403 SQL_FREERESULT($result);
1408 // "Getter" for member action array for given status
1409 function SURFBAR_GET_ACTION_ARRAY ($status) {
1411 $returnArray = array();
1413 // Get all assigned actions
1414 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1415 array($status), __FILE__, __LINE__);
1417 // Some entries there?
1418 if (SQL_NUMROWS($result) > 0) {
1420 while (list($action) = SQL_FETCHROW($result)) {
1421 $returnArray[] = $action;
1426 SQL_FREERESULT($result);
1429 return $returnArray;
1431 // Reload to configured stop page
1432 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1433 // Internal or external?
1434 if ((getConfig('surfbar_pause_mode') == "INTERNAL") || (getConfig('surfbar_pause_url') == "")) {
1435 // Reload to internal page
1436 LOAD_URL("surfbar.php?frame=".$page);
1438 // Reload to external page
1439 LOAD_CONFIGURED_URL('surfbar_pause_url');
1443 // Determine next id for surfbar or get data for given id, always call this before you call other
1444 // getters below this function!!!
1445 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1446 // Default is no id and no random number
1452 // Get array with lock ids
1453 $USE = SURFBAR_GET_LOCK_IDS();
1455 // Shall we add some URL ids to ignore?
1457 if (count($USE) > 0) {
1459 $ADD = " AND sbu.id NOT IN (";
1460 foreach ($USE as $url_id => $lid) {
1462 $ADD .= $url_id.",";
1465 // Add closing bracket
1466 $ADD = substr($ADD, 0, -1) . ")";
1469 // Determine depleted user account
1470 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1472 // Get maximum randomness factor
1473 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1475 // If more than one URL can be called generate the random number!
1477 // Generate random number
1478 $randNum = mt_rand(0, ($maxRand - 1));
1481 // And query the database
1482 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1483 $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
1484 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1485 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1486 ON sbu.id=sbs.url_id
1487 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1489 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."
1491 ORDER BY l.last_surfed ASC, sbu.id ASC
1493 array($randNum), __FILE__, __LINE__
1496 // Get data from specified id number
1497 $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
1498 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1499 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1500 ON sbu.id=sbs.url_id
1501 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1503 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))
1505 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1509 // Is there an id number?
1510 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1511 if (SQL_NUMROWS($result) == 1) {
1513 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - BEFORE", false);
1514 $GLOBALS['cache_array']['surfbar'] = merge_array($GLOBALS['cache_array']['surfbar'], SQL_FETCHARRAY($result));
1515 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - AFTER", false);
1517 // Determine waiting time
1518 $GLOBALS['cache_array']['surfbar']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1520 // Is the last salt there?
1521 if (is_null($GLOBALS['cache_array']['surfbar']['last_salt'])) {
1522 // Then repair it wit the static!
1523 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1524 $GLOBALS['cache_array']['surfbar']['last_salt'] = "";
1527 // Fix missing last_surfed
1528 if ((!isset($GLOBALS['cache_array']['surfbar']['last_surfed'])) || (is_null($GLOBALS['cache_array']['surfbar']['last_surfed']))) {
1530 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1531 $GLOBALS['cache_array']['surfbar']['last_surfed'] = 0;
1534 // Get base/fixed reward and costs
1535 $GLOBALS['cache_array']['surfbar']['reward'] = SURFBAR_DETERMINE_REWARD();
1536 $GLOBALS['cache_array']['surfbar']['costs'] = SURFBAR_DETERMINE_COSTS();
1537 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1539 // Only in dynamic model add the dynamic bonus!
1540 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1541 // Calculate dynamic reward/costs and add it
1542 $GLOBALS['cache_array']['surfbar']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1543 $GLOBALS['cache_array']['surfbar']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1544 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1548 $nextId = SURFBAR_GET_ID();
1552 SQL_FREERESULT($result);
1555 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1558 // -----------------------------------------------------------------------------
1559 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1560 // $GLOBALS['cache_array']['surfbar'] ARRAY!
1561 // -----------------------------------------------------------------------------
1562 // Private getter for data elements
1563 function SURFBAR_GET_DATA ($element) {
1564 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1569 // Is the entry there?
1570 if (isset($GLOBALS['cache_array']['surfbar'][$element])) {
1572 $data = $GLOBALS['cache_array']['surfbar'][$element];
1573 } else { // END - if
1575 print_r($GLOBALS['cache_array']['surfbar']);
1581 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1584 // Getter for reward from cache
1585 function SURFBAR_GET_REWARD () {
1586 // Get data element and return its contents
1587 return SURFBAR_GET_DATA('reward');
1589 // Getter for costs from cache
1590 function SURFBAR_GET_COSTS () {
1591 // Get data element and return its contents
1592 return SURFBAR_GET_DATA('costs');
1594 // Getter for URL from cache
1595 function SURFBAR_GET_URL () {
1596 // Get data element and return its contents
1597 return SURFBAR_GET_DATA('url');
1599 // Getter for salt from cache
1600 function SURFBAR_GET_SALT () {
1601 // Get data element and return its contents
1602 return SURFBAR_GET_DATA('salt');
1604 // Getter for id from cache
1605 function SURFBAR_GET_ID () {
1606 // Get data element and return its contents
1607 return SURFBAR_GET_DATA('id');
1609 // Getter for userid from cache
1610 function SURFBAR_GET_USERID () {
1611 // Get data element and return its contents
1612 return SURFBAR_GET_DATA('userid');
1614 // Getter for user reload locks
1615 function SURFBAR_GET_USER_LOCKS () {
1616 // Get data element and return its contents
1617 return SURFBAR_GET_DATA('user_locks');
1619 // Getter for reload time
1620 function SURFBAR_GET_RELOAD_TIME () {
1621 // Get data element and return its contents
1622 return SURFBAR_GET_DATA('time');
1624 // Getter for allowed views
1625 function SURFBAR_GET_VIEWS_ALLOWED () {
1626 // Get data element and return its contents
1627 return SURFBAR_GET_DATA('views_allowed');
1629 // Getter for fixed reload
1630 function SURFBAR_GET_FIXED_RELOAD () {
1631 // Get data element and return its contents
1632 return SURFBAR_GET_DATA('fixed_reload');
1634 // Getter for surf lock
1635 function SURFBAR_GET_SURF_LOCK () {
1636 // Get data element and return its contents
1637 return SURFBAR_GET_DATA('surf_lock');