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) {
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
64 // Register the new URL
65 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", $limit);
67 // Admin unlocked an email so we can migrate the URL
68 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
73 } elseif (!VALIDATE_URL($url)) {
76 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
77 // URL already found in surfbar!
79 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
84 // Register the new URL
85 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
87 // Admin function for unlocking URLs
88 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
89 // Is this an admin or invalid array?
91 // Not admin or invalid IDs array
93 } elseif (!is_array($IDs)) {
96 } elseif (count($IDs) == 0) {
101 // Set to true to make AND expression valid if first URL got unlocked
104 // Update the status for all ids
105 foreach ($IDs as $id => $dummy) {
106 // Test all ids through (ignores failed)
107 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
110 // Return total status
113 // Admin function for rejecting URLs
114 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
115 // Is this an admin or invalid array?
117 // Not admin or invalid IDs array
119 } elseif (!is_array($IDs)) {
122 } elseif (count($IDs) == 0) {
127 // Set to true to make AND expression valid if first URL got unlocked
130 // Update the status for all ids
131 foreach ($IDs as $id => $dummy) {
132 // Test all ids through (ignores failed)
133 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
136 // Return total status
140 // -----------------------------------------------------------------------------
142 // -----------------------------------------------------------------------------
144 // Member has added an URL
145 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
148 // Do some pre-checks
152 } elseif (!VALIDATE_URL($url)) {
155 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
156 // URL already found in surfbar!
158 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
161 } elseif ("".($limit + 0)."" != "".$limit."") {
162 // Invalid amount entered
166 // Register the new URL
167 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", $limit);
169 // Create list of actions depending on status for the user
170 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
171 // Load all actions in an array for given status
172 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
175 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
179 $width = round(100 / count($actionArray));
181 // "Walk" through all actions and create forms
182 foreach ($actionArray as $actionId=>$action) {
183 // Add form for this action
184 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
185 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
186 <input type=\"hidden\" name=\"id\" value=\"%s\" />
187 <input type=\"hidden\" name=\"action\" value=\"%s\" />
188 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
206 // Do the member form request
207 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
208 global $SURFBAR_CACHE;
210 // By default no action is performed
217 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
218 // Important form elements are missing!
220 } elseif (!isset($URLs[$formData['id']])) {
221 // ID not found in cache
223 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
224 // Action not allowed for current URL status
229 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
232 if ($action != $formData['action']) {
233 // Invalid data in action found
237 // Create the function name for selected action
238 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
240 // Is the function there?
241 if (function_exists($functionName)) {
243 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
245 // Extract URL data for call-back
246 $urlData = array(array_merge($URLs[$formData['id']], array($action => $formData)));
248 // Action found so execute it
249 $performed = call_user_func_array($functionName, $urlData);
251 // Log invalid request
252 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
253 ADD_FATAL(sprintf("Invalid member action! action=%s,id=%s,function=%s", $formData['action'], $formData['id'], $functionName));
259 // Validate if the requested action can be performed on current URL status
260 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
261 global $SURFBAR_CACHE;
263 // Search for the requested action/status combination in database
264 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
265 array($action, $status), __FILE__, __LINE__);
267 // Is the entry there?
268 $isValid = (SQL_NUMROWS($result) == 1);
270 // Fetch the new status if found
273 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
277 SQL_FREERESULT($result);
283 // -----------------------------------------------------------------------------
285 // -----------------------------------------------------------------------------
287 // Retreat a booked URL
288 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
289 // Create the data array for next function call
291 $urlData['id'] => $urlData
294 // Simply change the status here
295 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
297 // Book an URL now (from migration)
298 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
299 // Create the data array for next function call
301 $urlData['id'] => $urlData
304 // Simply change the status here
305 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
307 // Show edit form or do the changes
308 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
309 // Is the "execute" flag there?
310 if (isset($urlData['edit']['execute'])) {
311 // Execute the changes
312 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
316 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
318 // Show delete form or do the changes
319 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
320 // Is the "execute" flag there?
321 if (isset($urlData['delete']['execute'])) {
322 // Execute the changes
323 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
327 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
329 // Pause active banner
330 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
331 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
333 // Unpause stopped banner
334 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
335 // Fix missing entry for template
336 $urlData['edit'] = $urlData['unpause'];
337 $urlData['edit']['url'] = $urlData['url'];
338 $urlData['edit']['limit'] = $urlData['views_max'];
340 // Return status change
341 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
343 // Resubmit locked URL
344 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
345 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
347 // Display selected "action form"
348 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
349 // Translate some data
350 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
351 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
352 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
353 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
354 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
356 // Is the lock reason empty?
357 if (empty($urlData['lock_reason'])) {
358 // Fix it to three dashes
359 $urlData['lock_reason'] = "---";
362 // Include fields only for action 'edit'
363 if ($action == "edit") {
364 // Default is not limited
365 $urlData['limited_yes'] = "";
366 $urlData['limited_no'] = " checked=\"checked\"";
367 $urlData['limited'] = "false";
369 // Is this URL limited?
370 if ($urlData['views_max'] > 0) {
371 // Then rewrite form data
372 $urlData['limited_yes'] = " checked=\"checked\"";
373 $urlData['limited_no'] = "";
374 $urlData['limited'] = "true";
378 // Load the form and display it
379 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
381 // All fine by default ... ;-)
384 // Execute choosen action
385 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
386 // By default nothing is executed
389 // Is limitation "no" and "limit" is > 0?
390 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
391 // Set it to unlimited
392 $urlData[$action]['limit'] = 0;
395 // Construct function name
396 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
398 // Is 'userid' set and not 'uid' ?
399 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
401 $urlData['uid'] = $urlData['userid'];
404 // Is that function there?
405 if (function_exists($functionName)) {
406 // Execute the function
407 if (call_user_func_array($functionName, array($urlData)) == true) {
408 // Update status as well
409 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
413 ADD_FATAL(sprintf(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName));
419 // "Execute edit" function: Update changed data
420 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
421 // Default is nothing done
424 // Translate URLs for testing
425 $url1 = COMPILE_CODE($urlData['url']);
426 $url2 = COMPILE_CODE($urlData['edit']['url']);
428 // Has the URL or limit changed?
430 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
432 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",
433 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
442 // "Execute delete" function: Does nothing...
443 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
444 // Nothing special to do (see above function for such "special actions" to perform)
448 // -----------------------------------------------------------------------------
449 // Self-maintenance functions
450 // -----------------------------------------------------------------------------
453 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
454 // Handle URLs which limit has depleted so we can stop them
455 SURFBAR_HANDLE_DEPLETED_VIEWS();
457 // Handle low-points amounts
458 SURFBAR_HANDLE_LOW_POINTS();
460 // Handle URLs which limit has depleted
461 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
463 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND status='ACTIVE'");
465 // Do we have some entries?
466 if (count($urlArray) > 0) {
468 foreach ($urlArray as $id => $urlData) {
472 // Rewrite array for next call
473 $urlData[$id] = $data;
476 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
480 // Alert users which have URLs booked and are low on points amount
481 function SURFBAR_HANDLE_LOW_POINTS () {
485 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS($_CONFIG['surfbar_warn_low_points']);
487 // "Walk" through all URLs
488 foreach ($UIDs['uid'] as $uid => $dummy) {
489 // Is the last notification far enougth away to notify again?
490 if ((time() - $UIDs['notified'][$uid]) >= $_CONFIG['surfbar_low_interval']) {
494 'low' => TRANSLATE_COMMA($_CONFIG['surfbar_warn_low_points']),
495 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
496 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
497 'interval' => CREATE_FANCY_TIME($_CONFIG['surfbar_low_interval'])
501 SURFBAR_NOTIFY_USER("low_points", $content);
503 // Update last notified
504 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
505 array($uid), __FILE__, __LINE__);
510 // -----------------------------------------------------------------------------
512 // -----------------------------------------------------------------------------
514 // Looks up by an URL
515 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
516 // Now lookup that given URL by itself
517 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
520 return (count($urlArray) > 0);
522 // Load URL data by given search term and column
523 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
526 // By default nothing is found
527 $lastUrlData = array();
529 // Is the column an id number?
530 if (($column == "id") || ($column == "userid")) {
531 // Extra secure input
532 $searchTerm = bigintval($searchTerm);
535 // If the column is "id" there can be only one entry
537 if ($column == "id") {
541 // Look up the record
542 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed
543 FROM "._MYSQL_PREFIX."_surfbar_urls
544 WHERE %s='%s'".$add."
547 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
549 // Is there at least one record?
550 if (SQL_NUMROWS($result) > 0) {
552 while ($dataRow = SQL_FETCHARRAY($result)) {
553 // Shall we group these results?
554 if ($group == "id") {
555 // Add the row by id as index
556 $lastUrlData[$dataRow['id']] = $dataRow;
559 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
565 SQL_FREERESULT($result);
570 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
571 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $limit=0) {
574 // Make sure by the user registered URLs are always pending
575 if ($addMode == "reg") $status = "PENDING";
580 'frametester' => FRAMETESTER($url),
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") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
600 // Notify admin even when he as unlocked an email
601 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
605 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
607 // Return the insert id
608 return $content['insert_id'];
610 // Inserts an url by given data array and return the insert id
611 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
613 $uid = bigintval($urlData['uid']);
616 if (empty($uid)) $uid = 0;
618 // Just run the insert query for now
619 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid,url,status,views_max,views_allowed) VALUES (%s,'%s','%s',%s,%s)",
626 ), __FILE__, __LINE__
630 return SQL_INSERTID();
632 // Notify admin(s) with a selected message and content
633 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
634 // Prepare template name
635 $templateName = sprintf("admin_surfbar_%s", $messageType);
637 // Set default subject if following eval() wents wrong
638 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
640 // Create constant name
641 $constantName = sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
642 strtoupper($messageType)
646 if (defined($constantName)) {
647 $subject = constant($constantName);
649 ADD_FATAL(ADMIN_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
652 // Translate some data if present
653 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
654 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
655 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
656 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
657 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
658 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
660 // Send the notification out
661 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);
673 // Set default subject if following eval() wents wrong
674 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
676 // Create constant name
677 $constantName = sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
678 strtoupper($messageType)
682 if (defined($constantName)) {
683 $subject = constant($constantName);
685 ADD_FATAL(MEMBER_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
688 // Translate some data if present
689 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
690 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
691 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
692 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
693 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
694 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
697 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
700 return SEND_EMAIL($content['uid'], $subject, $mailText);
702 // Translates the limit
703 function SURFBAR_TRANSLATE_LIMIT ($limit) {
707 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
710 $return = TRANSLATE_COMMA($limit);
716 // Translate the URL status
717 function SURFBAR_TRANSLATE_STATUS ($status) {
718 // Create constant name
719 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
721 // Set default translated status
722 $statusTranslated = "!".$constantName."!";
724 // Is the constant there?
725 if (defined($constantName)) {
726 // Then get it's value
727 $statusTranslated = constant($constantName);
731 return $statusTranslated;
734 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
737 // Static values are default
738 $reward = $_CONFIG['surfbar_static_reward'];
740 // Do we have static or dynamic?
741 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
742 // "Calculate" dynamic reward
744 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
746 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
754 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
757 // Static costs is default
758 $costs = $_CONFIG['surfbar_static_costs'];
760 // Do we have static or dynamic?
761 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
762 // "Calculate" dynamic costs
764 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
766 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
773 // "Calculate" dynamic add
774 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
775 // Get min/max values
776 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
777 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
779 // "Calculate" dynamic part and return it
780 return mt_rand($min, $max);
782 // Determine right template name
783 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
784 // Default is the frameset
785 $templateName = "surfbar_frameset";
787 // Any frame set? ;-)
788 if (isset($_GET['frame'])) {
789 // Use the frame as a template name part... ;-)
790 $templateName = sprintf("surfbar_frame_%s",
791 SQL_ESCAPE($_GET['frame'])
796 return $templateName;
798 // Check if the "reload lock" of the current user is full, call this function
799 // before you call SURFBAR_CHECK_RELOAD_LOCK().
800 function SURFBAR_CHECK_RELOAD_FULL() {
801 global $SURFBAR_CACHE, $_CONFIG;
806 // Cache static reload lock
807 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
808 //DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."", false);
810 // Do we have dynamic model?
811 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
812 // "Calculate" dynamic lock
813 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
817 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
818 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
820 array($GLOBALS['userid']), __FILE__, __LINE__
824 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
827 if (is_null($SURFBAR_CACHE['user_locks'])) {
828 // Then fix it to zero!
829 $SURFBAR_CACHE['user_locks'] = 0;
833 SQL_FREERESULT($result);
836 $total = SURFBAR_GET_TOTAL_URLS();
838 // Do we have some URLs in lock? Admins can always surf on own URLs!
839 //DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}", false);
840 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
845 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
846 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
847 // Determine depleted user account
848 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
850 // Is the exlude userid set?
851 if ($excludeUserId > 0) {
853 $UIDs['uid'][$excludeUserId] = $excludeUserId;
856 // Get amount from database
857 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
858 FROM "._MYSQL_PREFIX."_surfbar_urls
859 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
860 array($status), __FILE__, __LINE__
864 list($cnt) = SQL_FETCHROW($result);
867 SQL_FREERESULT($result);
872 // Check wether the user is allowed to book more URLs
873 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
876 // Is this admin and userid is zero or does the user has some URLs left to book?
877 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
879 // Get total amount of URLs of given status for current user
880 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
883 // Is the user 0 and user is logged in?
884 if (($uid == 0) && (IS_MEMBER())) {
885 // Then use this userid
886 $uid = $GLOBALS['userid'];
887 } elseif ($uid == 0) {
889 return ($_CONFIG['surfbar_max_order'] + 1);
892 // Default is all URLs
895 // Is the status set?
896 if (is_array($status)) {
897 // Only URLs with these status
898 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
899 } elseif (!empty($status)) {
900 // Only URLs with this status
901 $ADD = sprintf(" AND status='%s'", $status);
902 } elseif (is_array($exclude)) {
903 // Exclude URLs with these status
904 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
905 } elseif (!empty($exclude)) {
906 // Exclude URLs with this status
907 $ADD = sprintf(" AND status != '%s'", $exclude);
910 // Get amount from database
911 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
912 FROM "._MYSQL_PREFIX."_surfbar_urls
913 WHERE userid=%s".$ADD."
915 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
919 list($cnt) = SQL_FETCHROW($result);
922 SQL_FREERESULT($result);
927 // Generate a validation code for the given id number
928 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
929 global $_CONFIG, $SURFBAR_CACHE;
931 // @TODO Invalid salt should be refused
932 $SURFBAR_CACHE['salt'] = "INVALID";
934 // Get code length from config
935 $length = $_CONFIG['code_length'];
938 if ($length == 0) $length = 10;
940 // Generate a code until the length matches
942 while (strlen($valCode) != $length) {
945 // Generate random hashed string
946 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
947 //DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
950 $SURFBAR_CACHE['salt'] = $salt;
951 //DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
954 // ... and now the validation code
955 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
956 //DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
959 // Hash it with md5() and salt it with the random string
960 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
962 // Finally encrypt it PGP-like and return it
963 $valHashedCode = generatePassString($hashedCode);
965 // Return hashed value
966 //DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
967 return $valHashedCode;
969 // Check validation code
970 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
971 global $SURFBAR_CACHE;
974 $urlId = bigintval($urlId);
976 // Now generate the code again
977 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
979 // Return result of checking hashes and salts
980 //DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
981 //DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
982 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
984 // Lockdown the userid/id combination (reload lock)
985 function SURFBAR_LOCKDOWN_ID ($urlId) {
986 //* DEBUG: */ print "LOCK!");
987 ///* DEBUG: */ return;
988 // Just add it to the database
989 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES (%s, %s)",
990 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
992 // Remove the salt from database
993 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
994 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
996 // Pay points to the user and remove it from the sender
997 function SURFBAR_PAY_POINTS ($urlId) {
998 // Remove it from the URL owner
999 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1000 if (SURFBAR_GET_USERID() > 0) {
1001 SUB_POINTS("surfbar", SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1004 // Book it to the user
1005 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
1006 ADD_POINTS_REFSYSTEM("surfbar", $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
1008 // Updates the statistics of current URL/userid
1009 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1015 // Get allowed views
1016 $allowed = SURFBAR_GET_ALLOWED_VIEWS();
1018 // Do we have a limit?
1020 // Then count views_max down!
1021 $ADD .= ",views_max=views_max-1";
1025 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1026 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1028 // Update the stats entry
1029 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1030 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1032 // Was that update okay?
1033 if (SQL_AFFECTEDROWS() < 1) {
1034 // No, then insert entry
1035 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES (%s,%s,1)",
1036 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1039 // Update total/daily/weekly/monthly counter
1040 $_CONFIG['surfbar_total_counter']++;
1041 $_CONFIG['surfbar_daily_counter']++;
1042 $_CONFIG['surfbar_weekly_counter']++;
1043 $_CONFIG['surfbar_monthly_counter']++;
1045 // Update config as well
1046 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1048 // Update the salt for validation and statistics
1049 function SURFBAR_UPDATE_SALT_STATS () {
1050 // Update statistics record
1051 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1053 // Simply store the salt from cache away in database...
1054 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1055 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1058 //DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1061 if (SQL_AFFECTEDROWS() < 1) {
1062 // Insert missing entry!
1063 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1064 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1068 //DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1070 // Return if the update was okay
1071 return (SQL_AFFECTEDROWS() == 1);
1073 // Check if the reload lock is active for given id
1074 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1075 //DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1077 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1078 FROM "._MYSQL_PREFIX."_surfbar_locks
1079 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
1080 ORDER BY last_surfed ASC
1082 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1086 list($cnt) = SQL_FETCHROW($result);
1089 SQL_FREERESULT($result);
1092 //DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."", false);
1095 // Determine which user hash no more points left
1096 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1100 'points' => array(),
1101 'notified' => array(),
1104 // Do we have a current user id?
1105 if ((IS_MEMBER()) && ($limit == 0)) {
1106 // Then add this as well
1107 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1108 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1109 $UIDs['notified'][$GLOBALS['userid']] = 0;
1111 // Get all userid except logged in one
1112 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1113 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1114 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1115 ON u.userid=d.userid
1116 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
1118 ORDER BY u.userid ASC",
1119 array($GLOBALS['userid']), __FILE__, __LINE__);
1122 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1123 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1124 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1125 ON u.userid=d.userid
1126 WHERE u.status='ACTIVE'
1128 ORDER BY u.userid ASC", __FILE__, __LINE__);
1132 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1134 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1135 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1137 // Shall we add this to ignore?
1138 if ($points <= $limit) {
1140 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1141 $UIDs['uid'][$uid] = $uid;
1142 $UIDs['points'][$uid] = $points;
1143 $UIDs['notified'][$uid] = $notified;
1148 SQL_FREERESULT($result);
1151 //DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1156 // Determine how many users are Online in surfbar
1157 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1160 // Count all users in surfbar modue and return the value
1161 $result = SQL_QUERY_ESC("SELECT id
1162 FROM "._MYSQL_PREFIX."_surfbar_stats
1163 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1165 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
1168 $cnt = SQL_NUMROWS($result);
1171 SQL_FREERESULT($result);
1176 // Determine waiting time for one URL
1177 function SURFBAR_DETERMINE_WAIT_TIME () {
1180 // Static time is default
1181 $time = $_CONFIG['surfbar_static_time'];
1183 // Which payment model do we have?
1184 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1185 // "Calculate" dynamic time
1186 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1192 // Changes the status of an URL from given to other
1193 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1196 // Make new status always lower-case
1197 $newStatus = strtolower($newStatus);
1199 // Get URL data for status comparison if missing
1200 if ((!is_array($data)) || (count($data) == 0)) {
1201 // Fetch missing URL data
1202 $data = SURFBAR_GET_URL_DATA($urlId);
1205 // Is the new status set?
1206 if ((!is_string($newStatus)) || (empty($newStatus))) {
1207 // Abort here, but fine!
1211 // Is the status like prevStatus is saying?
1212 if ($data[$urlId]['status'] != $prevStatus) {
1213 // No, then abort here
1218 // Update the status now
1219 // ---------- Comment out for debugging/developing member actions! ---------
1220 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1221 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1222 // ---------- Comment out for debugging/developing member actions! ---------
1225 //if (SQL_AFFECTEDROWS() != 1) {
1226 // // No, something went wrong
1230 // Prepare content for notification routines
1231 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1232 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1233 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
1234 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
1236 // Do some dirt fixing here:
1237 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1238 // Fix for template change
1239 $newStatus = "continued";
1242 // Send admin notification
1243 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1245 // Send user notification
1246 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1251 // Calculate minimum value for dynamic payment model
1252 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1255 // Addon is zero by default
1259 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1262 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1265 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1268 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1271 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1273 // Get user's total URLs
1274 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1277 if ($totalUrls > 0) {
1278 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1280 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1286 // Calculate maximum value for dynamic payment model
1287 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1290 // Addon is zero by default
1297 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1300 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1303 $addon += abs($max * $percent * $totalUsers);
1306 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1309 $addon += abs($max * $percent * $totalUrls);
1314 // Calculate dynamic lock
1315 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1318 // Default lock is 30 seconds
1322 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1325 $addon = abs(log($onlineUsers / $addon + 1));
1330 // "Getter" for lock ids array
1331 function SURFBAR_GET_LOCK_IDS () {
1332 // Prepare some arrays
1337 // Get all id from locks within the timestamp
1338 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1340 "._MYSQL_PREFIX."_surfbar_locks
1344 id ASC", array($GLOBALS['userid']),
1345 __FILE__, __LINE__);
1348 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1350 //DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."", false);
1352 // Skip entries that are too old
1353 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1355 //DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1357 // Add only if missing or bigger
1358 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1360 //DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1368 //DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1370 // Ignore these old entries!
1378 SQL_FREERESULT($result);
1383 // "Getter" for maximum random number
1384 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1386 // Count max availabe entries
1387 $result = SQL_QUERY("SELECT sbu.id AS cnt
1388 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1389 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1390 ON sbu.id=sbs.url_id
1391 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1393 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."
1394 GROUP BY sbu.id", __FILE__, __LINE__);
1397 //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1400 $maxRand = SQL_NUMROWS($result);
1403 SQL_FREERESULT($result);
1408 // Load all URLs of the current user and return it as an array
1409 function SURFBAR_GET_USER_URLS () {
1414 $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
1415 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1416 WHERE u.userid=%s AND u.status != 'DELETED'
1418 array($GLOBALS['userid']), __FILE__, __LINE__);
1420 // Are there entries?
1421 if (SQL_NUMROWS($result) > 0) {
1423 while ($row = SQL_FETCHARRAY($result)) {
1425 $URLs[$row['id']] = $row;
1430 SQL_FREERESULT($result);
1435 // "Getter" for member action array for given status
1436 function SURFBAR_GET_ACTION_ARRAY ($status) {
1438 $returnArray = array();
1440 // Get all assigned actions
1441 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1442 array($status), __FILE__, __LINE__);
1444 // Some entries there?
1445 if (SQL_NUMROWS($result) > 0) {
1447 while (list($action) = SQL_FETCHROW($result)) {
1448 $returnArray[] = $action;
1453 SQL_FREERESULT($result);
1456 return $returnArray;
1458 // Reload to configured stop page
1459 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1462 // Internal or external?
1463 if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1464 // Reload to internal page
1465 LOAD_URL("surfbar.php?frame=".$page);
1467 // Reload to external page
1468 LOAD_URL($_CONFIG['surfbar_pause_url']);
1472 // Determine next id for surfbar or get data for given id, always call this before you call other
1473 // getters below this function!!!
1474 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1475 global $SURFBAR_CACHE, $_CONFIG;
1477 // Default is no id and no random number
1483 // Get array with lock ids
1484 $USE = SURFBAR_GET_LOCK_IDS();
1486 // Shall we add some URL ids to ignore?
1488 if (count($USE) > 0) {
1490 $ADD = " AND sbu.id NOT IN (";
1491 foreach ($USE as $url_id => $lid) {
1493 $ADD .= $url_id.",";
1496 // Add closing bracket
1497 $ADD = substr($ADD, 0, -1) . ")";
1500 // Determine depleted user account
1501 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1503 // Get maximum randomness factor
1504 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1506 // If more than one URL can be called generate the random number!
1508 // Generate random number
1509 $randNum = mt_rand(0, ($maxRand - 1));
1512 // And query the database
1513 //DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."", false);
1514 $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
1515 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1516 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1517 ON sbu.id=sbs.url_id
1518 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1520 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."
1522 ORDER BY l.last_surfed ASC, sbu.id ASC
1524 array($randNum), __FILE__, __LINE__
1527 // Get data from specified id number
1528 $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
1529 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1530 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1531 ON sbu.id=sbs.url_id
1532 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1534 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))
1536 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1540 // Is there an id number?
1541 //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1542 if (SQL_NUMROWS($result) == 1) {
1544 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1545 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1546 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1548 // Determine waiting time
1549 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1551 // Is the last salt there?
1552 if (is_null($SURFBAR_CACHE['last_salt'])) {
1553 // Then repair it wit the static!
1554 //DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1555 $SURFBAR_CACHE['last_salt'] = "";
1558 // Fix missing last_surfed
1559 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1561 //DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1562 $SURFBAR_CACHE['last_surfed'] = 0;
1565 // Get base/fixed reward and costs
1566 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1567 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1568 //DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1570 // Only in dynamic model add the dynamic bonus!
1571 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1572 // Calculate dynamic reward/costs and add it
1573 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1574 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1575 //DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1579 $nextId = SURFBAR_GET_ID();
1583 SQL_FREERESULT($result);
1586 //DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1589 // -----------------------------------------------------------------------------
1590 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1591 // $SURFBAR_CACHE ARRAY!
1592 // -----------------------------------------------------------------------------
1593 // Private getter for data elements
1594 function SURFBAR_GET_DATA ($element) {
1595 global $SURFBAR_CACHE;
1596 //DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1601 // Is the entry there?
1602 if (isset($SURFBAR_CACHE[$element])) {
1604 $data = $SURFBAR_CACHE[$element];
1605 } else { // END - if
1607 print_r($SURFBAR_CACHE);
1608 debug_print_backtrace();
1613 //DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1616 // Getter for reward from cache
1617 function SURFBAR_GET_REWARD () {
1618 // Get data element and return its contents
1619 return SURFBAR_GET_DATA('reward');
1621 // Getter for costs from cache
1622 function SURFBAR_GET_COSTS () {
1623 // Get data element and return its contents
1624 return SURFBAR_GET_DATA('costs');
1626 // Getter for URL from cache
1627 function SURFBAR_GET_URL () {
1628 // Get data element and return its contents
1629 return SURFBAR_GET_DATA('url');
1631 // Getter for salt from cache
1632 function SURFBAR_GET_SALT () {
1633 // Get data element and return its contents
1634 return SURFBAR_GET_DATA('salt');
1636 // Getter for id from cache
1637 function SURFBAR_GET_ID () {
1638 // Get data element and return its contents
1639 return SURFBAR_GET_DATA('id');
1641 // Getter for userid from cache
1642 function SURFBAR_GET_USERID () {
1643 // Get data element and return its contents
1644 return SURFBAR_GET_DATA('userid');
1646 // Getter for user reload locks
1647 function SURFBAR_GET_USER_RELOAD_LOCK () {
1648 // Get data element and return its contents
1649 return SURFBAR_GET_DATA('user_locks');
1651 // Getter for reload time
1652 function SURFBAR_GET_RELOAD_TIME () {
1653 // Get data element and return its contents
1654 return SURFBAR_GET_DATA('time');
1656 // Getter for allowed views
1657 function SURFBAR_GET_ALLOWED_VIEWS () {
1658 // Get data element and return its contents
1659 return SURFBAR_GET_DATA('views_allowed');