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 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 //------------------------------------------------------------------------------
45 //------------------------------------------------------------------------------
47 // Admin has added an URL with given user id and so on
48 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
52 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
54 } elseif (!isUrlValid($url)) {
56 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
58 } elseif (SURFBAR_LOOKUP_BY_URL($url, 0)) {
59 // URL already found in surfbar!
60 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Already added.", $url, $limit, $reload));
62 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
64 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
66 } elseif ('' . ($limit + 0) . '' != '' . $limit . '') {
67 // Invalid limit entered
68 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid limit entered.", $url, $limit, $reload));
70 } elseif ('' . ($reload + 0) . '' != '' . $reload . '') {
71 // Invalid amount entered
72 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid reload entered.", $url, $limit, $reload));
76 // Register the new URL
77 return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
80 // Admin unlocked an email so we can migrate the URL
81 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
86 } elseif (!isUrlValid($url)) {
89 } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
90 // URL already found in surfbar!
92 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
97 // Register the new URL
98 return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
101 // Admin function for unlocking URLs
102 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
103 // Is this an admin or invalid array?
105 // Not admin or invalid ids array
107 } elseif (!is_array($IDs)) {
110 } elseif (count($IDs) == 0) {
115 // Set to true to make AND expression valid if first URL got unlocked
118 // Update the status for all ids
119 foreach ($IDs as $id => $dummy) {
120 // Test all ids through (ignores failed)
121 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
124 // Return total status
128 // Admin function for rejecting URLs
129 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
130 // Is this an admin or invalid array?
132 // Not admin or invalid ids array
134 } elseif (!is_array($IDs)) {
137 } elseif (count($IDs) == 0) {
142 // Set to true to make AND expression valid if first URL got unlocked
145 // Update the status for all ids
146 foreach ($IDs as $id => $dummy) {
147 // Test all ids through (ignores failed)
148 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
151 // Return total status
156 //------------------------------------------------------------------------------
158 //------------------------------------------------------------------------------
160 // Member has added an URL
161 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
162 // Do some pre-checks
166 } elseif ((!isUrlValid($url)) && (!isAdmin())) {
169 } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
170 // URL already found in surfbar!
172 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
175 } elseif (''.($limit + 0).'' != ''.$limit.'') {
176 // Invalid amount entered
180 // Register the new URL
181 return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
184 // Create list of actions depending on status for the user
185 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
186 // Load all actions in an array for given status
187 $actionArray = SURFBAR_GET_ARRAY_FROM_STATUS($status);
190 $OUT = '<table border="0" cellspacing="0" cellpadding="1" width="100%">
194 $width = round(100 / count($actionArray));
196 // "Walk" through all actions and create forms
197 foreach ($actionArray as $actionId => $action) {
198 // Add form for this action
199 $OUT .= loadTemplate('member_surfbar_list_form', true, array(
201 'url_id' => bigintval($urlId),
202 'action' => strtolower($action)
214 // Do the member form request
215 function SURFBAR_MEMBER_DO_FORM ($formData, $urlArray) {
216 // By default no action is performed
223 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
224 // Important form elements are missing!
226 } elseif (!isset($urlArray[$formData['id']])) {
227 // id not found in cache
229 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $urlArray[$formData['id']]['url_status'])) {
230 // Action not allowed for current URL status
235 $action = secureString($formData['action']);
238 if ($action != $formData['action']) {
239 // Invalid data in action found
243 // Create the function name for selected action
244 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
246 // Is the function there?
247 if (function_exists($functionName)) {
249 $urlArray[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
251 // Extract URL data for call-back
252 $urlData = array(merge_array($urlArray[$formData['id']], array($action => $formData)));
254 // Action found so execute it
255 $performed = call_user_func_array($functionName, $urlData);
257 // Log invalid request
258 logDebugMessage(__FUNCTION__, __LINE__, "action={$formData['action']},id={$formData['id']},function={$functionName}");
259 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
266 // Validate if the requested action can be performed on current URL status
267 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
268 // Search for the requested action/status combination in database
269 $result = SQL_QUERY_ESC("SELECT `actions_new_status` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_action`='%s' AND `actions_status`='%s' LIMIT 1",
270 array($action, $status), __FUNCTION__, __LINE__);
272 // Is the entry there?
273 $isValid = (SQL_NUMROWS($result) == 1);
275 // Fetch the new status if found
278 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
282 SQL_FREERESULT($result);
289 //------------------------------------------------------------------------------
291 //------------------------------------------------------------------------------
293 // Retreat a booked URL
294 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
295 // Create the data array for next function call
297 $urlData['id'] => $urlData
300 // Simply change the status here
301 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
304 // Book an URL now (from migration)
305 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
306 // Create the data array for next function call
308 $urlData['id'] => $urlData
311 // Simply change the status here
312 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
315 // Show edit form or do the changes
316 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
317 // Is the "execute" flag there?
318 if (isset($urlData['edit']['execute'])) {
319 // Execute the changes
320 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
324 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
327 // Show delete form or do the changes
328 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
329 // Is the "execute" flag there?
330 if (isset($urlData['delete']['execute'])) {
331 // Execute the changes
332 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
336 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
339 // Pause active banner
340 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
341 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
344 // Unpause stopped banner
345 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
346 // Fix missing entry for template
347 $urlData['edit'] = $urlData['unpause'];
348 $urlData['edit']['url'] = $urlData['url'];
349 $urlData['edit']['limit'] = SURFBAR_GET_VIEWS_MAX();
351 // Return status change
352 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
355 // Resubmit locked URL
356 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
357 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
360 // Display selected "action form"
361 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
362 // Translate some data if present
363 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
365 // Include fields only for action 'edit'
366 if ($action == 'edit') {
367 // Default is not limited
368 $urlData['limited_yes'] = '';
369 $urlData['limited_no'] = ' checked="checked"';
370 $urlData['limited'] = 'false';
372 // Is this URL limited?
373 if (SURFBAR_GET_VIEWS_MAX() > 0) {
374 // Then rewrite form data
375 $urlData['limited_yes'] = ' checked="checked"';
376 $urlData['limited_no'] = '';
377 $urlData['limited'] = 'true';
381 // Load the form and display it
382 loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
384 // All fine by default ... ;-)
388 // Execute choosen action
389 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
390 // By default nothing is executed
393 // Is limitation "no" and "limit" is > 0?
394 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
395 // Set it to unlimited
396 $urlData[$action]['limit'] = '0';
399 // Construct function name
400 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
402 // Is that function there?
403 if (function_exists($functionName)) {
404 // Execute the function
405 if (call_user_func_array($functionName, array($urlData)) == true) {
406 // Update status as well
407 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
411 addFatalMessage(__FUNCTION__, __LINE__, '{--MEMBER_SURFBAR_EXECUTE_ACTION_404--}', $functionName);
417 // "Execute edit" function: Update changed data
418 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
419 // Default is nothing done
422 // Has the URL or limit changed?
424 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
426 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",
427 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['url_status']), __FUNCTION__, __LINE__);
436 // "Execute delete" function: Does nothing...
437 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
438 // Nothing special to do (see above function for such "special actions" to perform)
442 //------------------------------------------------------------------------------
443 // Self-maintenance functions
444 //------------------------------------------------------------------------------
447 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
448 // Handle URLs which limit has depleted so we can stop them
449 SURFBAR_HANDLE_DEPLETED_VIEWS();
451 // Handle low-points amounts
452 SURFBAR_HANDLE_LOW_POINTS();
454 // Handle URLs which limit has depleted
455 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
457 $urlArray = SURFBAR_GET_URL_DATA(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
459 // Do we have some entries?
460 if (count($urlArray) > 0) {
462 foreach ($urlArray as $id => $urlData) {
466 // Rewrite array for next call
467 $urlData[$id] = $data;
470 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
475 // Alert users which have URLs booked and are low on points amount
476 function SURFBAR_HANDLE_LOW_POINTS () {
478 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
480 // "Walk" through all URLs
481 foreach ($userids['url_userid'] as $userid => $dummy) {
482 // Is the last notification far enougth away to notify again?
483 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
486 'url_userid' => $userid,
487 'points' => $userids['points'][$userid],
488 'notified' => $userids['notified'][$userid]
492 SURFBAR_NOTIFY_USER('low_points', $content);
494 // Update last notified
495 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
496 array($userid), __FUNCTION__, __LINE__);
502 //------------------------------------------------------------------------------
504 //------------------------------------------------------------------------------
507 // Looks up by an URL
508 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
509 // Now lookup that given URL by itself
510 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
513 return (count($urlArray) > 0);
516 // Load URL data by given search term and column
517 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
518 // By default nothing is found
519 $GLOBALS['last_url_data'] = array();
521 // Is the column an id number?
522 if (($column == 'url_id') || ($column == 'url_userid')) {
523 // Extra secure input
524 $searchTerm = bigintval($searchTerm);
527 // If the column is 'id' there can be only one entry
529 if ($column == 'id') {
533 // Look up the record
534 $result = SQL_QUERY_ESC("SELECT
542 UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
543 UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
549 `{?_MYSQL_PREFIX?}_surfbar_urls`
551 `%s`='%s'" . $add . "
561 ), __FUNCTION__, __LINE__);
563 // Is there at least one record?
564 if (!SQL_HASZERONUMS($result)) {
566 while ($dataRow = SQL_FETCHARRAY($result)) {
567 // Shall we group these results?
568 if ($group == 'url_id') {
569 // Add the row by id as index
570 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
573 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
579 SQL_FREERESULT($result);
582 return $GLOBALS['last_url_data'];
585 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
586 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
587 // Make sure by the user registered URLs are always pending
588 if ($addMode == 'reg') {
593 $content = merge_array($extraFields, array(
595 'url_userid' => $userid,
596 'url_status' => $status,
599 // Is limit/reload set?
600 if (!isset($config['limit'])) {
601 $content['limit'] = '0';
603 if (!isset($config['reload'])) {
604 $content['reload'] = '0';
607 // Insert the URL into database
608 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
611 if ($content['insert_id'] == '0') {
612 // INSERT did not insert any data!
616 // If in reg-mode we notify admin
617 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
618 // Notify admin even when he as unlocked an email
619 SURFBAR_NOTIFY_ADMIN('url_' . $addMode, $content);
623 SURFBAR_NOTIFY_USER('url_' . $addMode, $content);
625 // Return the insert id
626 return $content['insert_id'];
629 // Inserts an url by given data array and return the insert id
630 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
632 $userid = bigintval($urlData['url_userid']);
635 if (empty($userid)) $userid = '0';
637 // Just run the insert query for now
638 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)",
642 $urlData['url_status'],
646 ), __FUNCTION__, __LINE__
650 return SQL_INSERTID();
653 // Notify admin(s) with a selected message and content
654 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
655 // Prepare template name
656 $templateName = sprintf("admin_surfbar_%s", $messageType);
659 $subject = sprintf("{--ADMIN_SURFBAR_NOTIFY_%s_SUBJECT--}",
660 strtoupper($messageType)
663 // Is the subject line there?
664 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
665 // Set default subject if following eval() wents wrong
666 $subject = '{%message,ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT=' . strtoupper($messageType) . '%}';
669 // Translate some data if present
670 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
672 // Send the notification out
673 return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
676 // Notify the user about the performed action
677 function SURFBAR_NOTIFY_USER ($messageType, $content) {
678 // Skip notification if userid is zero
679 if ($content['url_userid'] == '0') {
683 // Prepare template name
684 $templateName = sprintf("member_surfbar_%s", $messageType);
687 $subject = sprintf("{--MEMBER_SURFBAR_NOTIFY_%s_SUBJECT--}",
688 strtoupper($messageType)
691 // Is the subject line there?
692 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
693 // Set default subject if following eval() wents wrong
694 $subject = '{--MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT--}';
697 // Translate some data if present
698 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
701 $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
704 return sendEmail($content['url_userid'], $subject, $mailText);
707 // Translates some data for template usage
708 // @TODO Can't we use our new expression language instead of this ugly code?
709 function SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE ($content) {
711 if (isset($content['url_registered'])) $content['url_registered'] = generateDateTime($content['url_registered'], 2);
712 if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
714 // Return translated content
718 // Translates the limit
719 function translateSurfbarLimit ($limit) {
723 $return = '{--MEMBER_SURFBAR_UNLIMITED_VIEWS--}';
726 $return = '{%pipe,translateComma=' . $limit . '%}';
733 // Translate the URL status
734 function translateSurfbarUrlStatus ($status) {
735 // NULL must be handled carfefully
736 if (is_null($status)) {
737 // Is NULL, so return other language string
738 return '{--SURFBAR_URL_STATUS_NONE--}';
740 // Return regular result
741 return sprintf("{--SURFBAR_URL_STATUS_%s--}", strtoupper($status));
745 // Translates the given action into a link title for members
746 function translateMemberSurfbarActionToTitle ($action) {
748 if (!isset($GLOBALS[__FUNCTION__][$action])) {
749 // Construct default return string (unknown
750 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_TITLE=' . $action . '%}';
752 // ... and the id's name
753 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE';
756 if (isMessageIdValid($messageId)) {
758 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
763 return $GLOBALS[__FUNCTION__][$action];
766 // Translates the given action into a submit button for members
767 function translateMemberSurfbarActionToSubmit ($action) {
769 if (!isset($GLOBALS[__FUNCTION__][$action])) {
770 // Construct default return string (unknown
771 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_SUBMIT=' . $action . '%}';
773 // ... and the id's name
774 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT';
777 if (isMessageIdValid($messageId)) {
779 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
784 return $GLOBALS[__FUNCTION__][$action];
788 function SURFBAR_DETERMINE_REWARD ($onlyMin = false) {
789 // Static values are default
790 $reward = getConfig('surfbar_static_reward');
792 // Do we have static or dynamic?
793 if (getSurfbarPaymentModel() == 'DYNAMIC') {
794 // "Calculate" dynamic reward
795 if ($onlyMin === true) {
796 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
798 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
807 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
808 // Static costs is default
809 $costs = getConfig('surfbar_static_costs');
811 // Do we have static or dynamic?
812 if (getSurfbarPaymentModel() == 'DYNAMIC') {
813 // "Calculate" dynamic costs
815 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
817 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
825 // "Calculate" dynamic add
826 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
827 // Get min/max values
828 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
829 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
831 // "Calculate" dynamic part and return it
832 return mt_rand($min, $max);
835 // Determine right template name
836 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
837 // Default is the frameset
838 $templateName = 'surfbar_frameset';
840 // Any frame set? ;-)
841 if (isGetRequestParameterSet('frame')) {
842 // Use the frame as a template name part... ;-)
843 $templateName = sprintf("surfbar_frame_%s",
844 getRequestParameter('frame')
849 return $templateName;
852 // Check if the "reload lock" of the current user is full, call this function
853 // before you call SURFBAR_CHECK_RELOAD_LOCK().
854 function SURFBAR_CHECK_RELOAD_FULL () {
858 // Cache static reload lock
859 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
860 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
862 // Do we have dynamic model?
863 if (getSurfbarPaymentModel() == 'DYNAMIC') {
864 // "Calculate" dynamic lock
865 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
869 $result = SQL_QUERY_ESC("SELECT
870 COUNT(l.`locks_id`) AS `cnt`
872 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
874 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
876 u.`url_id`=l.`locks_url_id`
878 l.`locks_userid`=%s AND
879 (UNIX_TIMESTAMP() - {%%pipe,SURFBAR_GET_SURF_LOCK%%}) < UNIX_TIMESTAMP(l.`locks_last_surfed`) AND
881 ((UNIX_TIMESTAMP(l.`locks_last_surfed`) - u.`url_fixed_reload`) < 0 AND u.`url_fixed_reload` > 0) OR
882 u.`url_fixed_reload` = 0
885 array(getMemberId()), __FUNCTION__, __LINE__
889 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
892 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
893 // Then fix it to zero!
894 $GLOBALS['surfbar_cache']['user_locks'] = '0';
898 SQL_FREERESULT($result);
901 $total = SURFBAR_GET_TOTAL_URLS();
903 // Do we have some URLs in lock? Admins can always surf on own URLs!
904 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
905 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
911 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
912 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
913 // Determine depleted user account
914 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
916 // If we dont get any user ids back, there are no URLs
917 if (count($userids['url_userid']) == 0) {
918 // No user ids found, no URLs!
922 // Is the exlude userid set?
923 if (isValidUserId($excludeUserId)) {
925 $userids['url_userid'][$excludeUserId] = $excludeUserId;
928 // Get amount from database
929 $result = SQL_QUERY_ESC("SELECT
930 COUNT(`url_id`) AS cnt
932 `{?_MYSQL_PREFIX?}_surfbar_urls`
934 `url_userid` NOT IN (".implode(', ', $userids['url_userid']).") AND
937 array($status), __FUNCTION__, __LINE__
941 list($count) = SQL_FETCHROW($result);
944 SQL_FREERESULT($result);
947 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $count);
953 // Check wether the user is allowed to book more URLs
954 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
955 // Is this admin and userid is zero or does the user has some URLs left to book?
956 return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getSurfbarMaxOrder()));
959 // Get total amount of URLs of given status for current user
960 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '', $exclude = '') {
961 // Is the user 0 and user is logged in?
962 if (($userid == '0') && (isMember())) {
963 // Then use this userid
964 $userid = getMemberId();
965 } elseif ($userid == '0') {
967 return (getSurfbarMaxOrder() + 1);
970 // Default is all URLs
973 // Is the status set?
974 if (is_array($status)) {
975 // Only URLs with these status
976 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
977 } elseif (!empty($status)) {
978 // Only URLs with this status
979 $add = sprintf(" AND `url_status`='%s'", $status);
980 } elseif (is_array($exclude)) {
981 // Exclude URLs with these status
982 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
983 } elseif (!empty($exclude)) {
984 // Exclude URLs with this status
985 $add = sprintf(" AND `url_status` != '%s'", $exclude);
988 // Get amount from database
989 $count = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
995 // Generate a validation code for the given id number
996 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
997 // @TODO Invalid salt should be refused
999 $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
1001 // Is extension ext-other there?
1002 if (isExtensionActive('other')) {
1003 // Get code length from config
1004 $length = getCodeLength();
1008 if ($length == '0') {
1012 // Generate a code until the length matches
1014 while (strlen($valCode) != $length) {
1017 // Generate random hashed string
1018 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
1019 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
1021 // Use this as salt!
1022 $GLOBALS['surfbar_cache']['salt'] = $salt;
1023 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
1026 // ... and now the validation code
1027 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT() . getEncryptSeperator() . $urlId), getMemberId());
1028 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
1031 // Hash it with md5() and salt it with the random string
1032 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
1034 // Finally encrypt it PGP-like and return it
1035 $valHashedCode = encodeHashForCookie($hashedCode);
1037 // Return hashed value
1038 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
1039 return $valHashedCode;
1042 // Check validation code
1043 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
1045 $urlId = bigintval($urlId);
1047 // Now generate the code again
1048 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1050 // Return result of checking hashes and salts
1051 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1052 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('salts_last_salt').'+++', false);
1053 return (($code == $check) && ($salt == SURFBAR_GET_DATA('salts_last_salt')));
1056 // Lockdown the userid/id combination (reload lock)
1057 function SURFBAR_LOCKDOWN_ID ($urlId) {
1058 //* DEBUG: */ debugOutput('LOCK!');
1059 ///* DEBUG: */ return;
1060 // Just add it to the database
1061 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)",
1062 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1064 // Remove the salt from database
1065 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1066 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1069 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1070 function SURFBAR_PAY_POINTS () {
1071 // Remove it from the URL owner
1072 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1073 if (isValidUserId(SURFBAR_GET_USERID())) {
1074 subtractPoints(sprintf("surfbar_%s", getSurfbarPaymentModel()), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1077 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1078 // @TODO Try to rewrite the following unset()
1079 unset($GLOBALS['ref_level']);
1081 // Book it to the user
1082 addPointsThroughReferalSystem(sprintf("surfbar_%s", getSurfbarPaymentModel()), getMemberId(), SURFBAR_GET_REWARD());
1085 // Updates the statistics of current URL/userid
1086 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1090 // Get allowed views
1091 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1093 // Do we have a limit?
1095 // Then count views_max down!
1096 $add .= ", `views_max`=`views_max`-1";
1100 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1".$add." WHERE `url_id`=%s LIMIT 1",
1101 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1103 // Update the stats entry
1104 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",
1108 ), __FUNCTION__, __LINE__);
1110 // Was that update okay?
1111 if (SQL_HASZEROAFFECTED()) {
1112 // No, then insert entry
1113 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)",
1117 ), __FUNCTION__, __LINE__);
1120 // Update total/daily/weekly/monthly counter
1121 incrementConfigEntry('surfbar_total_counter');
1122 incrementConfigEntry('surfbar_daily_counter');
1123 incrementConfigEntry('surfbar_weekly_counter');
1124 incrementConfigEntry('surfbar_monthly_counter');
1126 // Update config as well
1127 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1130 // Update the salt for validation and statistics
1131 function SURFBAR_UPDATE_SALT_STATS () {
1132 // Update statistics record
1133 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1136 SURFBAR_GENERATE_VALIDATION_CODE(SURFBAR_GET_ID());
1138 // Simply store the salt from cache away in database...
1139 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1144 ), __FUNCTION__, __LINE__);
1147 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1150 if (SQL_HASZEROAFFECTED()) {
1151 // Insert missing entry!
1152 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1153 array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1157 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1159 // Return if the update was okay
1160 return (!SQL_HASZEROAFFECTED());
1163 // Check if the reload lock is active for given id
1164 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1165 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1167 $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1169 `{?_MYSQL_PREFIX?}_surfbar_locks`
1171 `locks_userid`=%s AND
1172 `locks_url_id`=%s AND
1173 (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1175 `locks_last_surfed` ASC
1177 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1181 list($count) = SQL_FETCHROW($result);
1184 SQL_FREERESULT($result);
1187 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $count . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1188 return ($count == 1);
1191 // Determine which user hash no more points left
1192 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1195 'url_userid' => array(),
1196 'points' => array(),
1197 'notified' => array(),
1200 // Do we have a current user id?
1201 if ((isMember()) && ($limit == '0')) {
1202 // Then add this as well
1203 $userids['url_userid'][getMemberId()] = getMemberId();
1204 $userids['points'][getMemberId()] = getTotalPoints(getMemberId());
1205 $userids['notified'][getMemberId()] = '0';
1207 // Get all userid except logged in one
1208 $result = SQL_QUERY_ESC("SELECT
1209 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1211 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1213 `{?_MYSQL_PREFIX?}_user_data` AS d
1215 u.`url_userid`=d.`userid`
1217 u.`url_userid` NOT IN (%s,0) AND
1218 u.`url_status`='ACTIVE'
1222 u.`url_userid` ASC",
1223 array(getMemberId()), __FUNCTION__, __LINE__);
1226 $result = SQL_QUERY("SELECT
1227 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1229 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1231 `{?_MYSQL_PREFIX?}_user_data` AS d
1233 u.`url_userid`=d.`userid`
1235 u.`url_userid` > 0 AND
1236 u.`url_status`='ACTIVE'
1240 u.`url_userid` ASC", __FUNCTION__, __LINE__);
1244 while ($content = SQL_FETCHARRAY($result)) {
1246 $points = getTotalPoints($content['url_userid']);
1247 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['url_userid']},points={$points}", false);
1249 // Shall we add this to ignore?
1250 if ($points <= $limit) {
1252 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['url_userid']} has depleted points amount!", false);
1253 $userids['url_userid'][$content['url_userid']] = $content['url_userid'];
1254 $userids['points'][$content['url_userid']] = $points;
1255 $userids['notified'][$content['url_userid']] = $content['notified'];
1260 SQL_FREERESULT($result);
1263 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1269 // Determine how many users are Online in surfbar
1270 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1271 // Count all users in surfbar modue and return the value
1272 $result = SQL_QUERY('SELECT
1275 `{?_MYSQL_PREFIX?}_surfbar_stats`
1277 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1279 `stats_userid` ASC', __FUNCTION__, __LINE__);
1282 $count = SQL_NUMROWS($result);
1285 SQL_FREERESULT($result);
1291 // Determine waiting time for one URL
1292 function SURFBAR_DETERMINE_WAIT_TIME () {
1293 // Get fixed reload lock
1294 $fixed = SURFBAR_GET_FIXED_RELOAD();
1296 // Is the fixed reload time set?
1302 // Static time is default
1303 $time = getConfig('surfbar_static_time');
1305 // Which payment model do we have?
1306 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1307 // "Calculate" dynamic time
1308 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1315 // Changes the status of an URL from given to other
1316 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1317 // Make new status always lower-case
1318 $newStatus = strtolower($newStatus);
1320 // Get URL data for status comparison if missing
1321 if ((!is_array($data)) || (count($data) == 0)) {
1322 // Fetch missing URL data
1323 $data = SURFBAR_GET_URL_DATA($urlId);
1326 // Is the new status set?
1327 if ((!is_string($newStatus)) || (empty($newStatus))) {
1328 // Abort here, but fine!
1332 // Is the status like prevStatus is saying?
1333 if ($data[$urlId]['url_status'] != $prevStatus) {
1334 // No, then abort here
1339 // Update the status now
1340 // ---------- Comment out for debugging/developing member actions! ---------
1341 //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `url_id`=%s LIMIT 1",
1342 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1343 // ---------- Comment out for debugging/developing member actions! ---------
1346 // ---------- Comment out for debugging/developing member actions! ---------
1347 //if (SQL_AFFECTEDROWS() != 1) {
1348 // // No, something went wrong
1351 // ---------- Comment out for debugging/developing member actions! ---------
1353 // Prepare content for notification routines
1354 $data[$urlId]['url_userid'] = $data[$urlId]['url_userid'];
1355 $data[$urlId]['frametester'] = '{%pipe,generateFrametesterUrl=' . $data[$urlId]['url'] . '%}';
1356 $data[$urlId]['reward'] = '{%config,translateComma=surfbar_static_reward%}';
1357 $data[$urlId]['costs'] = '{%config,translateComma=surfbar_static_costs%}';
1359 // Do some dirty fixing here:
1360 if (($data[$urlId]['url_status'] == 'STOPPED') && ($newStatus == 'pending')) {
1361 // Fix for template change
1362 $newStatus = 'continued';
1365 // Send admin notification
1366 SURFBAR_NOTIFY_ADMIN('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1368 // Send user notification
1369 SURFBAR_NOTIFY_USER('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1375 // Calculate minimum value for dynamic payment model
1376 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1377 // Addon is zero by default
1381 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1384 $totalUsers = getTotalConfirmedUser();
1387 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1390 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1393 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1395 // Get user's total URLs
1396 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1399 if ($totalUrls > 0) {
1400 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1402 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1409 // Calculate maximum value for dynamic payment model
1410 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1411 // Addon is zero by default
1418 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1421 $totalUsers = getTotalConfirmedUser();
1424 $addon += abs($max * $percent * $totalUsers);
1427 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1430 $addon += abs($max * $percent * $totalUrls);
1436 // Calculate dynamic lock
1437 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1438 // Default lock is 30 seconds
1442 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1445 $addon = abs(log($onlineUsers / $addon + 1));
1451 // "Getter" for lock ids array
1452 function SURFBAR_GET_LOCK_IDS () {
1453 // Prepare some arrays
1458 // Get all id from locks within the timestamp
1459 $result = SQL_QUERY_ESC("SELECT `locks_id`, `locks_url_id`, UNIX_TIMESTAMP(`locks_last_surfed`) AS last_surfed
1461 `{?_MYSQL_PREFIX?}_surfbar_locks`
1465 `locks_id` ASC", array(getMemberId()),
1466 __FUNCTION__, __LINE__);
1469 while ($content = SQL_FETCHARRAY($result)) {
1471 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1473 // Skip entries that are too old
1474 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1476 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1478 // Add only if missing or bigger
1479 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1481 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1484 $IDs[$content['url_id']] = $content['last_surfed'];
1485 $USE[$content['url_id']] = $content['id'];
1489 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1491 // Ignore these old entries!
1492 $ignored[] = $content['url_id'];
1493 unset($IDs[$content['url_id']]);
1494 unset($USE[$content['url_id']]);
1499 SQL_FREERESULT($result);
1505 // "Getter" for maximum random number
1506 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1507 // Count max availabe entries
1508 $result = SQL_QUERY("SELECT
1511 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1513 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1515 sbu.url_id=sbs.salts_url_id
1517 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1519 sbu.url_id=l.locks_url_id
1521 sbu.url_userid NOT IN (" . implode(',', $userids) . ") AND
1522 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1523 sbu.url_status='ACTIVE'
1526 sbu.url_id ASC", __FUNCTION__, __LINE__);
1529 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1532 $maxRand = SQL_NUMROWS($result);
1535 SQL_FREERESULT($result);
1541 // Load all URLs of the current user and return it as an array
1542 function SURFBAR_GET_USER_URLS () {
1544 $urlArray = array();
1547 $result = SQL_QUERY_ESC("SELECT
1554 u.url_views_allowed,
1555 UNIX_TIMESTAMP(u.url_registered) AS `url_registered`,
1556 UNIX_TIMESTAMP(u.`url_last_locked`) AS `url_last_locked`,
1559 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1561 u.`url_userid`=%s AND
1562 u.`url_status` != 'DELETED'
1565 array(getMemberId()), __FUNCTION__, __LINE__);
1567 // Are there entries?
1568 if (!SQL_HASZERONUMS($result)) {
1570 while ($row = SQL_FETCHARRAY($result)) {
1572 $urlArray[$row['url_id']] = $row;
1577 SQL_FREERESULT($result);
1583 // "Getter" for member action array for given status
1584 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1586 $returnArray = array();
1588 // Get all assigned actions
1589 $result = SQL_QUERY_ESC("SELECT `actions_action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1590 array($status), __FUNCTION__, __LINE__);
1592 // Some entries there?
1593 if (!SQL_HASZERONUMS($result)) {
1595 // @TODO This can be somehow rewritten
1596 while ($content = SQL_FETCHARRAY($result)) {
1597 $returnArray[] = $content['actions_action'];
1602 SQL_FREERESULT($result);
1605 return $returnArray;
1608 // Reload to configured stop page
1609 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1610 // Internal or external?
1611 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1612 // Reload to internal page
1613 redirectToUrl('surfbar.php?frame=' . $page);
1615 // Reload to external page
1616 redirectToConfiguredUrl('surfbar_pause_url');
1620 // Determine next id for surfbar or get data for given id, always call this before you call other
1621 // getters below this function!
1622 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1623 // Default is no id and no random number
1628 if ($urlId == '0') {
1629 // Get array with lock ids
1630 $USE = SURFBAR_GET_LOCK_IDS();
1632 // Shall we add some URL ids to ignore?
1634 if (count($USE) > 0) {
1636 $add = " AND sbu.`url_id` NOT IN (";
1637 foreach ($USE as $url_id => $lid) {
1639 $add .= $url_id.',';
1642 // Add closing bracket
1643 $add = substr($add, 0, -1) . ')';
1646 // Determine depleted user account
1647 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1649 // Get maximum randomness factor
1650 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['url_userid'], $add);
1652 // If more than one URL can be called generate the random number!
1654 // Generate random number
1655 $randNum = mt_rand(0, ($maxRand - 1));
1658 // And query the database
1659 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1660 $result = SQL_QUERY_ESC("SELECT
1664 sbs.salts_last_salt,
1665 sbu.url_views_total,
1667 sbu.url_views_allowed,
1668 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1669 sbu.url_fixed_reload
1671 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1673 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1675 sbu.url_id=sbs.salts_url_id
1677 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1679 sbu.url_id=l.locks_url_id
1681 sbu.`url_userid` NOT IN (".implode(',', $userids['url_userid']).") AND
1682 sbu.url_status='ACTIVE' AND
1683 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1688 l.locks_last_surfed ASC,
1691 array($randNum), __FUNCTION__, __LINE__
1694 // Get data from specified id number
1695 $result = SQL_QUERY_ESC("SELECT
1699 sbs.salts_last_salt,
1700 sbu.url_views_total,
1702 sbu.url_views_allowed,
1703 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1704 sbu.url_fixed_reload
1706 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1708 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1710 sbu.url_id=sbs.salts_url_id
1712 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1714 sbu.url_id=l.locks_url_id
1716 sbu.url_userid != %s AND
1717 sbu.url_status='ACTIVE' AND
1719 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1721 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1725 // Is there an id number?
1726 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1727 if (SQL_NUMROWS($result) == 1) {
1729 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1730 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1731 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1733 // Determine waiting time
1734 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1736 // Is the last salt there?
1737 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1738 // Then repair it wit the static!
1739 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1740 $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1743 // Fix missing last_surfed
1744 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1746 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1747 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1750 // Get base/fixed reward and costs
1751 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1752 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1753 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1755 // Only in dynamic model add the dynamic bonus!
1756 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1757 // Calculate dynamic reward/costs and add it
1758 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1759 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1760 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1764 $nextId = SURFBAR_GET_ID();
1768 SQL_FREERESULT($result);
1771 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1775 //-----------------------------------------------------------------------------
1777 //-----------------------------------------------------------------------------
1779 // "Getter" for surfbar_dynamic_percent
1780 function getSurfbarDynamicPercent () {
1781 // Do we have cache?
1782 if (!isset($GLOBALS[__FUNCTION__])) {
1784 $GLOBALS[__FUNCTION__] = getConfig('surfbar_dynamic_percent');
1788 return $GLOBALS[__FUNCTION__];
1791 // "Getter" for surfbar_static_reward
1792 function getSurfbarStaticReward () {
1793 // Do we have cache?
1794 if (!isset($GLOBALS[__FUNCTION__])) {
1796 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_reward');
1800 return $GLOBALS[__FUNCTION__];
1803 // "Getter" for surfbar_static_time
1804 function getSurfbarStaticTime () {
1805 // Do we have cache?
1806 if (!isset($GLOBALS[__FUNCTION__])) {
1808 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_time');
1812 return $GLOBALS[__FUNCTION__];
1815 // "Getter" for surfbar_max_order
1816 function getSurfbarMaxOrder () {
1817 // Do we have cache?
1818 if (!isset($GLOBALS[__FUNCTION__])) {
1820 $GLOBALS[__FUNCTION__] = getConfig('surfbar_max_order');
1824 return $GLOBALS[__FUNCTION__];
1827 // "Getter" for surfbar_payment_model
1828 function getSurfbarPaymentModel () {
1829 // Do we have cache?
1830 if (!isset($GLOBALS[__FUNCTION__])) {
1832 $GLOBALS[__FUNCTION__] = getConfig('surfbar_payment_model');
1836 return $GLOBALS[__FUNCTION__];
1839 //------------------------------------------------------------------------------
1840 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1841 // THE $GLOBALS['surfbar_cache'] ARRAY!
1842 //------------------------------------------------------------------------------
1844 // Initializes the surfbar
1845 function SURFBAR_INIT () {
1847 $GLOBALS['surfbar_cache'] = array();
1850 // Private getter for data elements
1851 function SURFBAR_GET_DATA ($element) {
1852 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1857 // Is the entry there?
1858 if (isset($GLOBALS['surfbar_cache'][$element])) {
1860 $data = $GLOBALS['surfbar_cache'][$element];
1861 } else { // END - if
1863 print_r($GLOBALS['surfbar_cache']);
1865 debug_report_bug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
1869 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data, false);
1873 // Getter for reward from cache
1874 function SURFBAR_GET_REWARD () {
1875 // Get data element and return its contents
1876 return SURFBAR_GET_DATA('reward');
1879 // Getter for costs from cache
1880 function SURFBAR_GET_COSTS () {
1881 // Get data element and return its contents
1882 return SURFBAR_GET_DATA('costs');
1885 // Getter for URL from cache
1886 function SURFBAR_GET_URL () {
1887 // Get data element and return its contents
1888 return SURFBAR_GET_DATA('url');
1891 // Getter for salt from cache
1892 function SURFBAR_GET_SALT () {
1893 // Get data element and return its contents
1894 return SURFBAR_GET_DATA('salt');
1897 // Getter for id from cache
1898 function SURFBAR_GET_ID () {
1899 // Get data element and return its contents
1900 return SURFBAR_GET_DATA('url_id');
1903 // Getter for userid from cache
1904 function SURFBAR_GET_USERID () {
1905 // Get data element and return its contents
1906 return SURFBAR_GET_DATA('url_userid');
1909 // Getter for user reload locks
1910 function SURFBAR_GET_USER_LOCKS () {
1911 // Get data element and return its contents
1912 return SURFBAR_GET_DATA('user_locks');
1915 // Getter for reload time
1916 function SURFBAR_GET_RELOAD_TIME () {
1917 // Get data element and return its contents
1918 return SURFBAR_GET_DATA('time');
1921 // Getter for allowed views
1922 function SURFBAR_GET_VIEWS_ALLOWED () {
1923 // Get data element and return its contents
1924 return SURFBAR_GET_DATA('url_views_allowed');
1927 // Getter for maximum views
1928 function SURFBAR_GET_VIEWS_MAX () {
1929 // Get data element and return its contents
1930 return SURFBAR_GET_DATA('url_views_max');
1933 // Getter for fixed reload
1934 function SURFBAR_GET_FIXED_RELOAD () {
1935 // Get data element and return its contents
1936 return SURFBAR_GET_DATA('url_fixed_reload');
1939 // Getter for surf lock
1940 function SURFBAR_GET_SURF_LOCK () {
1941 // Get data element and return its contents
1942 return SURFBAR_GET_DATA('surf_lock');
1945 // Getter for new status
1946 function SURFBAR_GET_NEW_STATUS () {
1947 // Get data element and return its contents
1948 return SURFBAR_GET_DATA('new_status');