2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // -----------------------------------------------------------------------------
47 // -----------------------------------------------------------------------------
49 // Admin has added an URL with given user id and so on
50 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
54 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
56 } elseif (!isUrlValid($url)) {
58 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
60 } elseif (SURFBAR_LOOKUP_BY_URL($url, 0)) {
61 // URL already found in surfbar!
62 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Already added.", $url, $limit, $reload));
64 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
66 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
68 } elseif ('' . ($limit + 0) . '' != '' . $limit . '') {
69 // Invalid limit entered
70 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid limit entered.", $url, $limit, $reload));
72 } elseif ('' . ($reload + 0) . '' != '' . $reload . '') {
73 // Invalid amount entered
74 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid reload entered.", $url, $limit, $reload));
78 // Register the new URL
79 return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
82 // Admin unlocked an email so we can migrate the URL
83 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
88 } elseif (!isUrlValid($url)) {
91 } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
92 // URL already found in surfbar!
94 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
99 // Register the new URL
100 return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
103 // Admin function for unlocking URLs
104 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
105 // Is this an admin or invalid array?
107 // Not admin or invalid ids array
109 } elseif (!is_array($IDs)) {
112 } elseif (count($IDs) == 0) {
117 // Set to true to make AND expression valid if first URL got unlocked
120 // Update the status for all ids
121 foreach ($IDs as $id => $dummy) {
122 // Test all ids through (ignores failed)
123 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
126 // Return total status
130 // Admin function for rejecting URLs
131 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
132 // Is this an admin or invalid array?
134 // Not admin or invalid ids array
136 } elseif (!is_array($IDs)) {
139 } elseif (count($IDs) == 0) {
144 // Set to true to make AND expression valid if first URL got unlocked
147 // Update the status for all ids
148 foreach ($IDs as $id => $dummy) {
149 // Test all ids through (ignores failed)
150 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
153 // Return total status
158 // -----------------------------------------------------------------------------
160 // -----------------------------------------------------------------------------
162 // Member has added an URL
163 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
164 // Do some pre-checks
168 } elseif ((!isUrlValid($url)) && (!isAdmin())) {
171 } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
172 // URL already found in surfbar!
174 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
177 } elseif (''.($limit + 0).'' != ''.$limit.'') {
178 // Invalid amount entered
182 // Register the new URL
183 return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
186 // Create list of actions depending on status for the user
187 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
188 // Load all actions in an array for given status
189 $actionArray = SURFBAR_GET_ARRAY_FROM_STATUS($status);
192 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
196 $width = round(100 / count($actionArray));
198 // "Walk" through all actions and create forms
199 foreach ($actionArray as $actionId => $action) {
200 // Add form for this action
201 $OUT .= loadTemplate('member_surfbar_list_form', true, array(
203 'id' => bigintval($urlId),
204 'action' => strtolower($action),
205 'title' => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE--}',
206 'submit' => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT--}',
218 // Do the member form request
219 function SURFBAR_MEMBER_DO_FORM ($formData, $urlArray) {
220 // By default no action is performed
227 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
228 // Important form elements are missing!
230 } elseif (!isset($urlArray[$formData['id']])) {
231 // id not found in cache
233 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $urlArray[$formData['id']]['url_status'])) {
234 // Action not allowed for current URL status
239 $action = secureString($formData['action']);
242 if ($action != $formData['action']) {
243 // Invalid data in action found
247 // Create the function name for selected action
248 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
250 // Is the function there?
251 if (function_exists($functionName)) {
253 $urlArray[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
255 // Extract URL data for call-back
256 $urlData = array(merge_array($urlArray[$formData['id']], array($action => $formData)));
258 // Action found so execute it
259 $performed = call_user_func_array($functionName, $urlData);
261 // Log invalid request
262 logDebugMessage(__FUNCTION__, __LINE__, "action={$formData['action']},id={$formData['id']},function={$functionName}");
263 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
270 // Validate if the requested action can be performed on current URL status
271 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
272 // Search for the requested action/status combination in database
273 $result = SQL_QUERY_ESC("SELECT new_status FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
274 array($action, $status), __FUNCTION__, __LINE__);
276 // Is the entry there?
277 $isValid = (SQL_NUMROWS($result) == 1);
279 // Fetch the new status if found
282 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
286 SQL_FREERESULT($result);
293 // -----------------------------------------------------------------------------
295 // -----------------------------------------------------------------------------
297 // Retreat a booked URL
298 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
299 // Create the data array for next function call
301 $urlData['id'] => $urlData
304 // Simply change the status here
305 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
308 // Book an URL now (from migration)
309 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
310 // Create the data array for next function call
312 $urlData['id'] => $urlData
315 // Simply change the status here
316 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
319 // Show edit form or do the changes
320 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
321 // Is the "execute" flag there?
322 if (isset($urlData['edit']['execute'])) {
323 // Execute the changes
324 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
328 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
331 // Show delete form or do the changes
332 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
333 // Is the "execute" flag there?
334 if (isset($urlData['delete']['execute'])) {
335 // Execute the changes
336 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
340 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
343 // Pause active banner
344 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
345 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
348 // Unpause stopped banner
349 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
350 // Fix missing entry for template
351 $urlData['edit'] = $urlData['unpause'];
352 $urlData['edit']['url'] = $urlData['url'];
353 $urlData['edit']['limit'] = SURFBAR_GET_VIEWS_MAX();
355 // Return status change
356 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
359 // Resubmit locked URL
360 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
361 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
364 // Display selected "action form"
365 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
366 // Translate some data if present
367 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
369 // Is the lock reason empty?
370 if (empty($urlData['lock_reason'])) {
371 // Fix it to three dashes
372 $urlData['lock_reason'] = '---';
375 // Include fields only for action 'edit'
376 if ($action == 'edit') {
377 // Default is not limited
378 $urlData['limited_y'] = '';
379 $urlData['limited_n'] = ' checked="checked"';
380 $urlData['limited'] = 'false';
382 // Is this URL limited?
383 if (SURFBAR_GET_VIEWS_MAX() > 0) {
384 // Then rewrite form data
385 $urlData['limited_y'] = ' checked="checked"';
386 $urlData['limited_n'] = '';
387 $urlData['limited'] = 'true';
391 // Load the form and display it
392 loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
394 // All fine by default ... ;-)
398 // Execute choosen action
399 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
400 // By default nothing is executed
403 // Is limitation "no" and "limit" is > 0?
404 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
405 // Set it to unlimited
406 $urlData[$action]['limit'] = '0';
409 // Construct function name
410 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
412 // Is that function there?
413 if (function_exists($functionName)) {
414 // Execute the function
415 if (call_user_func_array($functionName, array($urlData)) == true) {
416 // Update status as well
417 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
421 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
427 // "Execute edit" function: Update changed data
428 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
429 // Default is nothing done
432 // Has the URL or limit changed?
434 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
436 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url`='%s', `url_views_allowed`=%s, `url_views_max`=%s WHERE `url_id`=%s AND `status`='%s' LIMIT 1",
437 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['url_status']), __FUNCTION__, __LINE__);
446 // "Execute delete" function: Does nothing...
447 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
448 // Nothing special to do (see above function for such "special actions" to perform)
452 // -----------------------------------------------------------------------------
453 // Self-maintenance functions
454 // -----------------------------------------------------------------------------
457 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
458 // Handle URLs which limit has depleted so we can stop them
459 SURFBAR_HANDLE_DEPLETED_VIEWS();
461 // Handle low-points amounts
462 SURFBAR_HANDLE_LOW_POINTS();
464 // Handle URLs which limit has depleted
465 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
467 $urlArray = SURFBAR_GET_URL_DATA(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
469 // Do we have some entries?
470 if (count($urlArray) > 0) {
472 foreach ($urlArray as $id => $urlData) {
476 // Rewrite array for next call
477 $urlData[$id] = $data;
480 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
485 // Alert users which have URLs booked and are low on points amount
486 function SURFBAR_HANDLE_LOW_POINTS () {
488 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
490 // "Walk" through all URLs
491 foreach ($userids['userid'] as $userid => $dummy) {
492 // Is the last notification far enougth away to notify again?
493 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
497 'low' => translateComma(getConfig('surfbar_warn_low_points')),
498 'points' => translateComma($userids['points'][$userid]),
499 'notified' => generateDateTime($userids['notified'][$userid]),
500 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
504 SURFBAR_NOTIFY_USER('low_points', $content);
506 // Update last notified
507 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
508 array($userid), __FUNCTION__, __LINE__);
514 // -----------------------------------------------------------------------------
516 // -----------------------------------------------------------------------------
519 // Looks up by an URL
520 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
521 // Now lookup that given URL by itself
522 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
525 return (count($urlArray) > 0);
528 // Load URL data by given search term and column
529 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
530 // By default nothing is found
531 $GLOBALS['last_url_data'] = array();
533 // Is the column an id number?
534 if (($column == 'url_id') || ($column == 'url_userid')) {
535 // Extra secure input
536 $searchTerm = bigintval($searchTerm);
539 // If the column is 'id' there can be only one entry
541 if ($column == 'id') {
545 // Look up the record
546 $result = SQL_QUERY_ESC("SELECT
554 UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
555 UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
561 `{?_MYSQL_PREFIX?}_surfbar_urls`
563 `%s`='%s'" . $add . "
573 ), __FUNCTION__, __LINE__);
575 // Is there at least one record?
576 if (SQL_NUMROWS($result) > 0) {
578 while ($dataRow = SQL_FETCHARRAY($result)) {
579 // Shall we group these results?
580 if ($group == 'url_id') {
581 // Add the row by id as index
582 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
585 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
591 SQL_FREERESULT($result);
594 return $GLOBALS['last_url_data'];
597 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
598 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
599 // Make sure by the user registered URLs are always pending
600 if ($addMode == 'reg') {
605 $content = merge_array($extraFields, array(
607 'frametester' => generateFrametesterUrl($url),
608 'url_userid' => $userid,
609 'url_status' => $status,
612 // Is limit/reload set?
613 if (!isset($config['limit'])) {
614 $content['limit'] = '0';
616 if (!isset($config['reload'])) {
617 $content['reload'] = '0';
620 // Insert the URL into database
621 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
624 if ($content['insert_id'] == '0') {
625 // INSERT did not insert any data!
629 // If in reg-mode we notify admin
630 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
631 // Notify admin even when he as unlocked an email
632 SURFBAR_NOTIFY_ADMIN('url_' . $addMode, $content);
636 SURFBAR_NOTIFY_USER('url_' . $addMode, $content);
638 // Return the insert id
639 return $content['insert_id'];
642 // Inserts an url by given data array and return the insert id
643 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
645 $userid = bigintval($urlData['url_userid']);
648 if (empty($userid)) $userid = '0';
650 // Just run the insert query for now
651 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_urls` (`url_userid`,`url`,`url_status`,`url_views_max`,`url_views_allowed`,`url_fixed_reload`) VALUES (%s,'%s','%s',%s,%s,%s)",
655 $urlData['url_status'],
659 ), __FUNCTION__, __LINE__
663 return SQL_INSERTID();
666 // Notify admin(s) with a selected message and content
667 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
668 // Prepare template name
669 $templateName = sprintf("admin_surfbar_%s", $messageType);
672 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
673 strtoupper($messageType)
676 // Is the subject line there?
677 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
678 // Set default subject if following eval() wents wrong
679 $subject = getMaskedMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT', strtoupper($messageType));
682 // Translate some data if present
683 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
685 // Send the notification out
686 return sendAdminNotification($subject, $templateName, $content, $content['userid']);
689 // Notify the user about the performed action
690 function SURFBAR_NOTIFY_USER ($messageType, $content) {
691 // Skip notification if userid is zero
692 if ($content['userid'] == '0') {
696 // Prepare template name
697 $templateName = sprintf("member_surfbar_%s", $messageType);
700 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
701 strtoupper($messageType)
704 // Is the subject line there?
705 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
706 // Set default subject if following eval() wents wrong
707 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
710 // Translate some data if present
711 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
714 $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
717 return sendEmail($content['userid'], $subject, $mailText);
720 // Translates some data for template usage
721 // @TODO Can't we use our new expression language instead of this ugly code?
722 function SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE ($content) {
724 if (isset($content['url_registered'])) $content['url_registered'] = generateDateTime($content['url_registered'], 2);
725 if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
727 // Return translated content
731 // Translates the limit
732 function translateSurfbarLimit ($limit) {
736 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
739 $return = translateComma($limit);
746 // Translate the URL status
747 function translateSurfbarUrlStatus ($status) {
748 // Create constant name
749 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
752 $statusTranslated = getMessage($constantName);
755 return $statusTranslated;
759 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
760 // Static values are default
761 $reward = getConfig('surfbar_static_reward');
763 // Do we have static or dynamic?
764 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
765 // "Calculate" dynamic reward
767 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
769 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
778 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
779 // Static costs is default
780 $costs = getConfig('surfbar_static_costs');
782 // Do we have static or dynamic?
783 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
784 // "Calculate" dynamic costs
786 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
788 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
796 // "Calculate" dynamic add
797 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
798 // Get min/max values
799 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
800 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
802 // "Calculate" dynamic part and return it
803 return mt_rand($min, $max);
806 // Determine right template name
807 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
808 // Default is the frameset
809 $templateName = "surfbar_frameset";
811 // Any frame set? ;-)
812 if (isGetRequestParameterSet('frame')) {
813 // Use the frame as a template name part... ;-)
814 $templateName = sprintf("surfbar_frame_%s",
815 getRequestParameter('frame')
820 return $templateName;
823 // Check if the "reload lock" of the current user is full, call this function
824 // before you call SURFBAR_CHECK_RELOAD_LOCK().
825 function SURFBAR_CHECK_RELOAD_FULL() {
829 // Cache static reload lock
830 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
831 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
833 // Do we have dynamic model?
834 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
835 // "Calculate" dynamic lock
836 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
840 $result = SQL_QUERY_ESC("SELECT
841 COUNT(l.locks_id) AS cnt
843 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
845 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
847 u.url_id=l.locks_url_id
849 l.locks_userid=%s AND
850 (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.locks_last_surfed) AND
852 ((UNIX_TIMESTAMP(l.locks_last_surfed) - u.url_fixed_reload) < 0 AND u.url_fixed_reload > 0) OR
853 u.url_fixed_reload = '0'
856 array(getMemberId()), __FUNCTION__, __LINE__
860 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
863 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
864 // Then fix it to zero!
865 $GLOBALS['surfbar_cache']['user_locks'] = '0';
869 SQL_FREERESULT($result);
872 $total = SURFBAR_GET_TOTAL_URLS();
874 // Do we have some URLs in lock? Admins can always surf on own URLs!
875 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
876 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
882 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
883 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
884 // Determine depleted user account
885 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
887 // If we dont get any user ids back, there are no URLs
888 if (count($userids['userid']) == 0) {
889 // No user ids found, no URLs!
893 // Is the exlude userid set?
894 if ($excludeUserId > 0) {
896 $userids['userid'][$excludeUserId] = $excludeUserId;
899 // Get amount from database
900 $result = SQL_QUERY_ESC("SELECT
901 COUNT(`url_id`) AS cnt
903 `{?_MYSQL_PREFIX?}_surfbar_urls`
905 `url_userid` NOT IN (".implode(', ', $userids['userid']).") AND
908 array($status), __FUNCTION__, __LINE__
912 list($cnt) = SQL_FETCHROW($result);
915 SQL_FREERESULT($result);
921 // Check wether the user is allowed to book more URLs
922 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
923 // Is this admin and userid is zero or does the user has some URLs left to book?
924 return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
927 // Get total amount of URLs of given status for current user
928 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '', $exclude = '') {
929 // Is the user 0 and user is logged in?
930 if (($userid == '0') && (isMember())) {
931 // Then use this userid
932 $userid = getMemberId();
933 } elseif ($userid == '0') {
935 return (getConfig('surfbar_max_order') + 1);
938 // Default is all URLs
941 // Is the status set?
942 if (is_array($status)) {
943 // Only URLs with these status
944 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
945 } elseif (!empty($status)) {
946 // Only URLs with this status
947 $add = sprintf(" AND `url_status`='%s'", $status);
948 } elseif (is_array($exclude)) {
949 // Exclude URLs with these status
950 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
951 } elseif (!empty($exclude)) {
952 // Exclude URLs with this status
953 $add = sprintf(" AND `url_status` != '%s'", $exclude);
956 // Get amount from database
957 $cnt = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
963 // Generate a validation code for the given id number
964 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
965 // @TODO Invalid salt should be refused
966 $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
968 // Get code length from config
969 $length = getConfig('code_length');
972 if ($length == '0') $length = 10;
974 // Generate a code until the length matches
976 while (strlen($valCode) != $length) {
979 // Generate random hashed string
980 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
981 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
984 $GLOBALS['surfbar_cache']['salt'] = $salt;
985 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
988 // ... and now the validation code
989 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
990 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
993 // Hash it with md5() and salt it with the random string
994 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
996 // Finally encrypt it PGP-like and return it
997 $valHashedCode = encodeHashForCookie($hashedCode);
999 // Return hashed value
1000 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
1001 return $valHashedCode;
1004 // Check validation code
1005 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
1007 $urlId = bigintval($urlId);
1009 // Now generate the code again
1010 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1012 // Return result of checking hashes and salts
1013 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1014 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('salts_last_salt').'+++', false);
1015 return (($code == $check) && ($salt == SURFBAR_GET_DATA('salts_last_salt')));
1018 // Lockdown the userid/id combination (reload lock)
1019 function SURFBAR_LOCKDOWN_ID ($urlId) {
1020 //* DEBUG: */ outputHtml('LOCK!');
1021 ///* DEBUG: */ return;
1022 // Just add it to the database
1023 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)",
1024 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1026 // Remove the salt from database
1027 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1028 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1031 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1032 function SURFBAR_PAY_POINTS () {
1033 // Remove it from the URL owner
1034 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1035 if (SURFBAR_GET_USERID() > 0) {
1036 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1039 // Book it to the user
1040 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1041 addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1044 // Updates the statistics of current URL/userid
1045 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1049 // Get allowed views
1050 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1052 // Do we have a limit?
1054 // Then count views_max down!
1055 $add .= ", `views_max`=`views_max`-1";
1059 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1".$add." WHERE `url_id`=%s LIMIT 1",
1060 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1062 // Update the stats entry
1063 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `stats_count`=`stats_count`+1 WHERE `stats_userid`=%s AND `stats_url_id`=%s LIMIT 1",
1067 ), __FUNCTION__, __LINE__);
1069 // Was that update okay?
1070 if (SQL_AFFECTEDROWS() < 1) {
1071 // No, then insert entry
1072 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)",
1076 ), __FUNCTION__, __LINE__);
1079 // Update total/daily/weekly/monthly counter
1080 incrementConfigEntry('surfbar_total_counter');
1081 incrementConfigEntry('surfbar_daily_counter');
1082 incrementConfigEntry('surfbar_weekly_counter');
1083 incrementConfigEntry('surfbar_monthly_counter');
1085 // Update config as well
1086 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1089 // Update the salt for validation and statistics
1090 function SURFBAR_UPDATE_SALT_STATS () {
1091 // Update statistics record
1092 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1094 // Simply store the salt from cache away in database...
1095 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1100 ), __FUNCTION__, __LINE__);
1103 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1106 if (SQL_AFFECTEDROWS() < 1) {
1107 // Insert missing entry!
1108 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1109 array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1113 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1115 // Return if the update was okay
1116 return (SQL_AFFECTEDROWS() == 1);
1119 // Check if the reload lock is active for given id
1120 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1121 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1123 $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1125 `{?_MYSQL_PREFIX?}_surfbar_locks`
1127 `locks_userid`=%s AND
1128 `locks_url_id`=%s AND
1129 (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1131 `locks_last_surfed` ASC
1133 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1137 list($cnt) = SQL_FETCHROW($result);
1140 SQL_FREERESULT($result);
1143 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1147 // Determine which user hash no more points left
1148 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1151 'userid' => array(),
1152 'points' => array(),
1153 'notified' => array(),
1156 // Do we have a current user id?
1157 if ((isMember()) && ($limit == '0')) {
1158 // Then add this as well
1159 $userids['userid'][getMemberId()] = getMemberId();
1160 $userids['points'][getMemberId()] = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1161 $userids['notified'][getMemberId()] = '0';
1163 // Get all userid except logged in one
1164 $result = SQL_QUERY_ESC("SELECT
1165 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1167 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1169 `{?_MYSQL_PREFIX?}_user_data` AS d
1171 u.url_userid=d.userid
1173 u.url_userid NOT IN (%s,0) AND u.url_status='ACTIVE'
1178 array(getMemberId()), __FUNCTION__, __LINE__);
1181 $result = SQL_QUERY("SELECT
1182 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1184 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1186 `{?_MYSQL_PREFIX?}_user_data` AS d
1188 u.url_userid=d.userid
1190 u.url_status='ACTIVE'
1194 u.url_userid ASC", __FUNCTION__, __LINE__);
1198 while ($content = SQL_FETCHARRAY($result)) {
1200 $points = countSumTotalData($content['userid'], 'user_points', 'points') - countSumTotalData($content['userid'], 'user_data', 'used_points');
1201 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']},points={$points}", false);
1203 // Shall we add this to ignore?
1204 if ($points <= $limit) {
1206 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']} has depleted points amount!", false);
1207 $userids['userid'][$content['userid']] = $content['userid'];
1208 $userids['points'][$content['userid']] = $points;
1209 $userids['notified'][$content['userid']] = $content['notified'];
1214 SQL_FREERESULT($result);
1217 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1223 // Determine how many users are Online in surfbar
1224 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1225 // Count all users in surfbar modue and return the value
1226 $result = SQL_QUERY("SELECT
1229 `{?_MYSQL_PREFIX?}_surfbar_stats`
1231 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1233 `stats_userid` ASC", __FUNCTION__, __LINE__);
1236 $cnt = SQL_NUMROWS($result);
1239 SQL_FREERESULT($result);
1245 // Determine waiting time for one URL
1246 function SURFBAR_DETERMINE_WAIT_TIME () {
1247 // Get fixed reload lock
1248 $fixed = SURFBAR_GET_FIXED_RELOAD();
1250 // Is the fixed reload time set?
1256 // Static time is default
1257 $time = getConfig('surfbar_static_time');
1259 // Which payment model do we have?
1260 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1261 // "Calculate" dynamic time
1262 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1269 // Changes the status of an URL from given to other
1270 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1271 // Make new status always lower-case
1272 $newStatus = strtolower($newStatus);
1274 // Get URL data for status comparison if missing
1275 if ((!is_array($data)) || (count($data) == 0)) {
1276 // Fetch missing URL data
1277 $data = SURFBAR_GET_URL_DATA($urlId);
1280 // Is the new status set?
1281 if ((!is_string($newStatus)) || (empty($newStatus))) {
1282 // Abort here, but fine!
1286 // Is the status like prevStatus is saying?
1287 if ($data[$urlId]['url_status'] != $prevStatus) {
1288 // No, then abort here
1293 // Update the status now
1294 // ---------- Comment out for debugging/developing member actions! ---------
1295 //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1296 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1297 // ---------- Comment out for debugging/developing member actions! ---------
1300 // ---------- Comment out for debugging/developing member actions! ---------
1301 //if (SQL_AFFECTEDROWS() != 1) {
1302 // // No, something went wrong
1305 // ---------- Comment out for debugging/developing member actions! ---------
1307 // Prepare content for notification routines
1308 $data[$urlId]['userid'] = $data[$urlId]['userid'];
1309 $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1310 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1311 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1313 // Do some dirty fixing here:
1314 if (($data[$urlId]['url_status'] == 'STOPPED') && ($newStatus == 'pending')) {
1315 // Fix for template change
1316 $newStatus = 'continued';
1319 // Send admin notification
1320 SURFBAR_NOTIFY_ADMIN('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1322 // Send user notification
1323 SURFBAR_NOTIFY_USER('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1329 // Calculate minimum value for dynamic payment model
1330 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1331 // Addon is zero by default
1335 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1338 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1341 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1344 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1347 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1349 // Get user's total URLs
1350 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1353 if ($totalUrls > 0) {
1354 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1356 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1363 // Calculate maximum value for dynamic payment model
1364 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1365 // Addon is zero by default
1372 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1375 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1378 $addon += abs($max * $percent * $totalUsers);
1381 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1384 $addon += abs($max * $percent * $totalUrls);
1390 // Calculate dynamic lock
1391 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1392 // Default lock is 30 seconds
1396 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1399 $addon = abs(log($onlineUsers / $addon + 1));
1405 // "Getter" for lock ids array
1406 function SURFBAR_GET_LOCK_IDS () {
1407 // Prepare some arrays
1412 // Get all id from locks within the timestamp
1413 $result = SQL_QUERY_ESC("SELECT `locks_id`, `locks_url_id`, UNIX_TIMESTAMP(`locks_last_surfed`) AS last_surfed
1415 `{?_MYSQL_PREFIX?}_surfbar_locks`
1419 `locks_id` ASC", array(getMemberId()),
1420 __FUNCTION__, __LINE__);
1423 while ($content = SQL_FETCHARRAY($result)) {
1425 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1427 // Skip entries that are too old
1428 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1430 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1432 // Add only if missing or bigger
1433 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1435 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1438 $IDs[$content['url_id']] = $content['last_surfed'];
1439 $USE[$content['url_id']] = $content['id'];
1443 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1445 // Ignore these old entries!
1446 $ignored[] = $content['url_id'];
1447 unset($IDs[$content['url_id']]);
1448 unset($USE[$content['url_id']]);
1453 SQL_FREERESULT($result);
1459 // "Getter" for maximum random number
1460 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1461 // Count max availabe entries
1462 $result = SQL_QUERY("SELECT
1465 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1467 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1469 sbu.url_id=sbs.salts_url_id
1471 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1473 sbu.url_id=l.locks_url_id
1475 sbu.url_userid NOT IN (".implode(',', $userids).") AND
1476 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1477 sbu.url_status='ACTIVE'
1480 sbu.url_id ASC", __FUNCTION__, __LINE__);
1483 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1486 $maxRand = SQL_NUMROWS($result);
1489 SQL_FREERESULT($result);
1495 // Load all URLs of the current user and return it as an array
1496 function SURFBAR_GET_USER_URLS () {
1498 $urlArray = array();
1501 $result = SQL_QUERY_ESC("SELECT
1508 u.url_views_allowed,
1509 UNIX_TIMESTAMP(u.url_registered) AS `url_registered`,
1510 UNIX_TIMESTAMP(u.url_last_locked) AS `url_last_locked`,
1513 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1516 u.url_status != 'DELETED'
1519 array(getMemberId()), __FUNCTION__, __LINE__);
1521 // Are there entries?
1522 if (SQL_NUMROWS($result) > 0) {
1524 while ($row = SQL_FETCHARRAY($result)) {
1526 $urlArray[$row['id']] = $row;
1531 SQL_FREERESULT($result);
1537 // "Getter" for member action array for given status
1538 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1540 $returnArray = array();
1542 // Get all assigned actions
1543 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1544 array($status), __FUNCTION__, __LINE__);
1546 // Some entries there?
1547 if (SQL_NUMROWS($result) > 0) {
1549 // @TODO This can be somehow rewritten
1550 while ($content = SQL_FETCHARRAY($result)) {
1551 $returnArray[] = $content['action'];
1556 SQL_FREERESULT($result);
1559 return $returnArray;
1562 // Reload to configured stop page
1563 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1564 // Internal or external?
1565 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1566 // Reload to internal page
1567 redirectToUrl('surfbar.php?frame=' . $page);
1569 // Reload to external page
1570 redirectToConfiguredUrl('surfbar_pause_url');
1574 // Determine next id for surfbar or get data for given id, always call this before you call other
1575 // getters below this function!!!
1576 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1577 // Default is no id and no random number
1582 if ($urlId == '0') {
1583 // Get array with lock ids
1584 $USE = SURFBAR_GET_LOCK_IDS();
1586 // Shall we add some URL ids to ignore?
1588 if (count($USE) > 0) {
1590 $add = " AND sbu.url_id NOT IN (";
1591 foreach ($USE as $url_id => $lid) {
1593 $add .= $url_id.',';
1596 // Add closing bracket
1597 $add = substr($add, 0, -1) . ')';
1600 // Determine depleted user account
1601 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1603 // Get maximum randomness factor
1604 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['userid'], $add);
1606 // If more than one URL can be called generate the random number!
1608 // Generate random number
1609 $randNum = mt_rand(0, ($maxRand - 1));
1612 // And query the database
1613 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1614 $result = SQL_QUERY_ESC("SELECT
1618 sbs.salts_last_salt,
1619 sbu.url_views_total,
1621 sbu.url_views_allowed,
1622 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1623 sbu.url_fixed_reload
1625 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1627 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1629 sbu.url_id=sbs.salts_url_id
1631 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1633 sbu.url_id=l.locks_url_id
1635 sbu.url_userid NOT IN (".implode(',', $userids['userid']).") AND
1636 sbu.url_status='ACTIVE' AND
1637 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1642 l.locks_last_surfed ASC,
1645 array($randNum), __FUNCTION__, __LINE__
1648 // Get data from specified id number
1649 $result = SQL_QUERY_ESC("SELECT
1653 sbs.salts_last_salt,
1654 sbu.url_views_total,
1656 sbu.url_views_allowed,
1657 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1658 sbu.url_fixed_reload
1660 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1662 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1664 sbu.url_id=sbs.salts_url_id
1666 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1668 sbu.url_id=l.locks_url_id
1670 sbu.url_userid != %s AND
1671 sbu.url_status='ACTIVE' AND
1673 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1675 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1679 // Is there an id number?
1680 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1681 if (SQL_NUMROWS($result) == 1) {
1683 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1684 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1685 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1687 // Determine waiting time
1688 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1690 // Is the last salt there?
1691 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1692 // Then repair it wit the static!
1693 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1694 $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1697 // Fix missing last_surfed
1698 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1700 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1701 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1704 // Get base/fixed reward and costs
1705 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1706 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1707 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1709 // Only in dynamic model add the dynamic bonus!
1710 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1711 // Calculate dynamic reward/costs and add it
1712 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1713 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1714 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1718 $nextId = SURFBAR_GET_ID();
1722 SQL_FREERESULT($result);
1725 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1729 // -----------------------------------------------------------------------------
1730 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1731 // THE $GLOBALS['surfbar_cache'] ARRAY!
1732 // -----------------------------------------------------------------------------
1734 // Initializes the surfbar
1735 function SURFBAR_INIT () {
1737 $GLOBALS['surfbar_cache'] = array();
1740 // Private getter for data elements
1741 function SURFBAR_GET_DATA ($element) {
1742 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1747 // Is the entry there?
1748 if (isset($GLOBALS['surfbar_cache'][$element])) {
1750 $data = $GLOBALS['surfbar_cache'][$element];
1751 } else { // END - if
1753 print_r($GLOBALS['surfbar_cache']);
1755 debug_report_bug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
1759 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data, false);
1763 // Getter for reward from cache
1764 function SURFBAR_GET_REWARD () {
1765 // Get data element and return its contents
1766 return SURFBAR_GET_DATA('reward');
1769 // Getter for costs from cache
1770 function SURFBAR_GET_COSTS () {
1771 // Get data element and return its contents
1772 return SURFBAR_GET_DATA('costs');
1775 // Getter for URL from cache
1776 function SURFBAR_GET_URL () {
1777 // Get data element and return its contents
1778 return SURFBAR_GET_DATA('url');
1781 // Getter for salt from cache
1782 function SURFBAR_GET_SALT () {
1783 // Get data element and return its contents
1784 return SURFBAR_GET_DATA('salt');
1787 // Getter for id from cache
1788 function SURFBAR_GET_ID () {
1789 // Get data element and return its contents
1790 return SURFBAR_GET_DATA('url_id');
1793 // Getter for userid from cache
1794 function SURFBAR_GET_USERID () {
1795 // Get data element and return its contents
1796 return SURFBAR_GET_DATA('url_userid');
1799 // Getter for user reload locks
1800 function SURFBAR_GET_USER_LOCKS () {
1801 // Get data element and return its contents
1802 return SURFBAR_GET_DATA('user_locks');
1805 // Getter for reload time
1806 function SURFBAR_GET_RELOAD_TIME () {
1807 // Get data element and return its contents
1808 return SURFBAR_GET_DATA('time');
1811 // Getter for allowed views
1812 function SURFBAR_GET_VIEWS_ALLOWED () {
1813 // Get data element and return its contents
1814 return SURFBAR_GET_DATA('url_views_allowed');
1817 // Getter for maximum views
1818 function SURFBAR_GET_VIEWS_MAX () {
1819 // Get data element and return its contents
1820 return SURFBAR_GET_DATA('url_views_max');
1823 // Getter for fixed reload
1824 function SURFBAR_GET_FIXED_RELOAD () {
1825 // Get data element and return its contents
1826 return SURFBAR_GET_DATA('url_fixed_reload');
1829 // Getter for surf lock
1830 function SURFBAR_GET_SURF_LOCK () {
1831 // Get data element and return its contents
1832 return SURFBAR_GET_DATA('surf_lock');
1835 // Getter for new status
1836 function SURFBAR_GET_NEW_STATUS () {
1837 // Get data element and return its contents
1838 return SURFBAR_GET_DATA('new_status');