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 * $Date:: 2009-03-06 20:24:32 +0100 (Fr, 06. Mär 2009) $ *
15 * $Tag:: 0.2.1-FINAL $ *
16 * $Author:: stelzi $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
45 // -----------------------------------------------------------------------------
47 // -----------------------------------------------------------------------------
49 // Admin has added an URL with given user id and so on
50 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
55 } elseif (!VALIDATE_URL($url)) {
58 } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
59 // URL already found in surfbar!
61 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
64 } elseif ("".($limit + 0)."" != "".$limit."") {
65 // Invalid amount entered
67 } elseif ("".($reload + 0)."" != "".$reload."") {
68 // Invalid amount entered
72 // Register the new URL
73 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", array('limit' => $limit, 'reload' => $reload));
75 // Admin unlocked an email so we can migrate the URL
76 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
81 } elseif (!VALIDATE_URL($url)) {
84 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
85 // URL already found in surfbar!
87 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
92 // Register the new URL
93 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
95 // Admin function for unlocking URLs
96 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
97 // Is this an admin or invalid array?
99 // Not admin or invalid IDs array
101 } elseif (!is_array($IDs)) {
104 } elseif (count($IDs) == 0) {
109 // Set to true to make AND expression valid if first URL got unlocked
112 // Update the status for all ids
113 foreach ($IDs as $id => $dummy) {
114 // Test all ids through (ignores failed)
115 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
118 // Return total status
121 // Admin function for rejecting URLs
122 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
123 // Is this an admin or invalid array?
125 // Not admin or invalid IDs array
127 } elseif (!is_array($IDs)) {
130 } elseif (count($IDs) == 0) {
135 // Set to true to make AND expression valid if first URL got unlocked
138 // Update the status for all ids
139 foreach ($IDs as $id => $dummy) {
140 // Test all ids through (ignores failed)
141 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
144 // Return total status
148 // -----------------------------------------------------------------------------
150 // -----------------------------------------------------------------------------
152 // Member has added an URL
153 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
154 // Do some pre-checks
158 } elseif (!VALIDATE_URL($url)) {
161 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
162 // URL already found in surfbar!
164 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
167 } elseif ("".($limit + 0)."" != "".$limit."") {
168 // Invalid amount entered
172 // Register the new URL
173 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", array('limit' => $limit));
175 // Create list of actions depending on status for the user
176 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
177 // Load all actions in an array for given status
178 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
181 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
185 $width = round(100 / count($actionArray));
187 // "Walk" through all actions and create forms
188 foreach ($actionArray as $actionId=>$action) {
189 // Add form for this action
190 $OUT .= sprintf(LOAD_TEMPLATE("member_surfbar_list_form", true),
206 // Do the member form request
207 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
208 // By default no action is performed
215 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
216 // Important form elements are missing!
218 } elseif (!isset($URLs[$formData['id']])) {
219 // ID not found in cache
221 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
222 // Action not allowed for current URL status
227 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
230 if ($action != $formData['action']) {
231 // Invalid data in action found
235 // Create the function name for selected action
236 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
238 // Is the function there?
239 if (function_exists($functionName)) {
241 $URLs[$formData['id']]['new_status'] = $GLOBALS['cache_array']['surfbar']['new_status'];
243 // Extract URL data for call-back
244 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
246 // Action found so execute it
247 $performed = call_user_func_array($functionName, $urlData);
249 // Log invalid request
250 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
251 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
257 // Validate if the requested action can be performed on current URL status
258 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
259 // Search for the requested action/status combination in database
260 $result = SQL_QUERY_ESC("SELECT new_status FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
261 array($action, $status), __FUNCTION__, __LINE__);
263 // Is the entry there?
264 $isValid = (SQL_NUMROWS($result) == 1);
266 // Fetch the new status if found
269 list($GLOBALS['cache_array']['surfbar']['new_status']) = SQL_FETCHROW($result);
273 SQL_FREERESULT($result);
279 // -----------------------------------------------------------------------------
281 // -----------------------------------------------------------------------------
283 // Retreat a booked URL
284 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
285 // Create the data array for next function call
287 $urlData['id'] => $urlData
290 // Simply change the status here
291 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
293 // Book an URL now (from migration)
294 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
295 // Create the data array for next function call
297 $urlData['id'] => $urlData
300 // Simply change the status here
301 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
303 // Show edit form or do the changes
304 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
305 // Is the "execute" flag there?
306 if (isset($urlData['edit']['execute'])) {
307 // Execute the changes
308 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
312 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
314 // Show delete form or do the changes
315 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
316 // Is the "execute" flag there?
317 if (isset($urlData['delete']['execute'])) {
318 // Execute the changes
319 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
323 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
325 // Pause active banner
326 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
327 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
329 // Unpause stopped banner
330 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
331 // Fix missing entry for template
332 $urlData['edit'] = $urlData['unpause'];
333 $urlData['edit']['url'] = $urlData['url'];
334 $urlData['edit']['limit'] = $urlData['views_max'];
336 // Return status change
337 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
339 // Resubmit locked URL
340 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
341 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
343 // Display selected "action form"
344 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
345 // Translate some data
346 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
347 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
348 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
349 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
350 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
352 // Is the lock reason empty?
353 if (empty($urlData['lock_reason'])) {
354 // Fix it to three dashes
355 $urlData['lock_reason'] = "---";
358 // Include fields only for action 'edit'
359 if ($action == "edit") {
360 // Default is not limited
361 $urlData['limited_yes'] = "";
362 $urlData['limited_no'] = " checked=\"checked\"";
363 $urlData['limited'] = "false";
365 // Is this URL limited?
366 if ($urlData['views_max'] > 0) {
367 // Then rewrite form data
368 $urlData['limited_yes'] = " checked=\"checked\"";
369 $urlData['limited_no'] = "";
370 $urlData['limited'] = "true";
374 // Load the form and display it
375 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
377 // All fine by default ... ;-)
380 // Execute choosen action
381 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
382 // By default nothing is executed
385 // Is limitation "no" and "limit" is > 0?
386 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
387 // Set it to unlimited
388 $urlData[$action]['limit'] = 0;
391 // Construct function name
392 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
394 // Is 'userid' set and not 'uid' ?
395 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
397 $urlData['uid'] = $urlData['userid'];
400 // Is that function there?
401 if (function_exists($functionName)) {
402 // Execute the function
403 if (call_user_func_array($functionName, array($urlData)) == true) {
404 // Update status as well
405 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
409 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
415 // "Execute edit" function: Update changed data
416 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
417 // Default is nothing done
420 // Translate URLs for testing
421 $url1 = COMPILE_CODE($urlData['url']);
422 $url2 = COMPILE_CODE($urlData['edit']['url']);
424 // Has the URL or limit changed?
426 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
428 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",
429 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
438 // "Execute delete" function: Does nothing...
439 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
440 // Nothing special to do (see above function for such "special actions" to perform)
444 // -----------------------------------------------------------------------------
445 // Self-maintenance functions
446 // -----------------------------------------------------------------------------
449 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
450 // Handle URLs which limit has depleted so we can stop them
451 SURFBAR_HANDLE_DEPLETED_VIEWS();
453 // Handle low-points amounts
454 SURFBAR_HANDLE_LOW_POINTS();
456 // Handle URLs which limit has depleted
457 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
459 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND `status`='ACTIVE'");
461 // Do we have some entries?
462 if (count($urlArray) > 0) {
464 foreach ($urlArray as $id => $urlData) {
468 // Rewrite array for next call
469 $urlData[$id] = $data;
472 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
477 // Alert users which have URLs booked and are low on points amount
478 function SURFBAR_HANDLE_LOW_POINTS () {
480 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
482 // "Walk" through all URLs
483 foreach ($UIDs['uid'] as $uid => $dummy) {
484 // Is the last notification far enougth away to notify again?
485 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
489 'low' => TRANSLATE_COMMA(getConfig('surfbar_warn_low_points')),
490 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
491 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
492 'interval' => CREATE_FANCY_TIME(getConfig('surfbar_low_interval'))
496 SURFBAR_NOTIFY_USER("low_points", $content);
498 // Update last notified
499 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
500 array($uid), __FUNCTION__, __LINE__);
506 // -----------------------------------------------------------------------------
508 // -----------------------------------------------------------------------------
511 // Looks up by an URL
512 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
513 // Now lookup that given URL by itself
514 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
517 return (count($urlArray) > 0);
520 // Load URL data by given search term and column
521 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
524 // By default nothing is found
525 $lastUrlData = array();
527 // Is the column an id number?
528 if (($column == "id") || ($column == "userid")) {
529 // Extra secure input
530 $searchTerm = bigintval($searchTerm);
533 // If the column is "id" there can be only one entry
535 if ($column == "id") {
539 // Look up the record
540 $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
541 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
542 WHERE %s='%s'".$add."
545 array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
547 // Is there at least one record?
548 if (SQL_NUMROWS($result) > 0) {
550 while ($dataRow = SQL_FETCHARRAY($result)) {
551 // Shall we group these results?
552 if ($group == "id") {
553 // Add the row by id as index
554 $lastUrlData[$dataRow['id']] = $dataRow;
557 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
563 SQL_FREERESULT($result);
569 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
570 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
571 // Make sure by the user registered URLs are always pending
572 if ($addMode == "reg") $status = "PENDING";
575 $content = merge_array($extraFields, array(
577 'frametester' => FRAMETESTER($url),
582 // Is limit/reload set?
583 if (!isset($config['limit'])) $content['limit'] = 0;
584 if (!isset($config['reload'])) $content['reload'] = 0;
586 // Insert the URL into database
587 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
590 if ($content['insert_id'] == 0) {
591 // INSERT did not insert any data!
595 // Translate status and limit
596 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
598 // If in reg-mode we notify admin
599 if (($addMode == "reg") || (getConfig('surfbar_notify_admin_unlock') == "Y")) {
600 // Notify admin even when he as unlocked an email
601 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
605 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
607 // Return the insert id
608 return $content['insert_id'];
611 // Inserts an url by given data array and return the insert id
612 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
614 $uid = bigintval($urlData['uid']);
617 if (empty($uid)) $uid = 0;
619 // Just run the insert query for now
620 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)",
628 ), __FUNCTION__, __LINE__
632 return SQL_INSERTID();
635 // Notify admin(s) with a selected message and content
636 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
637 // Prepare template name
638 $templateName = sprintf("admin_surfbar_%s", $messageType);
641 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
642 strtoupper($messageType)
645 // Is the subject line there?
646 if ((substr($subject, 0, 1) == "!") && (substr($subject, -1, 1) == "!")) {
647 // Set default subject if following eval() wents wrong
648 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
651 // Translate some data if present
652 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
653 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
654 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
655 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
656 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
657 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
659 // Send the notification out
660 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
663 // Notify the user about the performed action
664 function SURFBAR_NOTIFY_USER ($messageType, $content) {
665 // Skip notification if userid is zero
666 if ($content['uid'] == 0) {
670 // Prepare template name
671 $templateName = sprintf("member_surfbar_%s", $messageType);
674 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
675 strtoupper($messageType)
678 // Is the subject line there?
679 if ((substr($subject, 0, 1) == "!") && (substr($subject, -1, 1) == "!")) {
680 // Set default subject if following eval() wents wrong
681 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
684 // Translate some data if present
685 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
686 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
687 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
688 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
689 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
690 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
693 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
696 return SEND_EMAIL($content['uid'], $subject, $mailText);
698 // Translates the limit
699 function SURFBAR_TRANSLATE_LIMIT ($limit) {
703 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
706 $return = TRANSLATE_COMMA($limit);
712 // Translate the URL status
713 function SURFBAR_TRANSLATE_STATUS ($status) {
714 // Create constant name
715 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
717 // Set default translated status
718 $statusTranslated = "!".$constantName."!";
720 // Is the constant there?
721 if (defined($constantName)) {
722 // Then get it's value
723 $statusTranslated = constant($constantName);
727 return $statusTranslated;
730 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
731 // Static values are default
732 $reward = getConfig('surfbar_static_reward');
734 // Do we have static or dynamic?
735 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
736 // "Calculate" dynamic reward
738 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
740 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
748 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
749 // Static costs is default
750 $costs = getConfig('surfbar_static_costs');
752 // Do we have static or dynamic?
753 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
754 // "Calculate" dynamic costs
756 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
758 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
765 // "Calculate" dynamic add
766 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
767 // Get min/max values
768 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
769 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
771 // "Calculate" dynamic part and return it
772 return mt_rand($min, $max);
774 // Determine right template name
775 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
776 // Default is the frameset
777 $templateName = "surfbar_frameset";
779 // Any frame set? ;-)
780 if (REQUEST_ISSET_GET(('frame'))) {
781 // Use the frame as a template name part... ;-)
782 $templateName = sprintf("surfbar_frame_%s",
783 REQUEST_GET(('frame'))
788 return $templateName;
790 // Check if the "reload lock" of the current user is full, call this function
791 // before you call SURFBAR_CHECK_RELOAD_LOCK().
792 function SURFBAR_CHECK_RELOAD_FULL() {
796 // Cache static reload lock
797 $GLOBALS['cache_array']['surfbar']['surf_lock'] = getConfig('surfbar_static_lock');
798 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
800 // Do we have dynamic model?
801 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
802 // "Calculate" dynamic lock
803 $GLOBALS['cache_array']['surfbar']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
807 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
808 INNER JOIN `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
810 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)
812 array($GLOBALS['userid']), __FUNCTION__, __LINE__
816 list($GLOBALS['cache_array']['surfbar']['user_locks']) = SQL_FETCHROW($result);
819 if (is_null($GLOBALS['cache_array']['surfbar']['user_locks'])) {
820 // Then fix it to zero!
821 $GLOBALS['cache_array']['surfbar']['user_locks'] = 0;
825 SQL_FREERESULT($result);
828 $total = SURFBAR_GET_TOTAL_URLS();
830 // Do we have some URLs in lock? Admins can always surf on own URLs!
831 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
832 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
837 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
838 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
839 // Determine depleted user account
840 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
842 // Is the exlude userid set?
843 if ($excludeUserId > 0) {
845 $UIDs['uid'][$excludeUserId] = $excludeUserId;
848 // Get amount from database
849 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
850 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
851 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND `status`='%s'",
852 array($status), __FUNCTION__, __LINE__
856 list($cnt) = SQL_FETCHROW($result);
859 SQL_FREERESULT($result);
864 // Check wether the user is allowed to book more URLs
865 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
866 // Is this admin and userid is zero or does the user has some URLs left to book?
867 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < getConfig('surfbar_max_order')));
869 // Get total amount of URLs of given status for current user
870 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
871 // Is the user 0 and user is logged in?
872 if (($uid == 0) && (IS_MEMBER())) {
873 // Then use this userid
874 $uid = $GLOBALS['userid'];
875 } elseif ($uid == 0) {
877 return (getConfig('surfbar_max_order') + 1);
880 // Default is all URLs
883 // Is the status set?
884 if (is_array($status)) {
885 // Only URLs with these status
886 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
887 } elseif (!empty($status)) {
888 // Only URLs with this status
889 $ADD = sprintf(" AND `status`='%s'", $status);
890 } elseif (is_array($exclude)) {
891 // Exclude URLs with these status
892 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
893 } elseif (!empty($exclude)) {
894 // Exclude URLs with this status
895 $ADD = sprintf(" AND status != '%s'", $exclude);
898 // Get amount from database
899 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
900 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
901 WHERE userid=%s".$ADD."
903 array($uid, getConfig('surfbar_max_order')), __FUNCTION__, __LINE__
907 list($cnt) = SQL_FETCHROW($result);
910 SQL_FREERESULT($result);
915 // Generate a validation code for the given id number
916 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
917 // @TODO Invalid salt should be refused
918 $GLOBALS['cache_array']['surfbar']['salt'] = "INVALID";
920 // Get code length from config
921 $length = getConfig('code_length');
924 if ($length == 0) $length = 10;
926 // Generate a code until the length matches
928 while (strlen($valCode) != $length) {
931 // Generate random hashed string
932 $GLOBALS['cache_array']['surfbar']['salt'] = sha1(GEN_PASS(255));
933 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
936 $GLOBALS['cache_array']['surfbar']['salt'] = $salt;
937 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
940 // ... and now the validation code
941 $valCode = generateRandomCodde($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
942 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
945 // Hash it with md5() and salt it with the random string
946 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
948 // Finally encrypt it PGP-like and return it
949 $valHashedCode = generatePassString($hashedCode);
951 // Return hashed value
952 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
953 return $valHashedCode;
955 // Check validation code
956 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
958 $urlId = bigintval($urlId);
960 // Now generate the code again
961 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
963 // Return result of checking hashes and salts
964 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
965 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
966 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
968 // Lockdown the userid/id combination (reload lock)
969 function SURFBAR_LOCKDOWN_ID ($urlId) {
970 //* DEBUG: */ print "LOCK!");
971 ///* DEBUG: */ return;
972 // Just add it to the database
973 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (userid, url_id) VALUES (%s, %s)",
974 array($GLOBALS['userid'], bigintval($urlId)), __FUNCTION__, __LINE__);
976 // Remove the salt from database
977 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE url_id=%s AND userid=%s LIMIT 1",
978 array(bigintval($urlId), $GLOBALS['userid']), __FUNCTION__, __LINE__);
980 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
981 function SURFBAR_PAY_POINTS () {
982 // Remove it from the URL owner
983 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
984 if (SURFBAR_GET_USERID() > 0) {
985 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
988 // Book it to the user
989 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
990 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
992 // Updates the statistics of current URL/userid
993 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
998 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1000 // Do we have a limit?
1002 // Then count views_max down!
1003 $ADD .= ",views_max=views_max-1";
1007 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1008 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1010 // Update the stats entry
1011 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1012 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1014 // Was that update okay?
1015 if (SQL_AFFECTEDROWS() < 1) {
1016 // No, then insert entry
1017 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1018 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1021 // Update total/daily/weekly/monthly counter
1022 incrementConfigEntry('surfbar_total_counter');
1023 incrementConfigEntry('surfbar_daily_counter');
1024 incrementConfigEntry('surfbar_weekly_counter');
1025 incrementConfigEntry('surfbar_monthly_counter');
1027 // Update config as well
1028 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1030 // Update the salt for validation and statistics
1031 function SURFBAR_UPDATE_SALT_STATS () {
1032 // Update statistics record
1033 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1035 // Simply store the salt from cache away in database...
1036 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1037 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FUNCTION__, __LINE__);
1040 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1043 if (SQL_AFFECTEDROWS() < 1) {
1044 // Insert missing entry!
1045 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1046 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1050 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1052 // Return if the update was okay
1053 return (SQL_AFFECTEDROWS() == 1);
1055 // Check if the reload lock is active for given id
1056 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1057 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1059 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1060 FROM `{!_MYSQL_PREFIX!}_surfbar_locks`
1061 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1062 ORDER BY last_surfed ASC
1064 array($GLOBALS['userid'], bigintval($urlId)), __FUNCTION__, __LINE__
1068 list($cnt) = SQL_FETCHROW($result);
1071 SQL_FREERESULT($result);
1074 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1077 // Determine which user hash no more points left
1078 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1082 'points' => array(),
1083 'notified' => array(),
1086 // Do we have a current user id?
1087 if ((IS_MEMBER()) && ($limit == 0)) {
1088 // Then add this as well
1089 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1090 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1091 $UIDs['notified'][$GLOBALS['userid']] = 0;
1093 // Get all userid except logged in one
1094 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1095 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1096 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1097 ON u.userid=d.userid
1098 WHERE u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1100 ORDER BY u.userid ASC",
1101 array($GLOBALS['userid']), __FUNCTION__, __LINE__);
1104 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1105 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1106 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1107 ON u.userid=d.userid
1108 WHERE u.`status`='ACTIVE'
1110 ORDER BY u.userid ASC", __FUNCTION__, __LINE__);
1114 while ($content = SQL_FETCHARRAY($result)) {
1116 $points = GET_TOTAL_DATA($content['userid'], "user_points", "points") - GET_TOTAL_DATA($content['userid'], "user_data", "used_points");
1117 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']},points={$points}", false);
1119 // Shall we add this to ignore?
1120 if ($points <= $limit) {
1122 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']} has depleted points amount!", false);
1123 $UIDs['uid'][$content['userid']] = $content['userid'];
1124 $UIDs['points'][$content['userid']] = $points;
1125 $UIDs['notified'][$content['userid']] = $content['notified'];
1130 SQL_FREERESULT($result);
1133 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1138 // Determine how many users are Online in surfbar
1139 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1140 // Count all users in surfbar modue and return the value
1141 $result = SQL_QUERY_ESC("SELECT id
1142 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1143 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1145 array(getConfig('online_timeout')), __FUNCTION__, __LINE__);
1148 $cnt = SQL_NUMROWS($result);
1151 SQL_FREERESULT($result);
1156 // Determine waiting time for one URL
1157 function SURFBAR_DETERMINE_WAIT_TIME () {
1158 // Get fixed reload lock
1159 $fixed = SURFBAR_GET_FIXED_RELOAD();
1161 // Is the fixed reload time set?
1167 // Static time is default
1168 $time = getConfig('surfbar_static_time');
1170 // Which payment model do we have?
1171 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1172 // "Calculate" dynamic time
1173 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1179 // Changes the status of an URL from given to other
1180 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1181 // Make new status always lower-case
1182 $newStatus = strtolower($newStatus);
1184 // Get URL data for status comparison if missing
1185 if ((!is_array($data)) || (count($data) == 0)) {
1186 // Fetch missing URL data
1187 $data = SURFBAR_GET_URL_DATA($urlId);
1190 // Is the new status set?
1191 if ((!is_string($newStatus)) || (empty($newStatus))) {
1192 // Abort here, but fine!
1196 // Is the status like prevStatus is saying?
1197 if ($data[$urlId]['status'] != $prevStatus) {
1198 // No, then abort here
1203 // Update the status now
1204 // ---------- Comment out for debugging/developing member actions! ---------
1205 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE id=%s LIMIT 1",
1206 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1207 // ---------- Comment out for debugging/developing member actions! ---------
1210 //if (SQL_AFFECTEDROWS() != 1) {
1211 // // No, something went wrong
1215 // Prepare content for notification routines
1216 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1217 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1218 $data[$urlId]['reward'] = TRANSLATE_COMMA(getConfig('surfbar_static_reward'));
1219 $data[$urlId]['costs'] = TRANSLATE_COMMA(getConfig('surfbar_static_costs'));
1221 // Do some dirty fixing here:
1222 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1223 // Fix for template change
1224 $newStatus = "continued";
1227 // Send admin notification
1228 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1230 // Send user notification
1231 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1236 // Calculate minimum value for dynamic payment model
1237 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1238 // Addon is zero by default
1242 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1245 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1248 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1251 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1254 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1256 // Get user's total URLs
1257 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1260 if ($totalUrls > 0) {
1261 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1263 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1269 // Calculate maximum value for dynamic payment model
1270 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1271 // Addon is zero by default
1278 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1281 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1284 $addon += abs($max * $percent * $totalUsers);
1287 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1290 $addon += abs($max * $percent * $totalUrls);
1295 // Calculate dynamic lock
1296 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1297 // Default lock is 30 seconds
1301 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1304 $addon = abs(log($onlineUsers / $addon + 1));
1309 // "Getter" for lock ids array
1310 function SURFBAR_GET_LOCK_IDS () {
1311 // Prepare some arrays
1316 // Get all id from locks within the timestamp
1317 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1319 {!_MYSQL_PREFIX!}_surfbar_locks
1323 id ASC", array($GLOBALS['userid']),
1324 __FUNCTION__, __LINE__);
1327 while ($content = SQL_FETCHARRAY($result)) {
1329 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$content['id']},url={$content['url_id']},rest=".(time() - $last)."/".SURFBAR_GET_SURF_LOCK()."", false);
1331 // Skip entries that are too old
1332 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1334 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1336 // Add only if missing or bigger
1337 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $last)) {
1339 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1342 $IDs[$content['url_id']] = $last;
1343 $USE[$content['url_id']] = $content['id'];
1347 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1349 // Ignore these old entries!
1350 $ignored[] = $content['url_id'];
1351 unset($IDs[$content['url_id']]);
1352 unset($USE[$content['url_id']]);
1357 SQL_FREERESULT($result);
1362 // "Getter" for maximum random number
1363 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1364 // Count max availabe entries
1365 $result = SQL_QUERY("SELECT sbu.id AS cnt
1366 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1367 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1368 ON sbu.id=sbs.url_id
1369 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1371 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."
1372 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1375 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1378 $maxRand = SQL_NUMROWS($result);
1381 SQL_FREERESULT($result);
1386 // Load all URLs of the current user and return it as an array
1387 function SURFBAR_GET_USER_URLS () {
1392 $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
1393 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1394 WHERE u.userid=%s AND u.status != 'DELETED'
1396 array($GLOBALS['userid']), __FUNCTION__, __LINE__);
1398 // Are there entries?
1399 if (SQL_NUMROWS($result) > 0) {
1401 while ($row = SQL_FETCHARRAY($result)) {
1403 $URLs[$row['id']] = $row;
1408 SQL_FREERESULT($result);
1413 // "Getter" for member action array for given status
1414 function SURFBAR_GET_ACTION_ARRAY ($status) {
1416 $returnArray = array();
1418 // Get all assigned actions
1419 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1420 array($status), __FUNCTION__, __LINE__);
1422 // Some entries there?
1423 if (SQL_NUMROWS($result) > 0) {
1425 // @TODO This can be somehow rewritten
1426 while ($content = SQL_FETCHARRAY($result)) {
1427 $returnArray[] = $content['action'];
1432 SQL_FREERESULT($result);
1435 return $returnArray;
1437 // Reload to configured stop page
1438 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1439 // Internal or external?
1440 if ((getConfig('surfbar_pause_mode') == "INTERNAL") || (getConfig('surfbar_pause_url') == "")) {
1441 // Reload to internal page
1442 LOAD_URL("surfbar.php?frame=".$page);
1444 // Reload to external page
1445 LOAD_CONFIGURED_URL('surfbar_pause_url');
1449 // Determine next id for surfbar or get data for given id, always call this before you call other
1450 // getters below this function!!!
1451 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1452 // Default is no id and no random number
1458 // Get array with lock ids
1459 $USE = SURFBAR_GET_LOCK_IDS();
1461 // Shall we add some URL ids to ignore?
1463 if (count($USE) > 0) {
1465 $ADD = " AND sbu.id NOT IN (";
1466 foreach ($USE as $url_id => $lid) {
1468 $ADD .= $url_id.",";
1471 // Add closing bracket
1472 $ADD = substr($ADD, 0, -1) . ")";
1475 // Determine depleted user account
1476 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1478 // Get maximum randomness factor
1479 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1481 // If more than one URL can be called generate the random number!
1483 // Generate random number
1484 $randNum = mt_rand(0, ($maxRand - 1));
1487 // And query the database
1488 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1489 $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
1490 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1491 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1492 ON sbu.id=sbs.url_id
1493 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1495 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."
1497 ORDER BY l.last_surfed ASC, sbu.id ASC
1499 array($randNum), __FUNCTION__, __LINE__
1502 // Get data from specified id number
1503 $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
1504 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1505 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1506 ON sbu.id=sbs.url_id
1507 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1509 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))
1511 array($GLOBALS['userid'], bigintval($urlId)), __FUNCTION__, __LINE__
1515 // Is there an id number?
1516 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1517 if (SQL_NUMROWS($result) == 1) {
1519 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - BEFORE", false);
1520 $GLOBALS['cache_array']['surfbar'] = merge_array($GLOBALS['cache_array']['surfbar'], SQL_FETCHARRAY($result));
1521 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - AFTER", false);
1523 // Determine waiting time
1524 $GLOBALS['cache_array']['surfbar']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1526 // Is the last salt there?
1527 if (is_null($GLOBALS['cache_array']['surfbar']['last_salt'])) {
1528 // Then repair it wit the static!
1529 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1530 $GLOBALS['cache_array']['surfbar']['last_salt'] = "";
1533 // Fix missing last_surfed
1534 if ((!isset($GLOBALS['cache_array']['surfbar']['last_surfed'])) || (is_null($GLOBALS['cache_array']['surfbar']['last_surfed']))) {
1536 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1537 $GLOBALS['cache_array']['surfbar']['last_surfed'] = 0;
1540 // Get base/fixed reward and costs
1541 $GLOBALS['cache_array']['surfbar']['reward'] = SURFBAR_DETERMINE_REWARD();
1542 $GLOBALS['cache_array']['surfbar']['costs'] = SURFBAR_DETERMINE_COSTS();
1543 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1545 // Only in dynamic model add the dynamic bonus!
1546 if (getConfig('surfbar_pay_model') == "DYNAMIC") {
1547 // Calculate dynamic reward/costs and add it
1548 $GLOBALS['cache_array']['surfbar']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1549 $GLOBALS['cache_array']['surfbar']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1550 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1554 $nextId = SURFBAR_GET_ID();
1558 SQL_FREERESULT($result);
1561 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1564 // -----------------------------------------------------------------------------
1565 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1566 // THE $GLOBALS['cache_array']['surfbar'] ARRAY!
1567 // -----------------------------------------------------------------------------
1568 // Private getter for data elements
1569 function SURFBAR_GET_DATA ($element) {
1570 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1575 // Is the entry there?
1576 if (isset($GLOBALS['cache_array']['surfbar'][$element])) {
1578 $data = $GLOBALS['cache_array']['surfbar'][$element];
1579 } else { // END - if
1581 print_r($GLOBALS['cache_array']['surfbar']);
1587 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1590 // Getter for reward from cache
1591 function SURFBAR_GET_REWARD () {
1592 // Get data element and return its contents
1593 return SURFBAR_GET_DATA('reward');
1595 // Getter for costs from cache
1596 function SURFBAR_GET_COSTS () {
1597 // Get data element and return its contents
1598 return SURFBAR_GET_DATA('costs');
1600 // Getter for URL from cache
1601 function SURFBAR_GET_URL () {
1602 // Get data element and return its contents
1603 return SURFBAR_GET_DATA('url');
1605 // Getter for salt from cache
1606 function SURFBAR_GET_SALT () {
1607 // Get data element and return its contents
1608 return SURFBAR_GET_DATA('salt');
1610 // Getter for id from cache
1611 function SURFBAR_GET_ID () {
1612 // Get data element and return its contents
1613 return SURFBAR_GET_DATA('id');
1615 // Getter for userid from cache
1616 function SURFBAR_GET_USERID () {
1617 // Get data element and return its contents
1618 return SURFBAR_GET_DATA('userid');
1620 // Getter for user reload locks
1621 function SURFBAR_GET_USER_LOCKS () {
1622 // Get data element and return its contents
1623 return SURFBAR_GET_DATA('user_locks');
1625 // Getter for reload time
1626 function SURFBAR_GET_RELOAD_TIME () {
1627 // Get data element and return its contents
1628 return SURFBAR_GET_DATA('time');
1630 // Getter for allowed views
1631 function SURFBAR_GET_VIEWS_ALLOWED () {
1632 // Get data element and return its contents
1633 return SURFBAR_GET_DATA('views_allowed');
1635 // Getter for fixed reload
1636 function SURFBAR_GET_FIXED_RELOAD () {
1637 // Get data element and return its contents
1638 return SURFBAR_GET_DATA('fixed_reload');
1640 // Getter for surf lock
1641 function SURFBAR_GET_SURF_LOCK () {
1642 // Get data element and return its contents
1643 return SURFBAR_GET_DATA('surf_lock');