2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2008 *
4 * =============== Last change: 08/31/2008 *
6 * -------------------------------------------------------------------- *
7 * File : surfbar_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for surfbar *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die Surfbar *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
40 // -----------------------------------------------------------------------------
42 // -----------------------------------------------------------------------------
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
50 } elseif (!VALIDATE_URL($url)) {
53 } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54 // URL already found in surfbar!
56 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
59 } elseif ("".($limit + 0)."" != "".$limit."") {
60 // Invalid amount entered
62 } elseif ("".($reload + 0)."" != "".$reload."") {
63 // Invalid amount entered
67 // Register the new URL
68 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", array('limit' => $limit, 'reload' => $reload));
70 // Admin unlocked an email so we can migrate the URL
71 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
76 } elseif (!VALIDATE_URL($url)) {
79 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
80 // URL already found in surfbar!
82 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
87 // Register the new URL
88 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
90 // Admin function for unlocking URLs
91 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
92 // Is this an admin or invalid array?
94 // Not admin or invalid IDs array
96 } elseif (!is_array($IDs)) {
99 } elseif (count($IDs) == 0) {
104 // Set to true to make AND expression valid if first URL got unlocked
107 // Update the status for all ids
108 foreach ($IDs as $id => $dummy) {
109 // Test all ids through (ignores failed)
110 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
113 // Return total status
116 // Admin function for rejecting URLs
117 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
118 // Is this an admin or invalid array?
120 // Not admin or invalid IDs array
122 } elseif (!is_array($IDs)) {
125 } elseif (count($IDs) == 0) {
130 // Set to true to make AND expression valid if first URL got unlocked
133 // Update the status for all ids
134 foreach ($IDs as $id => $dummy) {
135 // Test all ids through (ignores failed)
136 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
139 // Return total status
143 // -----------------------------------------------------------------------------
145 // -----------------------------------------------------------------------------
147 // Member has added an URL
148 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
151 // Do some pre-checks
155 } elseif (!VALIDATE_URL($url)) {
158 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
159 // URL already found in surfbar!
161 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
164 } elseif ("".($limit + 0)."" != "".$limit."") {
165 // Invalid amount entered
169 // Register the new URL
170 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", array('limit' => $limit));
172 // Create list of actions depending on status for the user
173 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
174 // Load all actions in an array for given status
175 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
178 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
182 $width = round(100 / count($actionArray));
184 // "Walk" through all actions and create forms
185 foreach ($actionArray as $actionId=>$action) {
186 // Add form for this action
187 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
188 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
189 <input type=\"hidden\" name=\"id\" value=\"%s\" />
190 <input type=\"hidden\" name=\"action\" value=\"%s\" />
191 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
209 // Do the member form request
210 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
211 global $SURFBAR_CACHE;
213 // By default no action is performed
220 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
221 // Important form elements are missing!
223 } elseif (!isset($URLs[$formData['id']])) {
224 // ID not found in cache
226 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
227 // Action not allowed for current URL status
232 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
235 if ($action != $formData['action']) {
236 // Invalid data in action found
240 // Create the function name for selected action
241 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
243 // Is the function there?
244 if (function_exists($functionName)) {
246 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
248 // Extract URL data for call-back
249 $urlData = array(array_merge($URLs[$formData['id']], array($action => $formData)));
251 // Action found so execute it
252 $performed = call_user_func_array($functionName, $urlData);
254 // Log invalid request
255 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
256 ADD_FATAL(sprintf("Invalid member action! action=%s,id=%s,function=%s", $formData['action'], $formData['id'], $functionName));
262 // Validate if the requested action can be performed on current URL status
263 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
264 global $SURFBAR_CACHE;
266 // Search for the requested action/status combination in database
267 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
268 array($action, $status), __FILE__, __LINE__);
270 // Is the entry there?
271 $isValid = (SQL_NUMROWS($result) == 1);
273 // Fetch the new status if found
276 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
280 SQL_FREERESULT($result);
286 // -----------------------------------------------------------------------------
288 // -----------------------------------------------------------------------------
290 // Retreat a booked URL
291 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
292 // Create the data array for next function call
294 $urlData['id'] => $urlData
297 // Simply change the status here
298 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
300 // Book an URL now (from migration)
301 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
302 // Create the data array for next function call
304 $urlData['id'] => $urlData
307 // Simply change the status here
308 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
310 // Show edit form or do the changes
311 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
312 // Is the "execute" flag there?
313 if (isset($urlData['edit']['execute'])) {
314 // Execute the changes
315 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
319 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
321 // Show delete form or do the changes
322 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
323 // Is the "execute" flag there?
324 if (isset($urlData['delete']['execute'])) {
325 // Execute the changes
326 return SURFBAR_MEMBER_EXECUTE_ACTION("delete", $urlData);
330 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("delete", $urlData);
332 // Pause active banner
333 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
334 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
336 // Unpause stopped banner
337 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
338 // Fix missing entry for template
339 $urlData['edit'] = $urlData['unpause'];
340 $urlData['edit']['url'] = $urlData['url'];
341 $urlData['edit']['limit'] = $urlData['views_max'];
343 // Return status change
344 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
346 // Resubmit locked URL
347 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
348 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
350 // Display selected "action form"
351 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
352 // Translate some data
353 $urlData['registered'] = MAKE_DATETIME($urlData['registered'], "2");
354 $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
355 $urlData['views_max'] = TRANSLATE_COMMA($urlData['views_max']);
356 $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
357 $urlData['last_locked'] = MAKE_DATETIME($urlData['last_locked'], "2");
359 // Is the lock reason empty?
360 if (empty($urlData['lock_reason'])) {
361 // Fix it to three dashes
362 $urlData['lock_reason'] = "---";
365 // Include fields only for action 'edit'
366 if ($action == "edit") {
367 // Default is not limited
368 $urlData['limited_yes'] = "";
369 $urlData['limited_no'] = " checked=\"checked\"";
370 $urlData['limited'] = "false";
372 // Is this URL limited?
373 if ($urlData['views_max'] > 0) {
374 // Then rewrite form data
375 $urlData['limited_yes'] = " checked=\"checked\"";
376 $urlData['limited_no'] = "";
377 $urlData['limited'] = "true";
381 // Load the form and display it
382 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
384 // All fine by default ... ;-)
387 // Execute choosen action
388 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
389 // By default nothing is executed
392 // Is limitation "no" and "limit" is > 0?
393 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == "N") && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
394 // Set it to unlimited
395 $urlData[$action]['limit'] = 0;
398 // Construct function name
399 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
401 // Is 'userid' set and not 'uid' ?
402 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
404 $urlData['uid'] = $urlData['userid'];
407 // Is that function there?
408 if (function_exists($functionName)) {
409 // Execute the function
410 if (call_user_func_array($functionName, array($urlData)) == true) {
411 // Update status as well
412 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
416 ADD_FATAL(sprintf(MEMBER_SURFBAR_EXECUTE_ACTION_404, $functionName));
422 // "Execute edit" function: Update changed data
423 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
424 // Default is nothing done
427 // Translate URLs for testing
428 $url1 = COMPILE_CODE($urlData['url']);
429 $url2 = COMPILE_CODE($urlData['edit']['url']);
431 // Has the URL or limit changed?
433 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
435 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",
436 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FILE__, __LINE__);
445 // "Execute delete" function: Does nothing...
446 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
447 // Nothing special to do (see above function for such "special actions" to perform)
451 // -----------------------------------------------------------------------------
452 // Self-maintenance functions
453 // -----------------------------------------------------------------------------
456 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
457 // Handle URLs which limit has depleted so we can stop them
458 SURFBAR_HANDLE_DEPLETED_VIEWS();
460 // Handle low-points amounts
461 SURFBAR_HANDLE_LOW_POINTS();
463 // Handle URLs which limit has depleted
464 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
466 $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND status='ACTIVE'");
468 // Do we have some entries?
469 if (count($urlArray) > 0) {
471 foreach ($urlArray as $id => $urlData) {
475 // Rewrite array for next call
476 $urlData[$id] = $data;
479 SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
483 // Alert users which have URLs booked and are low on points amount
484 function SURFBAR_HANDLE_LOW_POINTS () {
488 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS($_CONFIG['surfbar_warn_low_points']);
490 // "Walk" through all URLs
491 foreach ($UIDs['uid'] as $uid => $dummy) {
492 // Is the last notification far enougth away to notify again?
493 if ((time() - $UIDs['notified'][$uid]) >= $_CONFIG['surfbar_low_interval']) {
497 'low' => TRANSLATE_COMMA($_CONFIG['surfbar_warn_low_points']),
498 'points' => TRANSLATE_COMMA($UIDs['points'][$uid]),
499 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
500 'interval' => CREATE_FANCY_TIME($_CONFIG['surfbar_low_interval'])
504 SURFBAR_NOTIFY_USER("low_points", $content);
506 // Update last notified
507 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
508 array($uid), __FILE__, __LINE__);
513 // -----------------------------------------------------------------------------
515 // -----------------------------------------------------------------------------
517 // Looks up by an URL
518 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
519 // Now lookup that given URL by itself
520 $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
523 return (count($urlArray) > 0);
525 // Load URL data by given search term and column
526 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
529 // By default nothing is found
530 $lastUrlData = array();
532 // Is the column an id number?
533 if (($column == "id") || ($column == "userid")) {
534 // Extra secure input
535 $searchTerm = bigintval($searchTerm);
538 // If the column is "id" there can be only one entry
540 if ($column == "id") {
544 // Look up the record
545 $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
546 FROM "._MYSQL_PREFIX."_surfbar_urls
547 WHERE %s='%s'".$add."
550 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
552 // Is there at least one record?
553 if (SQL_NUMROWS($result) > 0) {
555 while ($dataRow = SQL_FETCHARRAY($result)) {
556 // Shall we group these results?
557 if ($group == "id") {
558 // Add the row by id as index
559 $lastUrlData[$dataRow['id']] = $dataRow;
562 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
568 SQL_FREERESULT($result);
573 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
574 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
577 // Make sure by the user registered URLs are always pending
578 if ($addMode == "reg") $status = "PENDING";
581 $content = array_merge($extraFields, array(
583 'frametester' => FRAMETESTER($url),
588 // Is limit/reload set?
589 if (!isset($config['limit'])) $content['limit'] = 0;
590 if (!isset($config['reload'])) $content['reload'] = 0;
592 // Insert the URL into database
593 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
596 if ($content['insert_id'] == 0) {
597 // INSERT did not insert any data!
601 // Translate status and limit
602 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
604 // If in reg-mode we notify admin
605 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
606 // Notify admin even when he as unlocked an email
607 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
611 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
613 // Return the insert id
614 return $content['insert_id'];
616 // Inserts an url by given data array and return the insert id
617 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
619 $uid = bigintval($urlData['uid']);
622 if (empty($uid)) $uid = 0;
624 // Just run the insert query for now
625 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)",
633 ), __FILE__, __LINE__
637 return SQL_INSERTID();
639 // Notify admin(s) with a selected message and content
640 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
641 // Prepare template name
642 $templateName = sprintf("admin_surfbar_%s", $messageType);
644 // Set default subject if following eval() wents wrong
645 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
647 // Create constant name
648 $constantName = sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
649 strtoupper($messageType)
653 if (defined($constantName)) {
654 $subject = constant($constantName);
656 ADD_FATAL(ADMIN_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
659 // Translate some data if present
660 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
661 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
662 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
663 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
664 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
665 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
667 // Send the notification out
668 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
670 // Notify the user about the performed action
671 function SURFBAR_NOTIFY_USER ($messageType, $content) {
672 // Skip notification if userid is zero
673 if ($content['uid'] == 0) {
677 // Prepare template name
678 $templateName = sprintf("member_surfbar_%s", $messageType);
680 // Set default subject if following eval() wents wrong
681 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
683 // Create constant name
684 $constantName = sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
685 strtoupper($messageType)
689 if (defined($constantName)) {
690 $subject = constant($constantName);
692 ADD_FATAL(MEMBER_SURFBAR_NOTIFY_SUBJECT_404, $constantName);
695 // Translate some data if present
696 if (isset($content['status'])) $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
697 if (isset($content['registered'])) $content['registered'] = MAKE_DATETIME($content['registered'], "2");
698 if (isset($content['last_locked'])) $content['last_locked'] = MAKE_DATETIME($content['last_locked'], "2");
699 if (isset($content['views_total'])) $content['views_total'] = TRANSLATE_COMMA($content['views_total']);
700 if (isset($content['views_allowed'])) $content['views_allowed'] = TRANSLATE_COMMA($content['views_allowed']);
701 if (isset($content['views_max'])) $content['views_max'] = TRANSLATE_COMMA($content['views_max']);
704 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
707 return SEND_EMAIL($content['uid'], $subject, $mailText);
709 // Translates the limit
710 function SURFBAR_TRANSLATE_LIMIT ($limit) {
714 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
717 $return = TRANSLATE_COMMA($limit);
723 // Translate the URL status
724 function SURFBAR_TRANSLATE_STATUS ($status) {
725 // Create constant name
726 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
728 // Set default translated status
729 $statusTranslated = "!".$constantName."!";
731 // Is the constant there?
732 if (defined($constantName)) {
733 // Then get it's value
734 $statusTranslated = constant($constantName);
738 return $statusTranslated;
741 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
744 // Static values are default
745 $reward = $_CONFIG['surfbar_static_reward'];
747 // Do we have static or dynamic?
748 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
749 // "Calculate" dynamic reward
751 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
753 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
761 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
764 // Static costs is default
765 $costs = $_CONFIG['surfbar_static_costs'];
767 // Do we have static or dynamic?
768 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
769 // "Calculate" dynamic costs
771 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
773 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
780 // "Calculate" dynamic add
781 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
782 // Get min/max values
783 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
784 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
786 // "Calculate" dynamic part and return it
787 return mt_rand($min, $max);
789 // Determine right template name
790 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
791 // Default is the frameset
792 $templateName = "surfbar_frameset";
794 // Any frame set? ;-)
795 if (isset($_GET['frame'])) {
796 // Use the frame as a template name part... ;-)
797 $templateName = sprintf("surfbar_frame_%s",
798 SQL_ESCAPE($_GET['frame'])
803 return $templateName;
805 // Check if the "reload lock" of the current user is full, call this function
806 // before you call SURFBAR_CHECK_RELOAD_LOCK().
807 function SURFBAR_CHECK_RELOAD_FULL() {
808 global $SURFBAR_CACHE, $_CONFIG;
813 // Cache static reload lock
814 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
815 //DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."", false);
817 // Do we have dynamic model?
818 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
819 // "Calculate" dynamic lock
820 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
824 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
825 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
827 array($GLOBALS['userid']), __FILE__, __LINE__
831 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
834 if (is_null($SURFBAR_CACHE['user_locks'])) {
835 // Then fix it to zero!
836 $SURFBAR_CACHE['user_locks'] = 0;
840 SQL_FREERESULT($result);
843 $total = SURFBAR_GET_TOTAL_URLS();
845 // Do we have some URLs in lock? Admins can always surf on own URLs!
846 //DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}", false);
847 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
852 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
853 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
854 // Determine depleted user account
855 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
857 // Is the exlude userid set?
858 if ($excludeUserId > 0) {
860 $UIDs['uid'][$excludeUserId] = $excludeUserId;
863 // Get amount from database
864 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
865 FROM "._MYSQL_PREFIX."_surfbar_urls
866 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
867 array($status), __FILE__, __LINE__
871 list($cnt) = SQL_FETCHROW($result);
874 SQL_FREERESULT($result);
879 // Check wether the user is allowed to book more URLs
880 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
883 // Is this admin and userid is zero or does the user has some URLs left to book?
884 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
886 // Get total amount of URLs of given status for current user
887 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
890 // Is the user 0 and user is logged in?
891 if (($uid == 0) && (IS_MEMBER())) {
892 // Then use this userid
893 $uid = $GLOBALS['userid'];
894 } elseif ($uid == 0) {
896 return ($_CONFIG['surfbar_max_order'] + 1);
899 // Default is all URLs
902 // Is the status set?
903 if (is_array($status)) {
904 // Only URLs with these status
905 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
906 } elseif (!empty($status)) {
907 // Only URLs with this status
908 $ADD = sprintf(" AND status='%s'", $status);
909 } elseif (is_array($exclude)) {
910 // Exclude URLs with these status
911 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
912 } elseif (!empty($exclude)) {
913 // Exclude URLs with this status
914 $ADD = sprintf(" AND status != '%s'", $exclude);
917 // Get amount from database
918 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
919 FROM "._MYSQL_PREFIX."_surfbar_urls
920 WHERE userid=%s".$ADD."
922 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
926 list($cnt) = SQL_FETCHROW($result);
929 SQL_FREERESULT($result);
934 // Generate a validation code for the given id number
935 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
936 global $_CONFIG, $SURFBAR_CACHE;
938 // @TODO Invalid salt should be refused
939 $SURFBAR_CACHE['salt'] = "INVALID";
941 // Get code length from config
942 $length = $_CONFIG['code_length'];
945 if ($length == 0) $length = 10;
947 // Generate a code until the length matches
949 while (strlen($valCode) != $length) {
952 // Generate random hashed string
953 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
954 //DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
957 $SURFBAR_CACHE['salt'] = $salt;
958 //DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
961 // ... and now the validation code
962 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
963 //DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
966 // Hash it with md5() and salt it with the random string
967 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
969 // Finally encrypt it PGP-like and return it
970 $valHashedCode = generatePassString($hashedCode);
972 // Return hashed value
973 //DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
974 return $valHashedCode;
976 // Check validation code
977 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
978 global $SURFBAR_CACHE;
981 $urlId = bigintval($urlId);
983 // Now generate the code again
984 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
986 // Return result of checking hashes and salts
987 //DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
988 //DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
989 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
991 // Lockdown the userid/id combination (reload lock)
992 function SURFBAR_LOCKDOWN_ID ($urlId) {
993 //* DEBUG: */ print "LOCK!");
994 ///* DEBUG: */ return;
995 // Just add it to the database
996 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES (%s, %s)",
997 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
999 // Remove the salt from database
1000 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
1001 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
1003 // Pay points to the user and remove it from the sender
1004 function SURFBAR_PAY_POINTS ($urlId) {
1005 // Remove it from the URL owner
1006 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1007 if (SURFBAR_GET_USERID() > 0) {
1008 SUB_POINTS("surfbar", SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1011 // Book it to the user
1012 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
1013 ADD_POINTS_REFSYSTEM("surfbar", $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
1015 // Updates the statistics of current URL/userid
1016 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1022 // Get allowed views
1023 $allowed = SURFBAR_GET_ALLOWED_VIEWS();
1025 // Do we have a limit?
1027 // Then count views_max down!
1028 $ADD .= ",views_max=views_max-1";
1032 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
1033 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
1035 // Update the stats entry
1036 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1037 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1039 // Was that update okay?
1040 if (SQL_AFFECTEDROWS() < 1) {
1041 // No, then insert entry
1042 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES (%s,%s,1)",
1043 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
1046 // Update total/daily/weekly/monthly counter
1047 $_CONFIG['surfbar_total_counter']++;
1048 $_CONFIG['surfbar_daily_counter']++;
1049 $_CONFIG['surfbar_weekly_counter']++;
1050 $_CONFIG['surfbar_monthly_counter']++;
1052 // Update config as well
1053 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
1055 // Update the salt for validation and statistics
1056 function SURFBAR_UPDATE_SALT_STATS () {
1057 // Update statistics record
1058 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1060 // Simply store the salt from cache away in database...
1061 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
1062 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
1065 //DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
1068 if (SQL_AFFECTEDROWS() < 1) {
1069 // Insert missing entry!
1070 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1071 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
1075 //DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1077 // Return if the update was okay
1078 return (SQL_AFFECTEDROWS() == 1);
1080 // Check if the reload lock is active for given id
1081 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1082 //DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1084 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1085 FROM "._MYSQL_PREFIX."_surfbar_locks
1086 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
1087 ORDER BY last_surfed ASC
1089 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1093 list($cnt) = SQL_FETCHROW($result);
1096 SQL_FREERESULT($result);
1099 //DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."", false);
1102 // Determine which user hash no more points left
1103 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1107 'points' => array(),
1108 'notified' => array(),
1111 // Do we have a current user id?
1112 if ((IS_MEMBER()) && ($limit == 0)) {
1113 // Then add this as well
1114 $UIDs['uid'][$GLOBALS['userid']] = $GLOBALS['userid'];
1115 $UIDs['points'][$GLOBALS['userid']] = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
1116 $UIDs['notified'][$GLOBALS['userid']] = 0;
1118 // Get all userid except logged in one
1119 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1120 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1121 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1122 ON u.userid=d.userid
1123 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
1125 ORDER BY u.userid ASC",
1126 array($GLOBALS['userid']), __FILE__, __LINE__);
1129 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1130 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1131 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1132 ON u.userid=d.userid
1133 WHERE u.status='ACTIVE'
1135 ORDER BY u.userid ASC", __FILE__, __LINE__);
1139 while (list($uid, $notified) = SQL_FETCHROW($result)) {
1141 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1142 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1144 // Shall we add this to ignore?
1145 if ($points <= $limit) {
1147 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1148 $UIDs['uid'][$uid] = $uid;
1149 $UIDs['points'][$uid] = $points;
1150 $UIDs['notified'][$uid] = $notified;
1155 SQL_FREERESULT($result);
1158 //DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1163 // Determine how many users are Online in surfbar
1164 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1167 // Count all users in surfbar modue and return the value
1168 $result = SQL_QUERY_ESC("SELECT id
1169 FROM "._MYSQL_PREFIX."_surfbar_stats
1170 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1172 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
1175 $cnt = SQL_NUMROWS($result);
1178 SQL_FREERESULT($result);
1183 // Determine waiting time for one URL
1184 function SURFBAR_DETERMINE_WAIT_TIME () {
1187 // Get fixed reload lock
1188 $fixed = SURFBAR_GET_FIXED_RELOAD();
1190 // Is the fixed reload time set?
1196 // Static time is default
1197 $time = $_CONFIG['surfbar_static_time'];
1199 // Which payment model do we have?
1200 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1201 // "Calculate" dynamic time
1202 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1208 // Changes the status of an URL from given to other
1209 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1212 // Make new status always lower-case
1213 $newStatus = strtolower($newStatus);
1215 // Get URL data for status comparison if missing
1216 if ((!is_array($data)) || (count($data) == 0)) {
1217 // Fetch missing URL data
1218 $data = SURFBAR_GET_URL_DATA($urlId);
1221 // Is the new status set?
1222 if ((!is_string($newStatus)) || (empty($newStatus))) {
1223 // Abort here, but fine!
1227 // Is the status like prevStatus is saying?
1228 if ($data[$urlId]['status'] != $prevStatus) {
1229 // No, then abort here
1234 // Update the status now
1235 // ---------- Comment out for debugging/developing member actions! ---------
1236 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1237 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1238 // ---------- Comment out for debugging/developing member actions! ---------
1241 //if (SQL_AFFECTEDROWS() != 1) {
1242 // // No, something went wrong
1246 // Prepare content for notification routines
1247 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1248 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1249 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
1250 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
1252 // Do some dirt fixing here:
1253 if (($data[$urlId]['status'] == "STOPPED") && ($newStatus == "pending")) {
1254 // Fix for template change
1255 $newStatus = "continued";
1258 // Send admin notification
1259 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1261 // Send user notification
1262 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1267 // Calculate minimum value for dynamic payment model
1268 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1271 // Addon is zero by default
1275 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1278 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1281 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1284 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1287 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1289 // Get user's total URLs
1290 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1293 if ($totalUrls > 0) {
1294 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1296 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1302 // Calculate maximum value for dynamic payment model
1303 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1306 // Addon is zero by default
1313 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1316 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1319 $addon += abs($max * $percent * $totalUsers);
1322 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1325 $addon += abs($max * $percent * $totalUrls);
1330 // Calculate dynamic lock
1331 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1334 // Default lock is 30 seconds
1338 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1341 $addon = abs(log($onlineUsers / $addon + 1));
1346 // "Getter" for lock ids array
1347 function SURFBAR_GET_LOCK_IDS () {
1348 // Prepare some arrays
1353 // Get all id from locks within the timestamp
1354 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1356 "._MYSQL_PREFIX."_surfbar_locks
1360 id ASC", array($GLOBALS['userid']),
1361 __FILE__, __LINE__);
1364 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1366 //DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."", false);
1368 // Skip entries that are too old
1369 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1371 //DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1373 // Add only if missing or bigger
1374 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1376 //DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1384 //DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1386 // Ignore these old entries!
1394 SQL_FREERESULT($result);
1399 // "Getter" for maximum random number
1400 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1402 // Count max availabe entries
1403 $result = SQL_QUERY("SELECT sbu.id AS cnt
1404 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1405 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1406 ON sbu.id=sbs.url_id
1407 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1409 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."
1410 GROUP BY sbu.id", __FILE__, __LINE__);
1413 //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1416 $maxRand = SQL_NUMROWS($result);
1419 SQL_FREERESULT($result);
1424 // Load all URLs of the current user and return it as an array
1425 function SURFBAR_GET_USER_URLS () {
1430 $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
1431 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1432 WHERE u.userid=%s AND u.status != 'DELETED'
1434 array($GLOBALS['userid']), __FILE__, __LINE__);
1436 // Are there entries?
1437 if (SQL_NUMROWS($result) > 0) {
1439 while ($row = SQL_FETCHARRAY($result)) {
1441 $URLs[$row['id']] = $row;
1446 SQL_FREERESULT($result);
1451 // "Getter" for member action array for given status
1452 function SURFBAR_GET_ACTION_ARRAY ($status) {
1454 $returnArray = array();
1456 // Get all assigned actions
1457 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1458 array($status), __FILE__, __LINE__);
1460 // Some entries there?
1461 if (SQL_NUMROWS($result) > 0) {
1463 while (list($action) = SQL_FETCHROW($result)) {
1464 $returnArray[] = $action;
1469 SQL_FREERESULT($result);
1472 return $returnArray;
1474 // Reload to configured stop page
1475 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1478 // Internal or external?
1479 if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1480 // Reload to internal page
1481 LOAD_URL("surfbar.php?frame=".$page);
1483 // Reload to external page
1484 LOAD_URL($_CONFIG['surfbar_pause_url']);
1488 // Determine next id for surfbar or get data for given id, always call this before you call other
1489 // getters below this function!!!
1490 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1491 global $SURFBAR_CACHE, $_CONFIG;
1493 // Default is no id and no random number
1499 // Get array with lock ids
1500 $USE = SURFBAR_GET_LOCK_IDS();
1502 // Shall we add some URL ids to ignore?
1504 if (count($USE) > 0) {
1506 $ADD = " AND sbu.id NOT IN (";
1507 foreach ($USE as $url_id => $lid) {
1509 $ADD .= $url_id.",";
1512 // Add closing bracket
1513 $ADD = substr($ADD, 0, -1) . ")";
1516 // Determine depleted user account
1517 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1519 // Get maximum randomness factor
1520 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1522 // If more than one URL can be called generate the random number!
1524 // Generate random number
1525 $randNum = mt_rand(0, ($maxRand - 1));
1528 // And query the database
1529 //DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."", false);
1530 $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
1531 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1532 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1533 ON sbu.id=sbs.url_id
1534 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1536 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."
1538 ORDER BY l.last_surfed ASC, sbu.id ASC
1540 array($randNum), __FILE__, __LINE__
1543 // Get data from specified id number
1544 $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
1545 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1546 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1547 ON sbu.id=sbs.url_id
1548 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1550 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))
1552 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1556 // Is there an id number?
1557 //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1558 if (SQL_NUMROWS($result) == 1) {
1560 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1561 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1562 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1564 // Determine waiting time
1565 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1567 // Is the last salt there?
1568 if (is_null($SURFBAR_CACHE['last_salt'])) {
1569 // Then repair it wit the static!
1570 //DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1571 $SURFBAR_CACHE['last_salt'] = "";
1574 // Fix missing last_surfed
1575 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1577 //DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1578 $SURFBAR_CACHE['last_surfed'] = 0;
1581 // Get base/fixed reward and costs
1582 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1583 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1584 //DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1586 // Only in dynamic model add the dynamic bonus!
1587 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1588 // Calculate dynamic reward/costs and add it
1589 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1590 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1591 //DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1595 $nextId = SURFBAR_GET_ID();
1599 SQL_FREERESULT($result);
1602 //DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1605 // -----------------------------------------------------------------------------
1606 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1607 // $SURFBAR_CACHE ARRAY!
1608 // -----------------------------------------------------------------------------
1609 // Private getter for data elements
1610 function SURFBAR_GET_DATA ($element) {
1611 global $SURFBAR_CACHE;
1612 //DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1617 // Is the entry there?
1618 if (isset($SURFBAR_CACHE[$element])) {
1620 $data = $SURFBAR_CACHE[$element];
1621 } else { // END - if
1623 print_r($SURFBAR_CACHE);
1624 debug_print_backtrace();
1629 //DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1632 // Getter for reward from cache
1633 function SURFBAR_GET_REWARD () {
1634 // Get data element and return its contents
1635 return SURFBAR_GET_DATA('reward');
1637 // Getter for costs from cache
1638 function SURFBAR_GET_COSTS () {
1639 // Get data element and return its contents
1640 return SURFBAR_GET_DATA('costs');
1642 // Getter for URL from cache
1643 function SURFBAR_GET_URL () {
1644 // Get data element and return its contents
1645 return SURFBAR_GET_DATA('url');
1647 // Getter for salt from cache
1648 function SURFBAR_GET_SALT () {
1649 // Get data element and return its contents
1650 return SURFBAR_GET_DATA('salt');
1652 // Getter for id from cache
1653 function SURFBAR_GET_ID () {
1654 // Get data element and return its contents
1655 return SURFBAR_GET_DATA('id');
1657 // Getter for userid from cache
1658 function SURFBAR_GET_USERID () {
1659 // Get data element and return its contents
1660 return SURFBAR_GET_DATA('userid');
1662 // Getter for user reload locks
1663 function SURFBAR_GET_USER_RELOAD_LOCK () {
1664 // Get data element and return its contents
1665 return SURFBAR_GET_DATA('user_locks');
1667 // Getter for reload time
1668 function SURFBAR_GET_RELOAD_TIME () {
1669 // Get data element and return its contents
1670 return SURFBAR_GET_DATA('time');
1672 // Getter for allowed views
1673 function SURFBAR_GET_ALLOWED_VIEWS () {
1674 // Get data element and return its contents
1675 return SURFBAR_GET_DATA('views_allowed');
1677 // Getter for fixed reload
1678 function SURFBAR_GET_FIXED_RELOAD () {
1679 // Get data element and return its contents
1680 return SURFBAR_GET_DATA('fixed_reload');