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') {
591 $content = merge_array($extraFields, array(
593 'frametester' => FRAMETESTER($url),
598 // Is limit/reload set?
599 if (!isset($config['limit'])) {
600 $content['limit'] = 0;
602 if (!isset($config['reload'])) {
603 $content['reload'] = 0;
606 // Insert the URL into database
607 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
610 if ($content['insert_id'] == 0) {
611 // INSERT did not insert any data!
615 // Translate status and limit
616 $content['limit'] = surfbarTranslateLimit($content['limit']);
618 // If in reg-mode we notify admin
619 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
620 // Notify admin even when he as unlocked an email
621 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
625 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
627 // Return the insert id
628 return $content['insert_id'];
631 // Inserts an url by given data array and return the insert id
632 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
634 $uid = bigintval($urlData['uid']);
637 if (empty($uid)) $uid = 0;
639 // Just run the insert query for now
640 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)",
648 ), __FUNCTION__, __LINE__
652 return SQL_INSERTID();
655 // Notify admin(s) with a selected message and content
656 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
657 // Prepare template name
658 $templateName = sprintf("admin_surfbar_%s", $messageType);
661 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
662 strtoupper($messageType)
665 // Is the subject line there?
666 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
667 // Set default subject if following eval() wents wrong
668 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
671 // Translate some data if present
672 if (isset($content['status'])) $content['status'] = surfbarTranslateUserStatus($content['status']);
673 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], '2');
674 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], '2');
675 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
676 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
677 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
679 // Send the notification out
680 return sendAdminNotification($subject, $templateName, $content, $content['uid']);
683 // Notify the user about the performed action
684 function SURFBAR_NOTIFY_USER ($messageType, $content) {
685 // Skip notification if userid is zero
686 if ($content['uid'] == 0) {
690 // Prepare template name
691 $templateName = sprintf("member_surfbar_%s", $messageType);
694 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
695 strtoupper($messageType)
698 // Is the subject line there?
699 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
700 // Set default subject if following eval() wents wrong
701 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
704 // Translate some data if present
705 if (isset($content['status'])) $content['status'] = surfbarTranslateUserStatus($content['status']);
706 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], '2');
707 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], '2');
708 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
709 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
710 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
713 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
716 return sendEmail($content['uid'], $subject, $mailText);
719 // Translates the limit
720 function surfbarTranslateLimit ($limit) {
724 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
727 $return = translateComma($limit);
734 // Translate the URL status
735 function surfbarTranslateUserStatus ($status) {
736 // Create constant name
737 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
739 // Set default translated status
740 $statusTranslated = '!'.$constantName.'!';
742 // Is the constant there?
743 if (defined($constantName)) {
744 // Then get it's value
745 $statusTranslated = constant($constantName);
749 return $statusTranslated;
753 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
754 // Static values are default
755 $reward = getConfig('surfbar_static_reward');
757 // Do we have static or dynamic?
758 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
759 // "Calculate" dynamic reward
761 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
763 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
772 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
773 // Static costs is default
774 $costs = getConfig('surfbar_static_costs');
776 // Do we have static or dynamic?
777 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
778 // "Calculate" dynamic costs
780 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
782 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
790 // "Calculate" dynamic add
791 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
792 // Get min/max values
793 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
794 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
796 // "Calculate" dynamic part and return it
797 return mt_rand($min, $max);
800 // Determine right template name
801 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
802 // Default is the frameset
803 $templateName = "surfbar_frameset";
805 // Any frame set? ;-)
806 if (REQUEST_ISSET_GET('frame')) {
807 // Use the frame as a template name part... ;-)
808 $templateName = sprintf("surfbar_frame_%s",
814 return $templateName;
817 // Check if the "reload lock" of the current user is full, call this function
818 // before you call SURFBAR_CHECK_RELOAD_LOCK().
819 function SURFBAR_CHECK_RELOAD_FULL() {
823 // Cache static reload lock
824 $GLOBALS['cache_array']['surfbar']['surf_lock'] = getConfig('surfbar_static_lock');
825 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
827 // Do we have dynamic model?
828 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
829 // "Calculate" dynamic lock
830 $GLOBALS['cache_array']['surfbar']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
834 $result = SQL_QUERY_ESC("SELECT COUNT(l.id) AS cnt FROM `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
835 INNER JOIN `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
837 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)
839 array(getUserId()), __FUNCTION__, __LINE__
843 list($GLOBALS['cache_array']['surfbar']['user_locks']) = SQL_FETCHROW($result);
846 if (is_null($GLOBALS['cache_array']['surfbar']['user_locks'])) {
847 // Then fix it to zero!
848 $GLOBALS['cache_array']['surfbar']['user_locks'] = 0;
852 SQL_FREERESULT($result);
855 $total = SURFBAR_GET_TOTAL_URLS();
857 // Do we have some URLs in lock? Admins can always surf on own URLs!
858 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
859 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
865 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
866 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = 0) {
867 // Determine depleted user account
868 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
870 // Is the exlude userid set?
871 if ($excludeUserId > 0) {
873 $UIDs['uid'][$excludeUserId] = $excludeUserId;
876 // Get amount from database
877 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
878 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
879 WHERE userid NOT IN (".implode(',', $UIDs['uid']).") AND `status`='%s'",
880 array($status), __FUNCTION__, __LINE__
884 list($cnt) = SQL_FETCHROW($result);
887 SQL_FREERESULT($result);
893 // Check wether the user is allowed to book more URLs
894 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
895 // Is this admin and userid is zero or does the user has some URLs left to book?
896 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, '', array("REJECTED")) < getConfig('surfbar_max_order')));
899 // Get total amount of URLs of given status for current user
900 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status = '',$exclude = '') {
901 // Is the user 0 and user is logged in?
902 if (($uid == 0) && (IS_MEMBER())) {
903 // Then use this userid
905 } elseif ($uid == 0) {
907 return (getConfig('surfbar_max_order') + 1);
910 // Default is all URLs
913 // Is the status set?
914 if (is_array($status)) {
915 // Only URLs with these status
916 $add = sprintf(" AND status IN('%s')", implode("','", $status));
917 } elseif (!empty($status)) {
918 // Only URLs with this status
919 $add = sprintf(" AND `status`='%s'", $status);
920 } elseif (is_array($exclude)) {
921 // Exclude URLs with these status
922 $add = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
923 } elseif (!empty($exclude)) {
924 // Exclude URLs with this status
925 $add = sprintf(" AND status != '%s'", $exclude);
928 // Get amount from database
929 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
930 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
931 WHERE userid=%s".$add."
933 array($uid, getConfig('surfbar_max_order')), __FUNCTION__, __LINE__
937 list($cnt) = SQL_FETCHROW($result);
940 SQL_FREERESULT($result);
946 // Generate a validation code for the given id number
947 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
948 // @TODO Invalid salt should be refused
949 $GLOBALS['cache_array']['surfbar']['salt'] = "INVALID";
951 // Get code length from config
952 $length = getConfig('code_length');
955 if ($length == 0) $length = 10;
957 // Generate a code until the length matches
959 while (strlen($valCode) != $length) {
962 // Generate random hashed string
963 $GLOBALS['cache_array']['surfbar']['salt'] = sha1(generatePassword(255));
964 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
967 $GLOBALS['cache_array']['surfbar']['salt'] = $salt;
968 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
971 // ... and now the validation code
972 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getUserId());
973 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
976 // Hash it with md5() and salt it with the random string
977 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
979 // Finally encrypt it PGP-like and return it
980 $valHashedCode = generatePassString($hashedCode);
982 // Return hashed value
983 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
984 return $valHashedCode;
987 // Check validation code
988 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
990 $urlId = bigintval($urlId);
992 // Now generate the code again
993 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
995 // Return result of checking hashes and salts
996 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '---'.$code."|".$check.'---', false);
997 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
998 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1001 // Lockdown the userid/id combination (reload lock)
1002 function SURFBAR_LOCKDOWN_ID ($urlId) {
1003 //* DEBUG: */ print "LOCK!");
1004 ///* DEBUG: */ return;
1005 // Just add it to the database
1006 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (userid, url_id) VALUES (%s, %s)",
1007 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1009 // Remove the salt from database
1010 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE url_id=%s AND `userid`=%s LIMIT 1",
1011 array(bigintval($urlId), getUserId()), __FUNCTION__, __LINE__);
1014 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1015 function SURFBAR_PAY_POINTS () {
1016 // Remove it from the URL owner
1017 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1018 if (SURFBAR_GET_USERID() > 0) {
1019 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1022 // Book it to the user
1023 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".getUserId().",reward=".SURFBAR_GET_REWARD()."", false);
1024 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getUserId(), SURFBAR_GET_DATA('reward'));
1027 // Updates the statistics of current URL/userid
1028 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1032 // Get allowed views
1033 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1035 // Do we have a limit?
1037 // Then count views_max down!
1038 $add .= ",views_max=views_max-1";
1042 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET views_total=views_total+1".$add." WHERE `id`=%s LIMIT 1",
1043 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1045 // Update the stats entry
1046 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
1047 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1049 // Was that update okay?
1050 if (SQL_AFFECTEDROWS() < 1) {
1051 // No, then insert entry
1052 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1053 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1056 // Update total/daily/weekly/monthly counter
1057 incrementConfigEntry('surfbar_total_counter');
1058 incrementConfigEntry('surfbar_daily_counter');
1059 incrementConfigEntry('surfbar_weekly_counter');
1060 incrementConfigEntry('surfbar_monthly_counter');
1062 // Update config as well
1063 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1066 // Update the salt for validation and statistics
1067 function SURFBAR_UPDATE_SALT_STATS () {
1068 // Update statistics record
1069 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1071 // Simply store the salt from cache away in database...
1072 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET last_salt='%s' WHERE url_id=%s AND `userid`=%s LIMIT 1",
1073 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getUserId()), __FUNCTION__, __LINE__);
1076 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".getUserId()."", false);
1079 if (SQL_AFFECTEDROWS() < 1) {
1080 // Insert missing entry!
1081 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
1082 array(SURFBAR_GET_ID(), getUserId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1086 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1088 // Return if the update was okay
1089 return (SQL_AFFECTEDROWS() == 1);
1092 // Check if the reload lock is active for given id
1093 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1094 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1096 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
1097 FROM `{!_MYSQL_PREFIX!}_surfbar_locks`
1098 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(last_surfed)
1099 ORDER BY last_surfed ASC
1101 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1105 list($cnt) = SQL_FETCHROW($result);
1108 SQL_FREERESULT($result);
1111 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1115 // Determine which user hash no more points left
1116 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1120 'points' => array(),
1121 'notified' => array(),
1124 // Do we have a current user id?
1125 if ((IS_MEMBER()) && ($limit == 0)) {
1126 // Then add this as well
1127 $UIDs['uid'][getUserId()] = getUserId();
1128 $UIDs['points'][getUserId()] = GET_TOTAL_DATA(getUserId(), "user_points", "points") - GET_TOTAL_DATA(getUserId(), "user_data", "used_points");
1129 $UIDs['notified'][getUserId()] = 0;
1131 // Get all userid except logged in one
1132 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1133 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1134 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1135 ON u.userid=d.userid
1136 WHERE u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1138 ORDER BY u.userid ASC",
1139 array(getUserId()), __FUNCTION__, __LINE__);
1142 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1143 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1144 INNER JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1145 ON u.userid=d.userid
1146 WHERE u.`status`='ACTIVE'
1148 ORDER BY u.userid ASC", __FUNCTION__, __LINE__);
1152 while ($content = SQL_FETCHARRAY($result)) {
1154 $points = GET_TOTAL_DATA($content['userid'], "user_points", "points") - GET_TOTAL_DATA($content['userid'], "user_data", "used_points");
1155 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']},points={$points}", false);
1157 // Shall we add this to ignore?
1158 if ($points <= $limit) {
1160 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']} has depleted points amount!", false);
1161 $UIDs['uid'][$content['userid']] = $content['userid'];
1162 $UIDs['points'][$content['userid']] = $points;
1163 $UIDs['notified'][$content['userid']] = $content['notified'];
1168 SQL_FREERESULT($result);
1171 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getUserId().')', false);
1177 // Determine how many users are Online in surfbar
1178 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1179 // Count all users in surfbar modue and return the value
1180 $result = SQL_QUERY_ESC("SELECT id
1181 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1182 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1184 array(getConfig('online_timeout')), __FUNCTION__, __LINE__);
1187 $cnt = SQL_NUMROWS($result);
1190 SQL_FREERESULT($result);
1196 // Determine waiting time for one URL
1197 function SURFBAR_DETERMINE_WAIT_TIME () {
1198 // Get fixed reload lock
1199 $fixed = SURFBAR_GET_FIXED_RELOAD();
1201 // Is the fixed reload time set?
1207 // Static time is default
1208 $time = getConfig('surfbar_static_time');
1210 // Which payment model do we have?
1211 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1212 // "Calculate" dynamic time
1213 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1220 // Changes the status of an URL from given to other
1221 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1222 // Make new status always lower-case
1223 $newStatus = strtolower($newStatus);
1225 // Get URL data for status comparison if missing
1226 if ((!is_array($data)) || (count($data) == 0)) {
1227 // Fetch missing URL data
1228 $data = SURFBAR_GET_URL_DATA($urlId);
1231 // Is the new status set?
1232 if ((!is_string($newStatus)) || (empty($newStatus))) {
1233 // Abort here, but fine!
1237 // Is the status like prevStatus is saying?
1238 if ($data[$urlId]['status'] != $prevStatus) {
1239 // No, then abort here
1244 // Update the status now
1245 // ---------- Comment out for debugging/developing member actions! ---------
1246 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1247 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1248 // ---------- Comment out for debugging/developing member actions! ---------
1251 // ---------- Comment out for debugging/developing member actions! ---------
1252 //if (SQL_AFFECTEDROWS() != 1) {
1253 // // No, something went wrong
1256 // ---------- Comment out for debugging/developing member actions! ---------
1258 // Prepare content for notification routines
1259 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1260 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1261 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1262 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1264 // Do some dirty fixing here:
1265 if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1266 // Fix for template change
1267 $newStatus = 'continued';
1270 // Send admin notification
1271 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1273 // Send user notification
1274 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1280 // Calculate minimum value for dynamic payment model
1281 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1282 // Addon is zero by default
1286 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1289 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1292 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1295 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1298 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1300 // Get user's total URLs
1301 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1304 if ($totalUrls > 0) {
1305 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1307 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1314 // Calculate maximum value for dynamic payment model
1315 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1316 // Addon is zero by default
1323 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1326 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1329 $addon += abs($max * $percent * $totalUsers);
1332 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1335 $addon += abs($max * $percent * $totalUrls);
1341 // Calculate dynamic lock
1342 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1343 // Default lock is 30 seconds
1347 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1350 $addon = abs(log($onlineUsers / $addon + 1));
1356 // "Getter" for lock ids array
1357 function SURFBAR_GET_LOCK_IDS () {
1358 // Prepare some arrays
1363 // Get all id from locks within the timestamp
1364 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1366 {!_MYSQL_PREFIX!}_surfbar_locks
1370 id ASC", array(getUserId()),
1371 __FUNCTION__, __LINE__);
1374 while ($content = SQL_FETCHARRAY($result)) {
1376 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$content['id']},url={$content['url_id']},rest=".(time() - $last).'/'.SURFBAR_GET_SURF_LOCK()."", false);
1378 // Skip entries that are too old
1379 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1381 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1383 // Add only if missing or bigger
1384 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $last)) {
1386 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1389 $IDs[$content['url_id']] = $last;
1390 $USE[$content['url_id']] = $content['id'];
1394 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1396 // Ignore these old entries!
1397 $ignored[] = $content['url_id'];
1398 unset($IDs[$content['url_id']]);
1399 unset($USE[$content['url_id']]);
1404 SQL_FREERESULT($result);
1410 // "Getter" for maximum random number
1411 function SURFBAR_GET_MAX_RANDOM ($UIDs, $add) {
1412 // Count max availabe entries
1413 $result = SQL_QUERY("SELECT sbu.id AS cnt
1414 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1415 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1416 ON sbu.id=sbs.url_id
1417 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1419 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."
1420 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1423 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1426 $maxRand = SQL_NUMROWS($result);
1429 SQL_FREERESULT($result);
1435 // Load all URLs of the current user and return it as an array
1436 function SURFBAR_GET_USER_URLS () {
1441 $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
1442 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1443 WHERE u.userid=%s AND u.status != 'DELETED'
1445 array(getUserId()), __FUNCTION__, __LINE__);
1447 // Are there entries?
1448 if (SQL_NUMROWS($result) > 0) {
1450 while ($row = SQL_FETCHARRAY($result)) {
1452 $URLs[$row['id']] = $row;
1457 SQL_FREERESULT($result);
1463 // "Getter" for member action array for given status
1464 function SURFBAR_getModeAction_ARRAY ($status) {
1466 $returnArray = array();
1468 // Get all assigned actions
1469 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1470 array($status), __FUNCTION__, __LINE__);
1472 // Some entries there?
1473 if (SQL_NUMROWS($result) > 0) {
1475 // @TODO This can be somehow rewritten
1476 while ($content = SQL_FETCHARRAY($result)) {
1477 $returnArray[] = $content['action'];
1482 SQL_FREERESULT($result);
1485 return $returnArray;
1488 // Reload to configured stop page
1489 function SURFBAR_RELOAD_TO_STOP_PAGE ($page="stop") {
1490 // Internal or external?
1491 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1492 // Reload to internal page
1493 redirectToUrl('surfbar.php?frame=' . $page);
1495 // Reload to external page
1496 redirectToConfiguredUrl('surfbar_pause_url');
1500 // Determine next id for surfbar or get data for given id, always call this before you call other
1501 // getters below this function!!!
1502 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1503 // Default is no id and no random number
1509 // Get array with lock ids
1510 $USE = SURFBAR_GET_LOCK_IDS();
1512 // Shall we add some URL ids to ignore?
1514 if (count($USE) > 0) {
1516 $add = " AND sbu.id NOT IN (";
1517 foreach ($USE as $url_id => $lid) {
1519 $add .= $url_id.',';
1522 // Add closing bracket
1523 $add = substr($add, 0, -1) . ')';
1526 // Determine depleted user account
1527 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1529 // Get maximum randomness factor
1530 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $add);
1532 // If more than one URL can be called generate the random number!
1534 // Generate random number
1535 $randNum = mt_rand(0, ($maxRand - 1));
1538 // And query the database
1539 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1540 $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
1541 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1542 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1543 ON sbu.id=sbs.url_id
1544 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1546 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."
1548 ORDER BY l.last_surfed ASC, sbu.id ASC
1550 array($randNum), __FUNCTION__, __LINE__
1553 // Get data from specified id number
1554 $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
1555 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1556 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1557 ON sbu.id=sbs.url_id
1558 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1560 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))
1562 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1566 // Is there an id number?
1567 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1568 if (SQL_NUMROWS($result) == 1) {
1570 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - BEFORE", false);
1571 $GLOBALS['cache_array']['surfbar'] = merge_array($GLOBALS['cache_array']['surfbar'], SQL_FETCHARRAY($result));
1572 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['cache_array']['surfbar']).") - AFTER", false);
1574 // Determine waiting time
1575 $GLOBALS['cache_array']['surfbar']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1577 // Is the last salt there?
1578 if (is_null($GLOBALS['cache_array']['surfbar']['last_salt'])) {
1579 // Then repair it wit the static!
1580 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1581 $GLOBALS['cache_array']['surfbar']['last_salt'] = '';
1584 // Fix missing last_surfed
1585 if ((!isset($GLOBALS['cache_array']['surfbar']['last_surfed'])) || (is_null($GLOBALS['cache_array']['surfbar']['last_surfed']))) {
1587 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1588 $GLOBALS['cache_array']['surfbar']['last_surfed'] = 0;
1591 // Get base/fixed reward and costs
1592 $GLOBALS['cache_array']['surfbar']['reward'] = SURFBAR_DETERMINE_REWARD();
1593 $GLOBALS['cache_array']['surfbar']['costs'] = SURFBAR_DETERMINE_COSTS();
1594 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1596 // Only in dynamic model add the dynamic bonus!
1597 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1598 // Calculate dynamic reward/costs and add it
1599 $GLOBALS['cache_array']['surfbar']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1600 $GLOBALS['cache_array']['surfbar']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1601 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1605 $nextId = SURFBAR_GET_ID();
1609 SQL_FREERESULT($result);
1612 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1616 // -----------------------------------------------------------------------------
1617 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1618 // THE $GLOBALS['cache_array']['surfbar'] ARRAY!
1619 // -----------------------------------------------------------------------------
1620 // Private getter for data elements
1621 function SURFBAR_GET_DATA ($element) {
1622 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1627 // Is the entry there?
1628 if (isset($GLOBALS['cache_array']['surfbar'][$element])) {
1630 $data = $GLOBALS['cache_array']['surfbar'][$element];
1631 } else { // END - if
1633 print_r($GLOBALS['cache_array']['surfbar']);
1639 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1643 // Getter for reward from cache
1644 function SURFBAR_GET_REWARD () {
1645 // Get data element and return its contents
1646 return SURFBAR_GET_DATA('reward');
1649 // Getter for costs from cache
1650 function SURFBAR_GET_COSTS () {
1651 // Get data element and return its contents
1652 return SURFBAR_GET_DATA('costs');
1655 // Getter for URL from cache
1656 function SURFBAR_GET_URL () {
1657 // Get data element and return its contents
1658 return SURFBAR_GET_DATA('url');
1661 // Getter for salt from cache
1662 function SURFBAR_GET_SALT () {
1663 // Get data element and return its contents
1664 return SURFBAR_GET_DATA('salt');
1667 // Getter for id from cache
1668 function SURFBAR_GET_ID () {
1669 // Get data element and return its contents
1670 return SURFBAR_GET_DATA('id');
1673 // Getter for userid from cache
1674 function SURFBAR_GET_USERID () {
1675 // Get data element and return its contents
1676 return SURFBAR_GET_DATA('userid');
1679 // Getter for user reload locks
1680 function SURFBAR_GET_USER_LOCKS () {
1681 // Get data element and return its contents
1682 return SURFBAR_GET_DATA('user_locks');
1685 // Getter for reload time
1686 function SURFBAR_GET_RELOAD_TIME () {
1687 // Get data element and return its contents
1688 return SURFBAR_GET_DATA('time');
1691 // Getter for allowed views
1692 function SURFBAR_GET_VIEWS_ALLOWED () {
1693 // Get data element and return its contents
1694 return SURFBAR_GET_DATA('views_allowed');
1697 // Getter for fixed reload
1698 function SURFBAR_GET_FIXED_RELOAD () {
1699 // Get data element and return its contents
1700 return SURFBAR_GET_DATA('fixed_reload');
1703 // Getter for surf lock
1704 function SURFBAR_GET_SURF_LOCK () {
1705 // Get data element and return its contents
1706 return SURFBAR_GET_DATA('surf_lock');