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 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: Not admin.", $url, $limit, $reload));
54 } elseif (!isUrlValid($url)) {
56 /* DEBUG: */ 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 /* DEBUG: */ 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 /* DEBUG: */ 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 /* DEBUG: */ 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 /* DEBUG: */ 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) {
85 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Not admin, url=' . $url . ',userid=' . $userid);
87 } elseif (!isUrlValid($url)) {
89 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Invalid URL, url=' . $url . ',userid=' . $userid);
91 } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
92 // URL already found in surfbar!
93 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Already added, url=' . $url . ',userid=' . $userid);
95 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
97 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Maximum exceeded, url=' . $url . ',userid=' . $userid);
101 // Register the new URL
102 return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
105 // Admin function for unlocking URLs
106 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
107 // Is this an admin or invalid array?
109 // Not admin or invalid ids array
110 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not admin');
112 } elseif (!is_array($IDs)) {
114 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs type ' . gettype($IDs) . '!=array');
116 } elseif (count($IDs) == 0) {
118 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs is empty');
122 // Set to true to make AND expression valid if first URL got unlocked
125 // Update the status for all ids
126 foreach ($IDs as $id => $dummy) {
127 // Test all ids through (ignores failed)
128 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
131 // Return total status
135 // Admin function for rejecting URLs
136 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
137 // Is this an admin or invalid array?
139 // Not admin or invalid ids array
140 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not admin');
142 } elseif (!is_array($IDs)) {
144 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs type ' . gettype($IDs) . '!=array');
146 } elseif (count($IDs) == 0) {
148 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs is empty');
152 // Set to true to make AND expression valid if first URL got unlocked
155 // Update the status for all ids
156 foreach ($IDs as $id => $dummy) {
157 // Test all ids through (ignores failed)
158 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
161 // Return total status
166 //------------------------------------------------------------------------------
168 //------------------------------------------------------------------------------
170 // Member has added an URL
171 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
172 // Do some pre-checks
175 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not member');
177 } elseif ((!isUrlValid($url)) && (!isAdmin())) {
179 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid, url=' . $url . ',limit=' . $limit);
181 } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
182 // URL already found in surfbar!
183 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Already found, url=' . $url . ',limit=' . $limit);
185 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
187 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Maximum exceeded, url=' . $url . ',limit=' . $limit);
189 } elseif (''.($limit + 0).'' != ''.$limit.'') {
190 // Invalid amount entered
191 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid limit, url=' . $url . ',limit=' . $limit);
195 // Register the new URL
196 return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
199 // Create list of actions depending on status for the user
200 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
201 // Load all actions in an array for given status
202 $actionArray = SURFBAR_GET_ARRAY_FROM_STATUS($status);
205 $OUT = '<table border="0" cellspacing="0" cellpadding="1" width="100%">
209 $width = round(100 / count($actionArray));
211 // "Walk" through all actions and create forms
212 foreach ($actionArray as $actionId => $action) {
213 // Add form for this action
214 $OUT .= loadTemplate('member_list_surfbar_form', true, array(
216 'url_id' => bigintval($urlId),
217 'action' => strtolower($action)
229 // Do the member form request
230 function SURFBAR_MEMBER_DO_FORM ($formData, $urlArray) {
231 // By default no action is performed
237 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not member');
239 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
240 // Important form elements are missing!
241 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid form data, required field id/action not found');
243 } elseif (!isset($urlArray[$formData['id']])) {
244 // Id not found in cache
245 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Field id not found in cache');
247 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $urlArray[$formData['id']]['url_status'])) {
248 // Action not allowed for current URL status
249 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Action not allowed to perform. action=' . $formData['action'] . ',url_status=' . $urlArray[$formData['id']]['url_status'] . 'id=' . $formData['id']);
254 $action = secureString($formData['action']);
257 if ($action != $formData['action']) {
258 // Invalid data in action found
262 // Create the function name for selected action
263 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
265 // Is the function there?
266 if (function_exists($functionName)) {
268 $urlArray[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
270 // Extract URL data for call-back
271 $urlData = array(merge_array($urlArray[$formData['id']], array($action => $formData)));
273 // Action found so execute it
274 $performed = call_user_func_array($functionName, $urlData);
276 // Log invalid request
277 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid member action! action=' . $formData['action'] . ',id=' . $formData['id'] . ',function=' . $functionName);
284 // Validate if the requested action can be performed on current URL status
285 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
286 // Search for the requested action/status combination in database
287 $result = SQL_QUERY_ESC("SELECT `actions_new_status` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_action`='%s' AND `actions_status`='%s' LIMIT 1",
288 array($action, $status), __FUNCTION__, __LINE__);
290 // Is the entry there?
291 $isValid = (SQL_NUMROWS($result) == 1);
293 // Fetch the new status if found
296 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
300 SQL_FREERESULT($result);
307 //------------------------------------------------------------------------------
309 //------------------------------------------------------------------------------
311 // Retreat a booked URL
312 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
313 // Create the data array for next function call
315 $urlData['id'] => $urlData
318 // Simply change the status here
319 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
322 // Book an URL now (from migration)
323 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
324 // Create the data array for next function call
326 $urlData['id'] => $urlData
329 // Simply change the status here
330 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
333 // Show edit form or do the changes
334 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
335 // Is the "execute" flag there?
336 if (isset($urlData['edit']['execute'])) {
337 // Execute the changes
338 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
342 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
345 // Show delete form or do the changes
346 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
347 // Is the "execute" flag there?
348 if (isset($urlData['delete']['execute'])) {
349 // Execute the changes
350 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
354 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
357 // Pause active banner
358 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
359 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
362 // Unpause stopped banner
363 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
364 // Fix missing entry for template
365 $urlData['edit'] = $urlData['unpause'];
366 $urlData['edit']['url'] = $urlData['url'];
367 $urlData['edit']['limit'] = SURFBAR_GET_VIEWS_MAX();
369 // Return status change
370 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
373 // Resubmit locked URL
374 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
375 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
378 // Display selected "action form"
379 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
380 // Translate some data if present
381 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
383 // Include fields only for action 'edit'
384 if ($action == 'edit') {
385 // Default is not limited
386 $urlData['limited_yes'] = '';
387 $urlData['limited_no'] = ' checked="checked"';
388 $urlData['limited'] = 'false';
390 // Is this URL limited?
391 if (SURFBAR_GET_VIEWS_MAX() > 0) {
392 // Then rewrite form data
393 $urlData['limited_yes'] = ' checked="checked"';
394 $urlData['limited_no'] = '';
395 $urlData['limited'] = 'true';
399 // Load the form and display it
400 loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
402 // All fine by default ... ;-)
406 // Execute choosen action
407 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
408 // By default nothing is executed
411 // Is limitation "no" and "limit" is > 0?
412 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
413 // Set it to unlimited
414 $urlData[$action]['limit'] = '0';
417 // Construct function name
418 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
420 // Is that function there?
421 if (function_exists($functionName)) {
422 // Execute the function
423 if (call_user_func_array($functionName, array($urlData)) == true) {
424 // Update status as well
425 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
429 debug_report_bug(__FUNCTION__, __LINE__, 'Callback function ' . $functionName . ' not found.');
435 // "Execute edit" function: Update changed data
436 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
437 // Default is nothing done
440 // Has the URL or limit changed?
442 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
444 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",
445 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['url_status']), __FUNCTION__, __LINE__);
454 // "Execute delete" function: Does nothing...
455 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
456 // Nothing special to do (see above function for such "special actions" to perform)
460 //------------------------------------------------------------------------------
461 // Self-maintenance functions
462 //------------------------------------------------------------------------------
465 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
466 // Handle URLs which limit has depleted so we can stop them
467 SURFBAR_HANDLE_DEPLETED_VIEWS();
469 // Handle low-points amounts
470 SURFBAR_HANDLE_LOW_POINTS();
473 // Handle URLs which limit has depleted
474 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
476 $urlArray = SURFBAR_GET_URL_DATA(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
478 // Do we have some entries?
479 if (count($urlArray) > 0) {
481 foreach ($urlArray as $id => $urlData) {
485 // Rewrite array for next call
491 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
496 // Alert users which have URLs booked and are low on points amount
497 function SURFBAR_HANDLE_LOW_POINTS () {
499 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
501 // "Walk" through all URLs
502 foreach ($userids['url_userid'] as $userid => $dummy) {
503 // Is the last notification far enougth away to notify again?
504 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
507 'url_userid' => $userid,
508 'points' => $userids['points'][$userid],
509 'notified' => $userids['notified'][$userid]
513 SURFBAR_NOTIFY_USER('low_points', $content);
515 // Update last notified
516 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
517 array($userid), __FUNCTION__, __LINE__);
523 //------------------------------------------------------------------------------
525 //------------------------------------------------------------------------------
528 // Looks up by an URL
529 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
530 // Now lookup that given URL by itself
531 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
534 return (count($urlArray) > 0);
537 // Load URL data by given search term and column
538 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
539 // By default nothing is found
540 $GLOBALS['last_url_data'] = array();
542 // Is the column an id number?
543 if (($column == 'url_id') || ($column == 'url_userid')) {
544 // Extra secure input
545 $searchTerm = bigintval($searchTerm);
548 // If the column is 'id' there can be only one entry
550 if ($column == 'id') {
554 // Look up the record
555 $result = SQL_QUERY_ESC("SELECT
563 UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
564 UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
570 `{?_MYSQL_PREFIX?}_surfbar_urls`
572 `%s`='%s'" . $add . "
582 ), __FUNCTION__, __LINE__);
584 // Is there at least one record?
585 if (!SQL_HASZERONUMS($result)) {
587 while ($dataRow = SQL_FETCHARRAY($result)) {
588 // Shall we group these results?
589 if ($group == 'url_id') {
590 // Add the row by id as index
591 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
594 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
600 SQL_FREERESULT($result);
603 return $GLOBALS['last_url_data'];
606 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
607 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
608 // Make sure by the user registered URLs are always pending
609 if ($addMode == 'reg') {
614 $content = merge_array($extraFields, array(
616 'url_userid' => $userid,
617 'url_status' => $status,
620 // Is limit/reload set?
621 if (!isset($content['limit'])) {
622 $content['limit'] = '0';
624 if (!isset($content['reload'])) {
625 $content['reload'] = '0';
628 // Insert the URL into database
629 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
632 if ($content['insert_id'] == '0') {
633 // INSERT did not insert any data!
637 // If in reg-mode we notify admin
638 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
639 // Notify admin even when he as unlocked an email
640 SURFBAR_NOTIFY_ADMIN('url_' . $addMode, $content);
644 SURFBAR_NOTIFY_USER('url_' . $addMode, $content);
646 // Return the insert id
647 return $content['insert_id'];
650 // Inserts an url by given data array and return the insert id
651 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
653 $userid = bigintval($urlData['url_userid']);
656 if (empty($userid)) $userid = '0';
658 // Just run the insert query for now
659 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)",
663 $urlData['url_status'],
667 ), __FUNCTION__, __LINE__
671 return SQL_INSERTID();
674 // Notify admin(s) with a selected message and content
675 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
676 // Prepare template name
677 $templateName = sprintf("admin_surfbar_%s", $messageType);
680 $subject = sprintf("{--ADMIN_SURFBAR_NOTIFY_%s_SUBJECT--}",
681 strtoupper($messageType)
684 // Is the subject line there?
685 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
686 // Set default subject if following eval() wents wrong
687 $subject = '{%message,ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT=' . strtoupper($messageType) . '%}';
690 // Translate some data if present
691 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
693 // Send the notification out
694 return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
697 // Notify the user about the performed action
698 function SURFBAR_NOTIFY_USER ($messageType, $content) {
699 // Skip notification if userid is zero
700 if ($content['url_userid'] == '0') {
704 // Prepare template name
705 $templateName = sprintf("member_surfbar_%s", $messageType);
708 $subject = sprintf("{--MEMBER_SURFBAR_NOTIFY_%s_SUBJECT--}",
709 strtoupper($messageType)
712 // Is the subject line there?
713 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
714 // Set default subject if following eval() wents wrong
715 $subject = '{--MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT--}';
718 // Translate some data if present
719 $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
722 $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
725 return sendEmail($content['url_userid'], $subject, $mailText);
728 // Translates some data for template usage
729 // @TODO Can't we use our new expression language instead of this ugly code?
730 function SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE ($content) {
732 if (isset($content['url_registered'])) $content['url_registered'] = generateDateTime($content['url_registered'], 2);
733 if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
735 // Return translated content
739 // Translates the limit
740 function translateSurfbarLimit ($limit) {
744 $return = '{--MEMBER_SURFBAR_UNLIMITED_VIEWS--}';
747 $return = '{%pipe,translateComma=' . $limit . '%}';
754 // Translate the URL status
755 function translateSurfbarUrlStatus ($status) {
756 // NULL must be handled carfefully
757 if ((is_null($status)) || (trim($status) == '')) {
758 // Is NULL, so return other language string
759 return '{--SURFBAR_URL_STATUS_NONE--}';
761 // Return regular result
762 return sprintf("{--SURFBAR_URL_STATUS_%s--}", strtoupper($status));
766 // Translates the given action into a link title for members
767 function translateMemberSurfbarActionToTitle ($action) {
769 if (!isset($GLOBALS[__FUNCTION__][$action])) {
770 // Construct default return string (unknown
771 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_TITLE=' . $action . '%}';
773 // ... and the id's name
774 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE';
777 if (isMessageIdValid($messageId)) {
779 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
784 return $GLOBALS[__FUNCTION__][$action];
787 // Translates the given action into a submit button for members
788 function translateMemberSurfbarActionToSubmit ($action) {
790 if (!isset($GLOBALS[__FUNCTION__][$action])) {
791 // Construct default return string (unknown
792 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_SUBMIT=' . $action . '%}';
794 // ... and the id's name
795 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT';
798 if (isMessageIdValid($messageId)) {
800 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
805 return $GLOBALS[__FUNCTION__][$action];
809 function SURFBAR_DETERMINE_REWARD ($onlyMin = false) {
810 // Static values are default
811 $reward = getConfig('surfbar_static_reward');
813 // Do we have static or dynamic?
814 if (getSurfbarPaymentModel() == 'DYNAMIC') {
815 // "Calculate" dynamic reward
816 if ($onlyMin === true) {
817 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
819 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
828 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
829 // Static costs is default
830 $costs = getConfig('surfbar_static_costs');
832 // Do we have static or dynamic?
833 if (getSurfbarPaymentModel() == 'DYNAMIC') {
834 // "Calculate" dynamic costs
836 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
838 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
846 // "Calculate" dynamic add
847 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
848 // Get min/max values
849 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
850 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
852 // "Calculate" dynamic part and return it
853 return mt_rand($min, $max);
856 // Determine right template name
857 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
858 // Default is the frameset
859 $templateName = 'surfbar_frameset';
861 // Any frame set? ;-)
862 if (isGetRequestParameterSet('frame')) {
863 // Use the frame as a template name part... ;-)
864 $templateName = sprintf("surfbar_frame_%s",
865 getRequestParameter('frame')
870 return $templateName;
873 // Check if the "reload lock" of the current user is full, call this function
874 // before you call SURFBAR_CHECK_RELOAD_LOCK().
875 function SURFBAR_CHECK_RELOAD_FULL () {
876 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is ' . getConfig('surfbar_static_lock') . ' - ENTERED!');
880 // Cache static reload lock
881 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
883 // Do we have dynamic model?
884 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - BEFORE');
885 if (getSurfbarPaymentModel() == 'DYNAMIC') {
886 // "Calculate" dynamic lock
887 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
889 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - AFTER');
892 $result = SQL_QUERY_ESC("SELECT
893 COUNT(l.`locks_id`) AS `cnt`
895 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
897 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
899 u.`url_id`=l.`locks_url_id`
901 l.`locks_userid`=%s AND
902 (UNIX_TIMESTAMP() - {%%pipe,SURFBAR_GET_SURF_LOCK%%}) < UNIX_TIMESTAMP(l.`locks_last_surfed`) AND
904 ((UNIX_TIMESTAMP(l.`locks_last_surfed`) - u.`url_fixed_reload`) < 0 AND u.`url_fixed_reload` > 0) OR
905 u.`url_fixed_reload` = 0
908 array(getMemberId()), __FUNCTION__, __LINE__
912 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
915 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
916 // Then fix it to zero!
917 $GLOBALS['surfbar_cache']['user_locks'] = '0';
921 SQL_FREERESULT($result);
924 $total = SURFBAR_GET_TOTAL_URLS();
926 // Do we have some URLs in lock? Admins can always surf on own URLs!
927 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
930 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userLocks=' . SURFBAR_GET_USER_LOCKS() . ',total=' . $total . 'isFull=' . intval($isFull) . ' - EXIT!');
934 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
935 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
936 // Determine depleted user account
937 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
939 // If we dont get any user ids back, there are no URLs
940 if (count($userids['url_userid']) == 0) {
941 // No user ids found, no URLs!
945 // Is the exlude userid set?
946 if (isValidUserId($excludeUserId)) {
948 $userids['url_userid'][$excludeUserId] = $excludeUserId;
951 // Get amount from database
952 $result = SQL_QUERY_ESC("SELECT
953 COUNT(`url_id`) AS cnt
955 `{?_MYSQL_PREFIX?}_surfbar_urls`
957 `url_userid` NOT IN (".implode(', ', $userids['url_userid']).") AND
960 array($status), __FUNCTION__, __LINE__
964 list($count) = SQL_FETCHROW($result);
967 SQL_FREERESULT($result);
970 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $count);
976 // Check wether the user is allowed to book more URLs
977 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
978 // Is this admin and userid is zero or does the user has some URLs left to book?
979 return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getSurfbarMaxOrder()));
982 // Get total amount of URLs of given status for current user
983 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '', $exclude = '') {
984 // Is the user 0 and user is logged in?
985 if (($userid == '0') && (isMember())) {
986 // Then use this userid
987 $userid = getMemberId();
988 } elseif ($userid == '0') {
990 return (getSurfbarMaxOrder() + 1);
993 // Default is all URLs
996 // Is the status set?
997 if (is_array($status)) {
998 // Only URLs with these status
999 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
1000 } elseif (!empty($status)) {
1001 // Only URLs with this status
1002 $add = sprintf(" AND `url_status`='%s'", $status);
1003 } elseif (is_array($exclude)) {
1004 // Exclude URLs with these status
1005 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
1006 } elseif (!empty($exclude)) {
1007 // Exclude URLs with this status
1008 $add = sprintf(" AND `url_status` != '%s'", $exclude);
1011 // Get amount from database
1012 $count = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
1018 // Generate a validation code for the given id number
1019 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
1020 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ' - ENTERED!');
1021 // Init hash with invalid value
1023 // Generate random hashed string
1024 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
1025 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
1027 // Use this as salt!
1028 $GLOBALS['surfbar_cache']['salt'] = $salt;
1029 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
1032 // Hash it with md5() and salt it with the random string
1033 $hashedCode = generateHash(md5($urlId . getEncryptSeperator() . getMemberId()), SURFBAR_GET_SALT());
1035 // Finally encrypt it PGP-like and return it
1036 $valHashedCode = encodeHashForCookie($hashedCode);
1038 // Return hashed value
1039 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ',urlId=' . $urlId . ',salt=' . $salt . ',valHashedCode=' . $valHashedCode . ' - EXIT!');
1040 return $valHashedCode;
1043 // Check validation code
1044 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
1045 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',check=' . $check . ',salt=' . $salt . ' - ENTERED!');
1047 $urlId = bigintval($urlId);
1049 // Now generate the code again
1050 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1052 // Return result of checking hashes and salts
1053 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',(code==check)=' . intval($code == $check) . ',(salt==salts_last_salt)=' . intval($salt == SURFBAR_GET_DATA('salts_last_salt')) . ' - EXIT!');
1054 return (($code == $check) && ($salt == SURFBAR_GET_DATA('salts_last_salt')));
1057 // Lockdown the userid/id combination (reload lock)
1058 function SURFBAR_LOCKDOWN_ID ($urlId) {
1059 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ' - ENTERED!');
1060 // Search for an entry
1061 $countLock = countSumTotalData(getMemberId(), 'surfbar_locks', 'locks_id', 'locks_userid', true, ' AND `locks_url_id`=' . bigintval($urlId));
1063 // Do we have no record?
1064 if ($countLock == 0) {
1065 // Just add it to the database
1066 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)',
1070 ), __FUNCTION__, __LINE__);
1073 // Remove the salt from database
1074 SQL_QUERY_ESC('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1',
1078 ), __FUNCTION__, __LINE__);
1080 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1083 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1084 function SURFBAR_PAY_POINTS () {
1085 // Remove it from the URL owner
1086 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS() . ' - ENTERED!');
1087 if (isValidUserId(SURFBAR_GET_USERID())) {
1088 subtractPoints(sprintf("surfbar_%s", getSurfbarPaymentModel()), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1091 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD());
1092 // Init referal system here
1093 initReferalSystem();
1095 // Book it to the user
1096 addPointsThroughReferalSystem(sprintf("surfbar:%s", getSurfbarPaymentModel()), getMemberId(), SURFBAR_GET_REWARD());
1097 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS() . ' - EXIT!');
1100 // Updates the statistics of current URL/userid
1101 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1105 // Get allowed views
1106 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1108 // Do we have a limit?
1110 // Then count views_max down!
1111 $add .= ', `url_views_max`=`url_views_max`-1';
1115 SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1' . $add . ' WHERE `url_id`=%s LIMIT 1',
1116 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1118 // Update the stats entry
1119 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',
1123 ), __FUNCTION__, __LINE__);
1125 // Was that update okay?
1126 if (SQL_HASZEROAFFECTED()) {
1127 // No, then insert entry
1128 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)',
1132 ), __FUNCTION__, __LINE__);
1135 // Update total/daily/weekly/monthly counter
1136 incrementConfigEntry('surfbar_total_counter');
1137 incrementConfigEntry('surfbar_daily_counter');
1138 incrementConfigEntry('surfbar_weekly_counter');
1139 incrementConfigEntry('surfbar_monthly_counter');
1141 // Update config as well
1142 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1145 // Update the salt for validation and statistics
1146 function SURFBAR_UPDATE_SALT_STATS () {
1148 SURFBAR_GENERATE_VALIDATION_CODE(SURFBAR_GET_ID());
1150 // Make sure only valid salts can pass
1151 if (SURFBAR_GET_SALT() == 'INVALID') {
1153 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid salt provided, id=' . SURFBAR_GET_ID() . ',getMemberId()=' . getMemberId());
1156 // Update statistics record
1157 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1159 // Simply store the salt from cache away in database...
1160 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1165 ), __FUNCTION__, __LINE__);
1168 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . SURFBAR_GET_SALT() . ',id=' . SURFBAR_GET_ID() . ',userid=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - UPDATE!');
1171 if (SQL_HASZEROAFFECTED()) {
1172 // Insert missing entry!
1173 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1178 ), __FUNCTION__, __LINE__);
1182 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1184 // Return if the update was okay
1185 return (!SQL_HASZEROAFFECTED());
1188 // Check if the reload lock is active for given id
1189 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1190 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . ' - ENTERED!');
1192 $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1194 `{?_MYSQL_PREFIX?}_surfbar_locks`
1196 `locks_userid`=%s AND
1197 `locks_url_id`=%s AND
1198 (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1200 `locks_last_surfed` ASC
1202 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1206 list($count) = SQL_FETCHROW($result);
1209 SQL_FREERESULT($result);
1212 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',count=' . $count . ',SURFBAR_GET_SURF_LOCK()=' . SURFBAR_GET_SURF_LOCK() . ' - EXIT!');
1213 return ($count == 1);
1216 // Determine which user hash no more points left
1217 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1220 'url_userid' => array(),
1221 'points' => array(),
1222 'notified' => array(),
1225 // Do we have a current user id?
1226 if ((isMember()) && ($limit == '0')) {
1227 // Then add this as well
1228 $userids['url_userid'][getMemberId()] = getMemberId();
1229 $userids['points'][getMemberId()] = getTotalPoints(getMemberId());
1230 $userids['notified'][getMemberId()] = '0';
1232 // Get all userid except logged in one
1233 $result = SQL_QUERY_ESC("SELECT
1234 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1236 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1238 `{?_MYSQL_PREFIX?}_user_data` AS d
1240 u.`url_userid`=d.`userid`
1242 u.`url_userid` NOT IN (%s,0) AND
1243 u.`url_status`='ACTIVE'
1247 u.`url_userid` ASC",
1248 array(getMemberId()), __FUNCTION__, __LINE__);
1251 $result = SQL_QUERY("SELECT
1252 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1254 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1256 `{?_MYSQL_PREFIX?}_user_data` AS d
1258 u.`url_userid`=d.`userid`
1260 u.`url_userid` > 0 AND
1261 u.`url_status`='ACTIVE'
1265 u.`url_userid` ASC", __FUNCTION__, __LINE__);
1269 while ($content = SQL_FETCHARRAY($result)) {
1271 $points = getTotalPoints($content['url_userid']);
1272 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ',points=' . $points);
1274 // Shall we add this to ignore?
1275 if ($points <= $limit) {
1277 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ' has depleted points amount!');
1278 $userids['url_userid'][$content['url_userid']] = $content['url_userid'];
1279 $userids['points'][$content['url_userid']] = $points;
1280 $userids['notified'][$content['url_userid']] = $content['notified'];
1285 SQL_FREERESULT($result);
1288 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UIDs::count=' . count($userids) . ' (with own userid=' . getMemberId() . ')');
1294 // Determine how many users are Online in surfbar
1295 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1296 // Count all users in surfbar modue and return the value
1297 $result = SQL_QUERY('SELECT
1300 `{?_MYSQL_PREFIX?}_surfbar_stats`
1302 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1304 `stats_userid` ASC', __FUNCTION__, __LINE__);
1307 $count = SQL_NUMROWS($result);
1310 SQL_FREERESULT($result);
1316 // Determine waiting time for one URL
1317 function SURFBAR_DETERMINE_WAIT_TIME () {
1318 // Get fixed reload lock
1319 $fixed = SURFBAR_GET_FIXED_RELOAD();
1321 // Is the fixed reload time set?
1327 // Static time is default
1328 $time = getConfig('surfbar_static_time');
1330 // Which payment model do we have?
1331 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1332 // "Calculate" dynamic time
1333 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1340 // Changes the status of an URL from given to other
1341 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1342 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - ENTERED!');
1343 // Make new status always lower-case
1344 $newStatus = strtolower($newStatus);
1346 // Get URL data for status comparison if missing
1347 if ((!is_array($data)) || (count($data) == 0)) {
1348 // Fetch missing URL data
1349 $data = SURFBAR_GET_URL_DATA($urlId);
1353 $filterData = array(
1355 'prev_status' => $prevStatus,
1356 'new_status' => $newStatus,
1361 // Run pre filter chain
1362 $filterData = runFilterChain('pre_change_surfbar_url_status', $filterData);
1365 if (!is_null($filterData['abort'])) {
1367 return $filterData['abort'];
1370 // Update the status now
1371 // ---------- Comment out for debugging/developing member actions! ---------
1372 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_status`='%s' WHERE `url_id`=%s LIMIT 1",
1376 ), __FUNCTION__, __LINE__);
1377 // ---------- Comment out for debugging/developing member actions! ---------
1380 // ---------- Comment out for debugging/developing member actions! ---------
1381 if (SQL_AFFECTEDROWS() != 1) {
1382 // No, something went wrong
1385 // ---------- Comment out for debugging/developing member actions! ---------
1387 // Run post filter chain
1388 $filterData = runFilterChain('post_change_surfbar_url_status', $filterData);
1390 // Extract data from it again
1391 $data = $filterData['data'];
1394 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - EXIT!');
1398 // Calculate minimum value for dynamic payment model
1399 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1400 // Addon is zero by default
1404 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1407 $totalUsers = getTotalConfirmedUser();
1410 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1413 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1416 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1418 // Get user's total URLs
1419 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1422 if ($totalUrls > 0) {
1423 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1425 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1432 // Calculate maximum value for dynamic payment model
1433 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1434 // Addon is zero by default
1441 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1444 $totalUsers = getTotalConfirmedUser();
1447 $addon += abs($max * $percent * $totalUsers);
1450 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1453 $addon += abs($max * $percent * $totalUrls);
1459 // Calculate dynamic lock
1460 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1461 // Default lock is 30 seconds
1465 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1468 $addon = abs(log($onlineUsers / $addon + 1));
1474 // "Getter" for lock ids array
1475 function SURFBAR_GET_LOCK_IDS () {
1476 // Prepare some arrays
1481 // Get all id from locks within the timestamp
1482 $result = SQL_QUERY_ESC("SELECT
1485 UNIX_TIMESTAMP(`locks_last_surfed`) AS `last_surfed`
1487 `{?_MYSQL_PREFIX?}_surfbar_locks`
1491 `locks_id` ASC", array(getMemberId()),
1492 __FUNCTION__, __LINE__);
1495 while ($content = SQL_FETCHARRAY($result)) {
1497 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK());
1499 // Skip entries that are too old
1500 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['locks_url_id'], $ignored))) {
1502 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1504 // Add only if missing or bigger
1505 if ((!isset($IDs[$content['locks_url_id']])) || ($IDs[$content['locks_url_id']] > $content['last_surfed'])) {
1507 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1510 $IDs[$content['locks_url_id']] = $content['last_surfed'];
1511 $USE[$content['locks_url_id']] = $content['locks_id'];
1515 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1517 // Ignore these old entries!
1518 $ignored[] = $content['locks_url_id'];
1519 unset($IDs[$content['locks_url_id']]);
1520 unset($USE[$content['locks_url_id']]);
1525 SQL_FREERESULT($result);
1531 // "Getter" for maximum random number
1532 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1533 // Count max availabe entries
1534 $result = SQL_QUERY("SELECT
1537 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1539 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1541 sbu.url_id=sbs.salts_url_id
1543 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1545 sbu.url_id=l.locks_url_id
1547 sbu.url_userid NOT IN (" . implode(',', $userids) . ") AND
1548 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1549 sbu.url_status='ACTIVE'
1552 sbu.url_id ASC", __FUNCTION__, __LINE__);
1555 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1558 $maxRand = SQL_NUMROWS($result);
1561 SQL_FREERESULT($result);
1567 // Load all URLs of the current user and return it as an array
1568 function SURFBAR_GET_USER_URLS () {
1570 $urlArray = array();
1573 $result = SQL_QUERY_ESC("SELECT
1580 u.url_views_allowed,
1581 UNIX_TIMESTAMP(u.url_registered) AS `url_registered`,
1582 UNIX_TIMESTAMP(u.`url_last_locked`) AS `url_last_locked`,
1585 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1587 u.`url_userid`=%s AND
1588 u.`url_status` != 'DELETED'
1591 array(getMemberId()), __FUNCTION__, __LINE__);
1593 // Are there entries?
1594 if (!SQL_HASZERONUMS($result)) {
1596 while ($row = SQL_FETCHARRAY($result)) {
1598 $urlArray[$row['url_id']] = $row;
1603 SQL_FREERESULT($result);
1609 // "Getter" for member action array for given status
1610 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1612 $returnArray = array();
1614 // Get all assigned actions
1615 $result = SQL_QUERY_ESC("SELECT `actions_action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1616 array($status), __FUNCTION__, __LINE__);
1618 // Some entries there?
1619 if (!SQL_HASZERONUMS($result)) {
1621 // @TODO This can be somehow rewritten
1622 while ($content = SQL_FETCHARRAY($result)) {
1623 $returnArray[] = $content['actions_action'];
1628 SQL_FREERESULT($result);
1631 return $returnArray;
1634 // Reload to configured stop page
1635 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1636 // Internal or external?
1637 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'page=' . $page . ' - ENTERED!');
1638 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1639 // Reload to internal page
1640 redirectToUrl('surfbar.php?frame=' . $page);
1642 // Reload to external page
1643 redirectToConfiguredUrl('surfbar_pause_url');
1647 // Determine next id for surfbar or get data for given id, always call this before you call other
1648 // getters below this function!
1649 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1650 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ' - ENTERED!');
1651 // Default is no id and no random number
1656 if ($urlId == '0') {
1657 // Get array with lock ids
1658 $USE = SURFBAR_GET_LOCK_IDS();
1660 // Shall we add some URL ids to ignore?
1662 if (count($USE) > 0) {
1664 $add = " AND sbu.`url_id` NOT IN (";
1665 foreach ($USE as $url_id => $lid) {
1667 $add .= $url_id.',';
1670 // Add closing bracket
1671 $add = substr($add, 0, -1) . ')';
1674 // Determine depleted user account
1675 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1677 // Get maximum randomness factor
1678 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['url_userid'], $add);
1680 // If more than one URL can be called generate the random number!
1682 // Generate random number
1683 $randNum = mt_rand(0, ($maxRand - 1));
1686 // And query the database
1687 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK());
1688 $result = SQL_QUERY_ESC("SELECT
1692 sbs.salts_last_salt,
1693 sbu.url_views_total,
1695 sbu.url_views_allowed,
1696 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1697 sbu.url_fixed_reload
1699 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1701 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1703 sbu.url_id=sbs.salts_url_id
1705 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1707 sbu.url_id=l.locks_url_id
1709 sbu.`url_userid` NOT IN (".implode(',', $userids['url_userid']).") AND
1710 sbu.url_status='ACTIVE' AND
1711 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1716 l.locks_last_surfed ASC,
1719 array($randNum), __FUNCTION__, __LINE__
1722 // Get data from specified id number
1723 $result = SQL_QUERY_ESC("SELECT
1727 sbs.salts_last_salt,
1728 sbu.url_views_total,
1730 sbu.url_views_allowed,
1731 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1732 sbu.url_fixed_reload
1734 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1736 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1738 sbu.url_id=sbs.salts_url_id
1740 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1742 sbu.url_id=l.locks_url_id
1744 sbu.url_userid != %s AND
1745 sbu.url_status='ACTIVE' AND
1747 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1749 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1753 // Is there an id number?
1754 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1755 if (SQL_NUMROWS($result) == 1) {
1757 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1758 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1759 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1761 // Determine waiting time
1762 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1764 // Is the last salt there?
1765 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1766 // Then repair it wit the static!
1767 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1768 $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1771 // Fix missing last_surfed
1772 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1774 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1775 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1778 // Get base/fixed reward and costs
1779 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1780 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1781 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS());
1783 // Only in dynamic model add the dynamic bonus!
1784 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1785 // Calculate dynamic reward/costs and add it
1786 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1787 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1788 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS());
1792 $nextId = SURFBAR_GET_ID();
1796 SQL_FREERESULT($result);
1799 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',nextId=' . $nextId . ' - EXIT!');
1803 //-----------------------------------------------------------------------------
1805 //-----------------------------------------------------------------------------
1807 // "Getter" for surfbar_dynamic_percent
1808 function getSurfbarDynamicPercent () {
1809 // Do we have cache?
1810 if (!isset($GLOBALS[__FUNCTION__])) {
1812 $GLOBALS[__FUNCTION__] = getConfig('surfbar_dynamic_percent');
1816 return $GLOBALS[__FUNCTION__];
1819 // "Getter" for surfbar_static_reward
1820 function getSurfbarStaticReward () {
1821 // Do we have cache?
1822 if (!isset($GLOBALS[__FUNCTION__])) {
1824 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_reward');
1828 return $GLOBALS[__FUNCTION__];
1831 // "Getter" for surfbar_static_time
1832 function getSurfbarStaticTime () {
1833 // Do we have cache?
1834 if (!isset($GLOBALS[__FUNCTION__])) {
1836 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_time');
1840 return $GLOBALS[__FUNCTION__];
1843 // "Getter" for surfbar_max_order
1844 function getSurfbarMaxOrder () {
1845 // Do we have cache?
1846 if (!isset($GLOBALS[__FUNCTION__])) {
1848 $GLOBALS[__FUNCTION__] = getConfig('surfbar_max_order');
1852 return $GLOBALS[__FUNCTION__];
1855 // "Getter" for surfbar_payment_model
1856 function getSurfbarPaymentModel () {
1857 // Do we have cache?
1858 if (!isset($GLOBALS[__FUNCTION__])) {
1860 $GLOBALS[__FUNCTION__] = getConfig('surfbar_payment_model');
1864 return $GLOBALS[__FUNCTION__];
1867 //------------------------------------------------------------------------------
1868 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1869 // THE $GLOBALS['surfbar_cache'] ARRAY!
1870 //------------------------------------------------------------------------------
1872 // Initializes the surfbar
1873 function SURFBAR_INIT () {
1875 $GLOBALS['surfbar_cache'] = array();
1878 // Private getter for data elements
1879 function SURFBAR_GET_DATA ($element) {
1880 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element=' . $element . ' - ENTERED!');
1885 // Is the entry there?
1886 if (isset($GLOBALS['surfbar_cache'][$element])) {
1888 $data = $GLOBALS['surfbar_cache'][$element];
1889 } else { // END - if
1891 print_r($GLOBALS['surfbar_cache']);
1893 debug_report_bug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
1897 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data . ' - EXIT!');
1901 // Getter for reward from cache
1902 function SURFBAR_GET_REWARD () {
1903 // Get data element and return its contents
1904 return SURFBAR_GET_DATA('reward');
1907 // Getter for costs from cache
1908 function SURFBAR_GET_COSTS () {
1909 // Get data element and return its contents
1910 return SURFBAR_GET_DATA('costs');
1913 // Getter for URL from cache
1914 function SURFBAR_GET_URL () {
1915 // Get data element and return its contents
1916 return SURFBAR_GET_DATA('url');
1919 // Getter for salt from cache
1920 function SURFBAR_GET_SALT () {
1921 // Get data element and return its contents
1922 return SURFBAR_GET_DATA('salt');
1925 // Getter for id from cache
1926 function SURFBAR_GET_ID () {
1927 // Get data element and return its contents
1928 return SURFBAR_GET_DATA('url_id');
1931 // Getter for userid from cache
1932 function SURFBAR_GET_USERID () {
1933 // Get data element and return its contents
1934 return SURFBAR_GET_DATA('url_userid');
1937 // Getter for user reload locks
1938 function SURFBAR_GET_USER_LOCKS () {
1939 // Get data element and return its contents
1940 return SURFBAR_GET_DATA('user_locks');
1943 // Getter for reload time
1944 function SURFBAR_GET_RELOAD_TIME () {
1945 // Get data element and return its contents
1946 return SURFBAR_GET_DATA('time');
1949 // Getter for allowed views
1950 function SURFBAR_GET_VIEWS_ALLOWED () {
1951 // Get data element and return its contents
1952 return SURFBAR_GET_DATA('url_views_allowed');
1955 // Getter for maximum views
1956 function SURFBAR_GET_VIEWS_MAX () {
1957 // Get data element and return its contents
1958 return SURFBAR_GET_DATA('url_views_max');
1961 // Getter for fixed reload
1962 function SURFBAR_GET_FIXED_RELOAD () {
1963 // Get data element and return its contents
1964 return SURFBAR_GET_DATA('url_fixed_reload');
1967 // Getter for surf lock
1968 function SURFBAR_GET_SURF_LOCK () {
1969 // Get data element and return its contents
1970 return SURFBAR_GET_DATA('surf_lock');
1973 // Getter for new status
1974 function SURFBAR_GET_NEW_STATUS () {
1975 // Get data element and return its contents
1976 return SURFBAR_GET_DATA('new_status');
1979 // Getter for last salt
1980 function SURFBAR_GET_LAST_SALT () {
1981 // Get data element and return its contents
1982 return SURFBAR_GET_DATA('salts_last_salt');