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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
45 // -----------------------------------------------------------------------------
47 // -----------------------------------------------------------------------------
49 // Admin has added an URL with given user id and so on
50 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
55 } elseif (!isUrlValid($url)) {
58 } elseif (SURFBAR_LOOKUP_BY_URL($url, '0')) {
59 // URL already found in surfbar!
61 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
64 } elseif (''.($limit + 0).'' != ''.$limit.'') {
65 // Invalid amount entered
67 } elseif (''.($reload + 0).'' != ''.$reload.'') {
68 // Invalid amount entered
72 // Register the new URL
73 return SURFBAR_REGISTER_URL($url, '0', 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
76 // Admin unlocked an email so we can migrate the URL
77 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
82 } elseif (!isUrlValid($url)) {
85 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
86 // URL already found in surfbar!
88 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
93 // Register the new URL
94 return SURFBAR_REGISTER_URL($url, $uid, 'MIGRATED', 'migrate');
97 // Admin function for unlocking URLs
98 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
99 // Is this an admin or invalid array?
101 // Not admin or invalid IDs array
103 } elseif (!is_array($IDs)) {
106 } elseif (count($IDs) == 0) {
111 // Set to true to make AND expression valid if first URL got unlocked
114 // Update the status for all ids
115 foreach ($IDs as $id => $dummy) {
116 // Test all ids through (ignores failed)
117 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
120 // Return total status
124 // Admin function for rejecting URLs
125 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
126 // Is this an admin or invalid array?
128 // Not admin or invalid IDs array
130 } elseif (!is_array($IDs)) {
133 } elseif (count($IDs) == 0) {
138 // Set to true to make AND expression valid if first URL got unlocked
141 // Update the status for all ids
142 foreach ($IDs as $id => $dummy) {
143 // Test all ids through (ignores failed)
144 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
147 // Return total status
152 // -----------------------------------------------------------------------------
154 // -----------------------------------------------------------------------------
156 // Member has added an URL
157 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
158 // Do some pre-checks
162 } elseif (!isUrlValid($url)) {
165 } elseif (SURFBAR_LOOKUP_BY_URL($url, getUserId())) {
166 // URL already found in surfbar!
168 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getUserId())) {
171 } elseif (''.($limit + 0).'' != ''.$limit.'') {
172 // Invalid amount entered
176 // Register the new URL
177 return SURFBAR_REGISTER_URL($url, getUserId(), 'PENDING', 'reg', array('limit' => $limit));
180 // Create list of actions depending on status for the user
181 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
182 // Load all actions in an array for given status
183 $actionArray = SURFBAR_getModeAction_ARRAY($status);
186 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
190 $width = round(100 / count($actionArray));
192 // "Walk" through all actions and create forms
193 foreach ($actionArray as $actionId => $action) {
194 // Add form for this action
195 $OUT .= sprintf(LOAD_TEMPLATE('member_surfbar_list_form', true),
212 // Do the member form request
213 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
214 // By default no action is performed
221 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
222 // Important form elements are missing!
224 } elseif (!isset($URLs[$formData['id']])) {
225 // ID not found in cache
227 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
228 // Action not allowed for current URL status
233 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
236 if ($action != $formData['action']) {
237 // Invalid data in action found
241 // Create the function name for selected action
242 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
244 // Is the function there?
245 if (function_exists($functionName)) {
247 $URLs[$formData['id']]['new_status'] = $GLOBALS['cache_array']['surfbar']['new_status'];
249 // Extract URL data for call-back
250 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
252 // Action found so execute it
253 $performed = call_user_func_array($functionName, $urlData);
255 // Log invalid request
256 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
257 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
264 // Validate if the requested action can be performed on current URL status
265 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
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), __FUNCTION__, __LINE__);
270 // Is the entry there?
271 $isValid = (SQL_NUMROWS($result) == 1);
273 // Fetch the new status if found
276 list($GLOBALS['cache_array']['surfbar']['new_status']) = SQL_FETCHROW($result);
280 SQL_FREERESULT($result);
287 // -----------------------------------------------------------------------------
289 // -----------------------------------------------------------------------------
291 // Retreat a booked URL
292 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
293 // Create the data array for next function call
295 $urlData['id'] => $urlData
298 // Simply change the status here
299 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
302 // Book an URL now (from migration)
303 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
304 // Create the data array for next function call
306 $urlData['id'] => $urlData
309 // Simply change the status here
310 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
313 // Show edit form or do the changes
314 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
315 // Is the "execute" flag there?
316 if (isset($urlData['edit']['execute'])) {
317 // Execute the changes
318 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
322 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
325 // Show delete form or do the changes
326 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
327 // Is the "execute" flag there?
328 if (isset($urlData['delete']['execute'])) {
329 // Execute the changes
330 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
334 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
337 // Pause active banner
338 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
339 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
342 // Unpause stopped banner
343 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
344 // Fix missing entry for template
345 $urlData['edit'] = $urlData['unpause'];
346 $urlData['edit']['url'] = $urlData['url'];
347 $urlData['edit']['limit'] = $urlData['views_max'];
349 // Return status change
350 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
353 // Resubmit locked URL
354 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
355 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
358 // Display selected "action form"
359 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
360 // Translate some data
361 $urlData['registered'] = generateDateTime($urlData['registered'], '2');
362 $urlData['views_total'] = translateComma($urlData['views_total']);
363 $urlData['views_max'] = translateComma($urlData['views_max']);
364 $urlData['views_allowed'] = translateComma($urlData['views_allowed']);
365 $urlData['last_locked'] = generateDateTime($urlData['last_locked'], '2');
367 // Is the lock reason empty?
368 if (empty($urlData['lock_reason'])) {
369 // Fix it to three dashes
370 $urlData['lock_reason'] = '---';
373 // Include fields only for action 'edit'
374 if ($action == 'edit') {
375 // Default is not limited
376 $urlData['limited_yes'] = '';
377 $urlData['limited_no'] = ' checked="checked"';
378 $urlData['limited'] = 'false';
380 // Is this URL limited?
381 if ($urlData['views_max'] > 0) {
382 // Then rewrite form data
383 $urlData['limited_yes'] = ' checked="checked"';
384 $urlData['limited_no'] = '';
385 $urlData['limited'] = 'true';
389 // Load the form and display it
390 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
392 // All fine by default ... ;-)
396 // Execute choosen action
397 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
398 // By default nothing is executed
401 // Is limitation "no" and "limit" is > 0?
402 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == 'N') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
403 // Set it to unlimited
404 $urlData[$action]['limit'] = 0;
407 // Construct function name
408 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
410 // Is 'userid' set and not 'uid' ?
411 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
413 $urlData['uid'] = $urlData['userid'];
416 // Is that function there?
417 if (function_exists($functionName)) {
418 // Execute the function
419 if (call_user_func_array($functionName, array($urlData)) == true) {
420 // Update status as well
421 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
425 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
431 // "Execute edit" function: Update changed data
432 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
433 // Default is nothing done
436 // Translate URLs for testing
437 $url1 = COMPILE_CODE($urlData['url']);
438 $url2 = COMPILE_CODE($urlData['edit']['url']);
440 // Has the URL or limit changed?
442 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
444 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",
445 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
454 // "Execute delete" function: Does nothing...
455 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
456 // Nothing special to do (see above function for such "special actions" to perform)
460 // -----------------------------------------------------------------------------
461 // Self-maintenance functions
462 // -----------------------------------------------------------------------------
465 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
466 // Handle URLs which limit has depleted so we can stop them
467 SURFBAR_HANDLE_DEPLETED_VIEWS();
469 // Handle low-points amounts
470 SURFBAR_HANDLE_LOW_POINTS();
472 // Handle URLs which limit has depleted
473 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
475 $urlArray = SURFBAR_GET_URL_DATA('0', 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
477 // Do we have some entries?
478 if (count($urlArray) > 0) {
480 foreach ($urlArray as $id => $urlData) {
484 // Rewrite array for next call
485 $urlData[$id] = $data;
488 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
493 // Alert users which have URLs booked and are low on points amount
494 function SURFBAR_HANDLE_LOW_POINTS () {
496 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
498 // "Walk" through all URLs
499 foreach ($UIDs['uid'] as $uid => $dummy) {
500 // Is the last notification far enougth away to notify again?
501 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
505 'low' => translateComma(getConfig('surfbar_warn_low_points')),
506 'points' => translateComma($UIDs['points'][$uid]),
507 'notified' => generateDateTime($UIDs['notified'][$uid]),
508 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
512 SURFBAR_NOTIFY_USER('low_points', $content);
514 // Update last notified
515 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
516 array($uid), __FUNCTION__, __LINE__);
522 // -----------------------------------------------------------------------------
524 // -----------------------------------------------------------------------------
527 // Looks up by an URL
528 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
529 // Now lookup that given URL by itself
530 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($uid)));
533 return (count($urlArray) > 0);
536 // Load URL data by given search term and column
537 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add = '') {
538 // By default nothing is found
539 $GLOBALS['last_url_data'] = array();
541 // Is the column an id number?
542 if (($column == "id") || ($column == 'userid')) {
543 // Extra secure input
544 $searchTerm = bigintval($searchTerm);
547 // If the column is "id" there can be only one entry
549 if ($column == "id") {
553 // Look up the record
554 $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
555 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
556 WHERE %s='%s'".$add."
559 array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
561 // Is there at least one record?
562 if (SQL_NUMROWS($result) > 0) {
564 while ($dataRow = SQL_FETCHARRAY($result)) {
565 // Shall we group these results?
566 if ($group == "id") {
567 // Add the row by id as index
568 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
571 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
577 SQL_FREERESULT($result);
580 return $GLOBALS['last_url_data'];
583 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
584 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $extraFields = array()) {
585 // Make sure by the user registered URLs are always pending
586 if ($addMode == "reg") $status = "PENDING";
589 $content = merge_array($extraFields, array(
591 'frametester' => FRAMETESTER($url),
596 // Is limit/reload set?
597 if (!isset($config['limit'])) $content['limit'] = 0;
598 if (!isset($config['reload'])) $content['reload'] = 0;
600 // Insert the URL into database
601 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
604 if ($content['insert_id'] == 0) {
605 // INSERT did not insert any data!
609 // Translate status and limit
610 $content['limit'] = surfbarTranslateLimit($content['limit']);
612 // If in reg-mode we notify admin
613 if (($addMode == "reg") || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
614 // Notify admin even when he as unlocked an email
615 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
619 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
621 // Return the insert id
622 return $content['insert_id'];
625 // Inserts an url by given data array and return the insert id
626 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
628 $uid = bigintval($urlData['uid']);
631 if (empty($uid)) $uid = 0;
633 // Just run the insert query for now
634 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)",
642 ), __FUNCTION__, __LINE__
646 return SQL_INSERTID();
649 // Notify admin(s) with a selected message and content
650 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
651 // Prepare template name
652 $templateName = sprintf("admin_surfbar_%s", $messageType);
655 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
656 strtoupper($messageType)
659 // Is the subject line there?
660 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
661 // Set default subject if following eval() wents wrong
662 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
665 // Translate some data if present
666 if (isset($content['status'])) $content['status'] = surfbarTranslateUserStatus($content['status']);
667 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], '2');
668 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], '2');
669 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
670 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
671 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
673 // Send the notification out
674 return sendAdminNotification($subject, $templateName, $content, $content['uid']);
677 // Notify the user about the performed action
678 function SURFBAR_NOTIFY_USER ($messageType, $content) {
679 // Skip notification if userid is zero
680 if ($content['uid'] == 0) {
684 // Prepare template name
685 $templateName = sprintf("member_surfbar_%s", $messageType);
688 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
689 strtoupper($messageType)
692 // Is the subject line there?
693 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
694 // Set default subject if following eval() wents wrong
695 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
698 // Translate some data if present
699 if (isset($content['status'])) $content['status'] = surfbarTranslateUserStatus($content['status']);
700 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], '2');
701 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], '2');
702 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
703 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
704 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
707 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
710 return sendEmail($content['uid'], $subject, $mailText);
713 // Translates the limit
714 function surfbarTranslateLimit ($limit) {
718 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
721 $return = translateComma($limit);
728 // Translate the URL status
729 function surfbarTranslateUserStatus ($status) {
730 // Create constant name
731 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
733 // Set default translated status
734 $statusTranslated = '!'.$constantName.'!';
736 // Is the constant there?
737 if (defined($constantName)) {
738 // Then get it's value
739 $statusTranslated = constant($constantName);
743 return $statusTranslated;
747 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
748 // Static values are default
749 $reward = getConfig('surfbar_static_reward');
751 // Do we have static or dynamic?
752 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
753 // "Calculate" dynamic reward
755 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
757 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
766 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
767 // Static costs is default
768 $costs = getConfig('surfbar_static_costs');
770 // Do we have static or dynamic?
771 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
772 // "Calculate" dynamic costs
774 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
776 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
784 // "Calculate" dynamic add
785 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
786 // Get min/max values
787 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
788 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
790 // "Calculate" dynamic part and return it
791 return mt_rand($min, $max);
794 // Determine right template name
795 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
796 // Default is the frameset
797 $templateName = "surfbar_frameset";
799 // Any frame set? ;-)
800 if (REQUEST_ISSET_GET(('frame'))) {
801 // Use the frame as a template name part... ;-)
802 $templateName = sprintf("surfbar_frame_%s",
803 REQUEST_GET(('frame'))
808 return $templateName;
811 // Check if the "reload lock" of the current user is full, call this function
812 // before you call SURFBAR_CHECK_RELOAD_LOCK().
813 function SURFBAR_CHECK_RELOAD_FULL() {
817 // Cache static reload lock
818 $GLOBALS['cache_array']['surfbar']['surf_lock'] = getConfig('surfbar_static_lock');
819 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
821 // Do we have dynamic model?
822 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
823 // "Calculate" dynamic lock
824 $GLOBALS['cache_array']['surfbar']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
828 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
829 INNER JOIN `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
831 WHERE l.userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND (((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR u.fixed_reload = 0)
833 array(getUserId()), __FUNCTION__, __LINE__
837 list($GLOBALS['cache_array']['surfbar']['user_locks']) = SQL_FETCHROW($result);
840 if (is_null($GLOBALS['cache_array']['surfbar']['user_locks'])) {
841 // Then fix it to zero!
842 $GLOBALS['cache_array']['surfbar']['user_locks'] = 0;
846 SQL_FREERESULT($result);
849 $total = SURFBAR_GET_TOTAL_URLS();
851 // Do we have some URLs in lock? Admins can always surf on own URLs!
852 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
853 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
859 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
860 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = 0) {
861 // Determine depleted user account
862 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
864 // Is the exlude userid set?
865 if ($excludeUserId > 0) {
867 $UIDs['uid'][$excludeUserId] = $excludeUserId;
870 // Get amount from database
871 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
872 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
873 WHERE userid NOT IN (".implode(',', $UIDs['uid']).") AND `status`='%s'",
874 array($status), __FUNCTION__, __LINE__
878 list($cnt) = SQL_FETCHROW($result);
881 SQL_FREERESULT($result);
887 // Check wether the user is allowed to book more URLs
888 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
889 // Is this admin and userid is zero or does the user has some URLs left to book?
890 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, '', array("REJECTED")) < getConfig('surfbar_max_order')));
893 // Get total amount of URLs of given status for current user
894 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status = '',$exclude = '') {
895 // Is the user 0 and user is logged in?
896 if (($uid == 0) && (IS_MEMBER())) {
897 // Then use this userid
899 } elseif ($uid == 0) {
901 return (getConfig('surfbar_max_order') + 1);
904 // Default is all URLs
907 // Is the status set?
908 if (is_array($status)) {
909 // Only URLs with these status
910 $add = sprintf(" AND status IN('%s')", implode("','", $status));
911 } elseif (!empty($status)) {
912 // Only URLs with this status
913 $add = sprintf(" AND `status`='%s'", $status);
914 } elseif (is_array($exclude)) {
915 // Exclude URLs with these status
916 $add = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
917 } elseif (!empty($exclude)) {
918 // Exclude URLs with this status
919 $add = sprintf(" AND status != '%s'", $exclude);
922 // Get amount from database
923 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
924 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
925 WHERE userid=%s".$add."
927 array($uid, getConfig('surfbar_max_order')), __FUNCTION__, __LINE__
931 list($cnt) = SQL_FETCHROW($result);
934 SQL_FREERESULT($result);
940 // Generate a validation code for the given id number
941 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
942 // @TODO Invalid salt should be refused
943 $GLOBALS['cache_array']['surfbar']['salt'] = "INVALID";
945 // Get code length from config
946 $length = getConfig('code_length');
949 if ($length == 0) $length = 10;
951 // Generate a code until the length matches
953 while (strlen($valCode) != $length) {
956 // Generate random hashed string
957 $GLOBALS['cache_array']['surfbar']['salt'] = sha1(generatePassword(255));
958 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
961 $GLOBALS['cache_array']['surfbar']['salt'] = $salt;
962 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
965 // ... and now the validation code
966 $valCode = generateRandomCodde($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getUserId());
967 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
970 // Hash it with md5() and salt it with the random string
971 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
973 // Finally encrypt it PGP-like and return it
974 $valHashedCode = generatePassString($hashedCode);
976 // Return hashed value
977 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
978 return $valHashedCode;
981 // Check validation code
982 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
984 $urlId = bigintval($urlId);
986 // Now generate the code again
987 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
989 // Return result of checking hashes and salts
990 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '---'.$code."|".$check.'---', false);
991 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
992 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
995 // Lockdown the userid/id combination (reload lock)
996 function SURFBAR_LOCKDOWN_ID ($urlId) {
997 //* DEBUG: */ print "LOCK!");
998 ///* DEBUG: */ return;
999 // Just add it to the database
1000 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (userid, url_id) VALUES (%s, %s)",
1001 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1003 // Remove the salt from database
1004 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE url_id=%s AND `userid`=%s LIMIT 1",
1005 array(bigintval($urlId), getUserId()), __FUNCTION__, __LINE__);
1008 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1009 function SURFBAR_PAY_POINTS () {
1010 // Remove it from the URL owner
1011 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1012 if (SURFBAR_GET_USERID() > 0) {
1013 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1016 // Book it to the user
1017 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".getUserId().",reward=".SURFBAR_GET_REWARD()."", false);
1018 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getUserId(), SURFBAR_GET_DATA('reward'));
1021 // Updates the statistics of current URL/userid
1022 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1026 // Get allowed views
1027 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1029 // Do we have a limit?
1031 // Then count views_max down!
1032 $add .= ",views_max=views_max-1";
1036 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET views_total=views_total+1".$add." WHERE `id`=%s LIMIT 1",
1037 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1039 // Update the stats entry
1040 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1041 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1043 // Was that update okay?
1044 if (SQL_AFFECTEDROWS() < 1) {
1045 // No, then insert entry
1046 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1047 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1050 // Update total/daily/weekly/monthly counter
1051 incrementConfigEntry('surfbar_total_counter');
1052 incrementConfigEntry('surfbar_daily_counter');
1053 incrementConfigEntry('surfbar_weekly_counter');
1054 incrementConfigEntry('surfbar_monthly_counter');
1056 // Update config as well
1057 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1060 // Update the salt for validation and statistics
1061 function SURFBAR_UPDATE_SALT_STATS () {
1062 // Update statistics record
1063 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1065 // Simply store the salt from cache away in database...
1066 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET last_salt='%s' WHERE url_id=%s AND `userid`=%s LIMIT 1",
1067 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getUserId()), __FUNCTION__, __LINE__);
1070 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".getUserId()."", false);
1073 if (SQL_AFFECTEDROWS() < 1) {
1074 // Insert missing entry!
1075 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1076 array(SURFBAR_GET_ID(), getUserId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1080 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1082 // Return if the update was okay
1083 return (SQL_AFFECTEDROWS() == 1);
1086 // Check if the reload lock is active for given id
1087 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1088 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1090 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1091 FROM `{!_MYSQL_PREFIX!}_surfbar_locks`
1092 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1093 ORDER BY last_surfed ASC
1095 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1099 list($cnt) = SQL_FETCHROW($result);
1102 SQL_FREERESULT($result);
1105 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1109 // Determine which user hash no more points left
1110 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1114 'points' => array(),
1115 'notified' => array(),
1118 // Do we have a current user id?
1119 if ((IS_MEMBER()) && ($limit == 0)) {
1120 // Then add this as well
1121 $UIDs['uid'][getUserId()] = getUserId();
1122 $UIDs['points'][getUserId()] = GET_TOTAL_DATA(getUserId(), "user_points", "points") - GET_TOTAL_DATA(getUserId(), "user_data", "used_points");
1123 $UIDs['notified'][getUserId()] = 0;
1125 // Get all userid except logged in one
1126 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1127 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1128 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1129 ON u.userid=d.userid
1130 WHERE u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1132 ORDER BY u.userid ASC",
1133 array(getUserId()), __FUNCTION__, __LINE__);
1136 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1137 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1138 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1139 ON u.userid=d.userid
1140 WHERE u.`status`='ACTIVE'
1142 ORDER BY u.userid ASC", __FUNCTION__, __LINE__);
1146 while ($content = SQL_FETCHARRAY($result)) {
1148 $points = GET_TOTAL_DATA($content['userid'], "user_points", "points") - GET_TOTAL_DATA($content['userid'], "user_data", "used_points");
1149 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']},points={$points}", false);
1151 // Shall we add this to ignore?
1152 if ($points <= $limit) {
1154 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']} has depleted points amount!", false);
1155 $UIDs['uid'][$content['userid']] = $content['userid'];
1156 $UIDs['points'][$content['userid']] = $points;
1157 $UIDs['notified'][$content['userid']] = $content['notified'];
1162 SQL_FREERESULT($result);
1165 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getUserId().')', false);
1171 // Determine how many users are Online in surfbar
1172 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1173 // Count all users in surfbar modue and return the value
1174 $result = SQL_QUERY_ESC("SELECT id
1175 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1176 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1178 array(getConfig('online_timeout')), __FUNCTION__, __LINE__);
1181 $cnt = SQL_NUMROWS($result);
1184 SQL_FREERESULT($result);
1190 // Determine waiting time for one URL
1191 function SURFBAR_DETERMINE_WAIT_TIME () {
1192 // Get fixed reload lock
1193 $fixed = SURFBAR_GET_FIXED_RELOAD();
1195 // Is the fixed reload time set?
1201 // Static time is default
1202 $time = getConfig('surfbar_static_time');
1204 // Which payment model do we have?
1205 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1206 // "Calculate" dynamic time
1207 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1214 // Changes the status of an URL from given to other
1215 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1216 // Make new status always lower-case
1217 $newStatus = strtolower($newStatus);
1219 // Get URL data for status comparison if missing
1220 if ((!is_array($data)) || (count($data) == 0)) {
1221 // Fetch missing URL data
1222 $data = SURFBAR_GET_URL_DATA($urlId);
1225 // Is the new status set?
1226 if ((!is_string($newStatus)) || (empty($newStatus))) {
1227 // Abort here, but fine!
1231 // Is the status like prevStatus is saying?
1232 if ($data[$urlId]['status'] != $prevStatus) {
1233 // No, then abort here
1238 // Update the status now
1239 // ---------- Comment out for debugging/developing member actions! ---------
1240 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1241 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1242 // ---------- Comment out for debugging/developing member actions! ---------
1245 // ---------- Comment out for debugging/developing member actions! ---------
1246 //if (SQL_AFFECTEDROWS() != 1) {
1247 // // No, something went wrong
1250 // ---------- Comment out for debugging/developing member actions! ---------
1252 // Prepare content for notification routines
1253 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1254 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1255 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1256 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1258 // Do some dirty fixing here:
1259 if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1260 // Fix for template change
1261 $newStatus = 'continued';
1264 // Send admin notification
1265 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1267 // Send user notification
1268 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1274 // Calculate minimum value for dynamic payment model
1275 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1276 // Addon is zero by default
1280 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1283 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1286 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1289 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1292 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1294 // Get user's total URLs
1295 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1298 if ($totalUrls > 0) {
1299 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1301 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1308 // Calculate maximum value for dynamic payment model
1309 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1310 // Addon is zero by default
1317 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1320 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1323 $addon += abs($max * $percent * $totalUsers);
1326 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1329 $addon += abs($max * $percent * $totalUrls);
1335 // Calculate dynamic lock
1336 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1337 // Default lock is 30 seconds
1341 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1344 $addon = abs(log($onlineUsers / $addon + 1));
1350 // "Getter" for lock ids array
1351 function SURFBAR_GET_LOCK_IDS () {
1352 // Prepare some arrays
1357 // Get all id from locks within the timestamp
1358 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1360 {!_MYSQL_PREFIX!}_surfbar_locks
1364 id ASC", array(getUserId()),
1365 __FUNCTION__, __LINE__);
1368 while ($content = SQL_FETCHARRAY($result)) {
1370 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$content['id']},url={$content['url_id']},rest=".(time() - $last).'/'.SURFBAR_GET_SURF_LOCK()."", false);
1372 // Skip entries that are too old
1373 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1375 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1377 // Add only if missing or bigger
1378 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $last)) {
1380 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1383 $IDs[$content['url_id']] = $last;
1384 $USE[$content['url_id']] = $content['id'];
1388 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1390 // Ignore these old entries!
1391 $ignored[] = $content['url_id'];
1392 unset($IDs[$content['url_id']]);
1393 unset($USE[$content['url_id']]);
1398 SQL_FREERESULT($result);
1404 // "Getter" for maximum random number
1405 function SURFBAR_GET_MAX_RANDOM ($UIDs, $add) {
1406 // Count max availabe entries
1407 $result = SQL_QUERY("SELECT sbu.id AS cnt
1408 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1409 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1410 ON sbu.id=sbs.url_id
1411 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1413 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."
1414 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1417 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1420 $maxRand = SQL_NUMROWS($result);
1423 SQL_FREERESULT($result);
1429 // Load all URLs of the current user and return it as an array
1430 function SURFBAR_GET_USER_URLS () {
1435 $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
1436 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1437 WHERE u.userid=%s AND u.status != 'DELETED'
1439 array(getUserId()), __FUNCTION__, __LINE__);
1441 // Are there entries?
1442 if (SQL_NUMROWS($result) > 0) {
1444 while ($row = SQL_FETCHARRAY($result)) {
1446 $URLs[$row['id']] = $row;
1451 SQL_FREERESULT($result);
1457 // "Getter" for member action array for given status
1458 function SURFBAR_getModeAction_ARRAY ($status) {
1460 $returnArray = array();
1462 // Get all assigned actions
1463 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1464 array($status), __FUNCTION__, __LINE__);
1466 // Some entries there?
1467 if (SQL_NUMROWS($result) > 0) {
1469 // @TODO This can be somehow rewritten
1470 while ($content = SQL_FETCHARRAY($result)) {
1471 $returnArray[] = $content['action'];
1476 SQL_FREERESULT($result);
1479 return $returnArray;
1482 // Reload to configured stop page
1483 function SURFBAR_RELOAD_TO_STOP_PAGE ($page="stop") {
1484 // Internal or external?
1485 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1486 // Reload to internal page
1487 redirectToUrl('surfbar.php?frame=' . $page);
1489 // Reload to external page
1490 redirectToConfiguredUrl('surfbar_pause_url');
1494 // Determine next id for surfbar or get data for given id, always call this before you call other
1495 // getters below this function!!!
1496 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1497 // Default is no id and no random number
1503 // Get array with lock ids
1504 $USE = SURFBAR_GET_LOCK_IDS();
1506 // Shall we add some URL ids to ignore?
1508 if (count($USE) > 0) {
1510 $add = " AND sbu.id NOT IN (";
1511 foreach ($USE as $url_id => $lid) {
1513 $add .= $url_id.',';
1516 // Add closing bracket
1517 $add = substr($add, 0, -1) . ')';
1520 // Determine depleted user account
1521 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1523 // Get maximum randomness factor
1524 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $add);
1526 // If more than one URL can be called generate the random number!
1528 // Generate random number
1529 $randNum = mt_rand(0, ($maxRand - 1));
1532 // And query the database
1533 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1534 $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
1535 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1536 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1537 ON sbu.id=sbs.url_id
1538 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1540 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."
1542 ORDER BY l.last_surfed ASC, sbu.id ASC
1544 array($randNum), __FUNCTION__, __LINE__
1547 // Get data from specified id number
1548 $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
1549 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1550 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1551 ON sbu.id=sbs.url_id
1552 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1554 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))
1556 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1560 // Is there an id number?
1561 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1562 if (SQL_NUMROWS($result) == 1) {
1564 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - BEFORE", false);
1565 $GLOBALS['cache_array']['surfbar'] = merge_array($GLOBALS['cache_array']['surfbar'], SQL_FETCHARRAY($result));
1566 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - AFTER", false);
1568 // Determine waiting time
1569 $GLOBALS['cache_array']['surfbar']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1571 // Is the last salt there?
1572 if (is_null($GLOBALS['cache_array']['surfbar']['last_salt'])) {
1573 // Then repair it wit the static!
1574 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1575 $GLOBALS['cache_array']['surfbar']['last_salt'] = '';
1578 // Fix missing last_surfed
1579 if ((!isset($GLOBALS['cache_array']['surfbar']['last_surfed'])) || (is_null($GLOBALS['cache_array']['surfbar']['last_surfed']))) {
1581 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1582 $GLOBALS['cache_array']['surfbar']['last_surfed'] = 0;
1585 // Get base/fixed reward and costs
1586 $GLOBALS['cache_array']['surfbar']['reward'] = SURFBAR_DETERMINE_REWARD();
1587 $GLOBALS['cache_array']['surfbar']['costs'] = SURFBAR_DETERMINE_COSTS();
1588 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1590 // Only in dynamic model add the dynamic bonus!
1591 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1592 // Calculate dynamic reward/costs and add it
1593 $GLOBALS['cache_array']['surfbar']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1594 $GLOBALS['cache_array']['surfbar']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1595 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1599 $nextId = SURFBAR_GET_ID();
1603 SQL_FREERESULT($result);
1606 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1610 // -----------------------------------------------------------------------------
1611 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1612 // THE $GLOBALS['cache_array']['surfbar'] ARRAY!
1613 // -----------------------------------------------------------------------------
1614 // Private getter for data elements
1615 function SURFBAR_GET_DATA ($element) {
1616 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1621 // Is the entry there?
1622 if (isset($GLOBALS['cache_array']['surfbar'][$element])) {
1624 $data = $GLOBALS['cache_array']['surfbar'][$element];
1625 } else { // END - if
1627 print_r($GLOBALS['cache_array']['surfbar']);
1633 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1637 // Getter for reward from cache
1638 function SURFBAR_GET_REWARD () {
1639 // Get data element and return its contents
1640 return SURFBAR_GET_DATA('reward');
1643 // Getter for costs from cache
1644 function SURFBAR_GET_COSTS () {
1645 // Get data element and return its contents
1646 return SURFBAR_GET_DATA('costs');
1649 // Getter for URL from cache
1650 function SURFBAR_GET_URL () {
1651 // Get data element and return its contents
1652 return SURFBAR_GET_DATA('url');
1655 // Getter for salt from cache
1656 function SURFBAR_GET_SALT () {
1657 // Get data element and return its contents
1658 return SURFBAR_GET_DATA('salt');
1661 // Getter for id from cache
1662 function SURFBAR_GET_ID () {
1663 // Get data element and return its contents
1664 return SURFBAR_GET_DATA('id');
1667 // Getter for userid from cache
1668 function SURFBAR_GET_USERID () {
1669 // Get data element and return its contents
1670 return SURFBAR_GET_DATA('userid');
1673 // Getter for user reload locks
1674 function SURFBAR_GET_USER_LOCKS () {
1675 // Get data element and return its contents
1676 return SURFBAR_GET_DATA('user_locks');
1679 // Getter for reload time
1680 function SURFBAR_GET_RELOAD_TIME () {
1681 // Get data element and return its contents
1682 return SURFBAR_GET_DATA('time');
1685 // Getter for allowed views
1686 function SURFBAR_GET_VIEWS_ALLOWED () {
1687 // Get data element and return its contents
1688 return SURFBAR_GET_DATA('views_allowed');
1691 // Getter for fixed reload
1692 function SURFBAR_GET_FIXED_RELOAD () {
1693 // Get data element and return its contents
1694 return SURFBAR_GET_DATA('fixed_reload');
1697 // Getter for surf lock
1698 function SURFBAR_GET_SURF_LOCK () {
1699 // Get data element and return its contents
1700 return SURFBAR_GET_DATA('surf_lock');