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 - 2012 by Mailer Developer Team *
20 * For more information visit: http://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 doSurfbarAdminAddUrl ($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 (ifSurfbarHasUrlUserId($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 (!ifSurfbarMemberAllowedMoreUrls()) {
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 doSurfbarRegisterUrl($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
80 // Admin unlocked an email so we can migrate the URL
81 function doSurfbarAdminMigrateUrl ($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 (ifSurfbarHasUrlUserId($url, $userid)) {
92 // URL already found in surfbar!
93 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Already added, url=' . $url . ',userid=' . $userid);
95 } elseif (!ifSurfbarMemberAllowedMoreUrls($userid)) {
97 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Maximum exceeded, url=' . $url . ',userid=' . $userid);
101 // Register the new URL
102 return doSurfbarRegisterUrl($url, $userid, 'MIGRATED', 'migrate');
105 // Admin function for unlocking URLs
106 function doSurfbarAdminUnlockUrlIds ($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) && (changeSurfbarUrlStatus($id, 'PENDING', 'ACTIVE')));
131 // Return total status
135 // Admin function for rejecting URLs
136 function doSurfbarAdminRejectUrlIds ($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) && (changeSurfbarUrlStatus($id, 'PENDING', 'REJECTED')));
161 // Return total status
165 //------------------------------------------------------------------------------
167 //------------------------------------------------------------------------------
169 // Member has added an URL
170 function doSurfbarMemberAddUrl ($url, $limit) {
171 // Do some pre-checks
174 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: isMember()=false');
176 } elseif ((!isUrlValid($url)) && (!isAdmin())) {
178 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid, url=' . $url . ',limit=' . $limit);
180 } elseif (ifSurfbarHasUrlUserId($url, getMemberId())) {
181 // URL already found in surfbar!
182 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Already found, url=' . $url . ',limit=' . $limit);
184 } elseif (!ifSurfbarMemberAllowedMoreUrls(getMemberId())) {
186 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Maximum exceeded, url=' . $url . ',limit=' . $limit);
188 } elseif (''.($limit + 0).'' != ''.$limit.'') {
189 // Invalid amount entered
190 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid limit, url=' . $url . ',limit=' . $limit);
194 // Register the new URL
195 return doSurfbarRegisterUrl($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
198 // Create list of actions depending on status for the user
199 function generateSurfbarMemberActions ($urlId, $status) {
200 // Load all actions in an array for given status
201 $actionArray = getSurfbarArrayFromStatus($status);
204 $width = round(100 / count($actionArray));
206 // "Walk" through all actions and create forms
208 foreach ($actionArray as $actionId => $action) {
209 // Add form for this action
210 $OUT .= loadTemplate('member_list_surfbar_form', TRUE, array(
212 'url_id' => bigintval($urlId),
213 'action' => strtolower($action)
217 // Load main template
218 $output = loadTemplate('member_list_surfbar_table', TRUE, $OUT);
224 // Do the member form request
225 function doSurfbarMemberByFormData ($formData, $urlArray) {
226 // By default no action is performed
232 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: isMember()=false');
234 } elseif ((!isset($formData['url_id'])) || (!isset($formData['action']))) {
235 // Important form elements are missing!
236 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid form data, required field id/action not found');
238 } elseif (!isset($urlArray[$formData['url_id']])) {
239 // Id not found in cache
240 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Field url_id not found in cache');
242 } elseif (!isSurfbarMemberActionStatusValid($formData['action'], $urlArray[$formData['url_id']]['url_status'])) {
243 // Action not allowed for current URL status
244 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Action not allowed to perform. action=' . $formData['action'] . ',url_status=' . $urlArray[$formData['url_id']]['url_status'] . ',url_id=' . $formData['url_id']);
249 $action = secureString($formData['action']);
252 if ($action != $formData['action']) {
253 // Invalid data in action found
257 // Create the function name for selected action
258 $functionName = sprintf("doSurfbarMember%sAction", firstCharUpperCase($action));
260 // Is the function there?
261 if (function_exists($functionName)) {
262 // Load data and add it to globals array
263 $urlData = getSurfbarUrlData($formData['url_id']);
264 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], $urlData[$formData['url_id']]);
267 $urlArray[$formData['url_id']]['new_status'] = getSurfbarNewStatus('new_status');
269 // Extract URL data for call-back
270 $urlData = array(merge_array($urlArray[$formData['url_id']], array($action => $formData)));
272 // Action found so execute it
273 $performed = call_user_func_array($functionName, $urlData);
275 // Log invalid request
276 reportBug(__FUNCTION__, __LINE__, 'Invalid member action! action=' . $formData['action'] . ',url_id=' . $formData['url_id'] . ',function=' . $functionName);
283 // Getter for surfbar_actions table by given id number
284 function getSurfbarActionsDataById ($columnName, $id) {
286 if (!isset($GLOBALS[__FUNCTION__][$id][$columnName])) {
287 // Default is not found
288 $GLOBALS[__FUNCTION__][$id][$columnName] = '*INVALID*';
291 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_id`=%s LIMIT 1",
295 ), __FUNCTION__, __LINE__);
297 // Is there an entry?
298 if (SQL_NUMROWS($result) == 1) {
300 list($GLOBALS[__FUNCTION__][$id][$columnName]) = SQL_FETCHROW($result);
304 SQL_FREERESULT($result);
308 return $GLOBALS[__FUNCTION__][$id][$columnName];
311 // Validate if the requested action can be performed on current URL status
312 function isSurfbarMemberActionStatusValid ($action, $status) {
313 // Search for the requested action/status combination in database
314 $result = SQL_QUERY_ESC("SELECT `actions_new_status` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_action`='%s' AND `actions_status`='%s' LIMIT 1",
318 ), __FUNCTION__, __LINE__);
320 // Is the entry there?
321 $isValid = (SQL_NUMROWS($result) == 1);
324 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'action=' . $action . ',status=' . $status . ',isValid=' . intval($isValid));
326 // Fetch the new status if found
327 if ($isValid === TRUE) {
329 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
333 SQL_FREERESULT($result);
339 //------------------------------------------------------------------------------
341 //------------------------------------------------------------------------------
343 // Retreat a booked URL
344 function doSurfbarMemberRetreatAction ($urlData) {
345 // Create the data array for next function call
347 $urlData['url_id'] => $urlData
350 // Simply change the status here
351 return changeSurfbarUrlStatus ($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], $data);
354 // Book an URL now (from migration)
355 function doSurfbarMemberBooknowAction ($urlData) {
356 // Create the data array for next function call
358 $urlData['url_id'] => $urlData
361 // Simply change the status here
362 return changeSurfbarUrlStatus ($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], $data);
365 // Show edit form or do the changes
366 function doSurfbarMemberEditAction ($urlData) {
367 // Is the "execute" flag there?
368 if (isset($urlData['edit']['execute'])) {
369 // Execute the changes
370 return executeSurfbarMemberAction('edit', $urlData);
374 return displaySurfbarMemberActionForm('edit', $urlData);
377 // Show delete form or do the changes
378 function doSurfbarMemberDeleteAction ($urlData) {
379 // Is the "execute" flag there?
380 if (isset($urlData['delete']['execute'])) {
381 // Execute the changes
382 return executeSurfbarMemberAction('delete', $urlData);
386 return displaySurfbarMemberActionForm('delete', $urlData);
389 // Pause active banner
390 function doSurfbarMemberPauseAction ($urlData) {
391 return changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
394 // Unpause stopped banner
395 function doSurfbarMemberUnpauseAction ($urlData) {
396 // Fix missing entry for template
397 $urlData['edit'] = $urlData['unpause'];
398 $urlData['edit']['url'] = $urlData['url'];
399 $urlData['edit']['limit'] = getSurfbarViewsMax();
401 // Return status change
402 return changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
405 // Resubmit locked URL
406 function doSurfbarMemberResubmitAction ($urlData) {
407 return changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
410 // Display selected "action form"
411 function displaySurfbarMemberActionForm ($action, $urlData) {
412 // Translate some data if present
413 $content = prepareSurfbarContentForTemplate($urlData);
415 // Include fields only for action 'edit'
416 if ($action == 'edit') {
417 // Default is not limited
418 $urlData['limited_yes'] = '';
419 $urlData['limited_no'] = ' checked="checked"';
420 $urlData['limited'] = 'false';
422 // Is this URL limited?
423 if (getSurfbarViewsMax() > 0) {
424 // Then rewrite form data
425 $urlData['limited_yes'] = ' checked="checked"';
426 $urlData['limited_no'] = '';
427 $urlData['limited'] = 'true';
431 // Load the form and display it
432 loadTemplate(sprintf("member_surfbar_%s_action_form", $action), FALSE, $urlData);
434 // All fine by default ... ;-)
438 // Execute choosen action
439 function executeSurfbarMemberAction ($action, $urlData) {
440 // By default nothing is executed
443 // Is limitation "no" and "limit" is > 0?
444 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
445 // Set it to unlimited
446 $urlData[$action]['limit'] = '0';
449 // Construct function name
450 $functionName = sprintf("executeSurfbarMember%sAction", firstCharUpperCase($action));
452 // Is that function there?
453 if (function_exists($functionName)) {
454 // Execute the function
455 if (call_user_func_array($functionName, array($urlData)) == TRUE) {
456 // Update status as well
457 $executed = changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
461 reportBug(__FUNCTION__, __LINE__, 'Callback function ' . $functionName . ' does not exist.');
468 // "Execute edit" function: Update changed data
469 function executeSurfbarMemberEditAction ($urlData) {
470 // Default is nothing done
473 // Has the URL or limit changed?
475 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
477 SQL_QUERY_ESC("UPDATE
478 `{?_MYSQL_PREFIX?}_surfbar_urls`
481 `url_views_allowed`=%s,
489 $urlData['edit']['limit'],
490 $urlData['edit']['limit'],
492 $urlData['url_status']
493 ), __FUNCTION__, __LINE__);
503 // "Execute delete" function: Does nothing...
504 function executeSurfbarMemberDeleteAction ($urlData) {
505 // Nothing special to do (see above function for such "special actions" to perform)
509 //------------------------------------------------------------------------------
510 // Self-maintenance functions
511 //------------------------------------------------------------------------------
514 function doSurfbarSelfMaintenance () {
515 // Handle URLs which limit has depleted so we can stop them
516 doHandleSurfbarDepletedViews();
518 // Handle low-points amounts
519 doHandleSurfbarLowPoints();
522 // Handle URLs which limit has depleted
523 function doHandleSurfbarDepletedViews () {
525 $urlArray = getSurfbarUrlData(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
527 // Are there some entries?
528 if (count($urlArray) > 0) {
530 foreach ($urlArray as $id => $urlData) {
534 // Rewrite array for next call
540 changeSurfbarUrlStatus($id, 'ACTIVE', 'DEPLETED', $urlData);
545 // Alert users which have URLs booked and are low on points amount
546 function doHandleSurfbarLowPoints () {
548 $userids = determineSurfbarDepletedUserids(getConfig('surfbar_warn_low_points'));
550 // "Walk" through all URLs
551 foreach ($userids['url_userid'] as $userid => $dummy) {
552 // Is the last notification far enougth away to notify again?
553 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
556 'url_userid' => $userid,
557 'points' => $userids['points'][$userid],
558 'notified' => $userids['notified'][$userid]
562 doSurfbarNotifyMember('low_points', $content);
564 // Update last notified
565 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
566 array($userid), __FUNCTION__, __LINE__);
572 //------------------------------------------------------------------------------
574 //------------------------------------------------------------------------------
577 // Looks up by an URL
578 function ifSurfbarHasUrlUserId ($url, $userid) {
579 // Now lookup that given URL by itself
580 $urlArray = getSurfbarUrlData($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
583 return (count($urlArray) > 0);
586 // Load URL data by given search term and column
587 function getSurfbarUrlData ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
588 // By default nothing is found
589 $GLOBALS['last_url_data'] = array();
591 // Is the column an id number?
592 if (($column == 'url_id') || ($column == 'url_userid')) {
593 // Extra secure input
594 $searchTerm = bigintval($searchTerm);
597 // If the column is 'url_id' there can be only one entry
599 if ($column == 'url_id') {
603 // Look up the record
604 $result = SQL_QUERY_ESC("SELECT
612 UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
613 UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
619 `{?_MYSQL_PREFIX?}_surfbar_urls`
621 `%s`='%s'" . $add . "
631 ), __FUNCTION__, __LINE__);
633 // Is there at least one record?
634 if (!SQL_HASZERONUMS($result)) {
636 while ($dataRow = SQL_FETCHARRAY($result)) {
637 // Shall we group these results?
638 if ($group == 'url_id') {
639 // Add the row by id as index
640 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
643 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
649 SQL_FREERESULT($result);
652 return $GLOBALS['last_url_data'];
655 // Registers an URL with the surfbar. You should have called ifSurfbarHasUrlUserId() first!
656 function doSurfbarRegisterUrl ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
657 // Make sure by the user registered URLs are always pending
658 if ($addMode == 'reg') {
663 $content = merge_array($extraFields, array(
665 'url_userid' => $userid,
666 'url_status' => $status,
669 // Is limit/reload set?
670 if (!isset($content['limit'])) {
671 $content['limit'] = '0';
673 if (!isset($content['reload'])) {
674 $content['reload'] = '0';
677 // Insert the URL into database
678 $content['insert_id'] = insertSurfbarUrlByArray($content);
681 if ($content['insert_id'] == '0') {
682 // INSERT did not insert any data!
686 // If in reg-mode we notify admin
687 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
688 // Notify admin even when he as unlocked an email
689 doSurfbarNotifyAdmin('url_' . $addMode, $content);
693 doSurfbarNotifyMember('url_' . $addMode, $content);
695 // Return the insert id
696 return $content['insert_id'];
699 // Inserts an url by given data array and return the insert id
700 function insertSurfbarUrlByArray ($urlData) {
702 $userid = bigintval($urlData['url_userid']);
705 if (empty($userid)) {
709 // Just run the insert query for now
710 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)",
714 $urlData['url_status'],
718 ), __FUNCTION__, __LINE__
722 return SQL_INSERTID();
725 // Notify admin(s) with a selected message and content
726 function doSurfbarNotifyAdmin ($messageType, $content) {
727 // Prepare template name
728 $templateName = sprintf("admin_surfbar_%s", $messageType);
731 $subject = sprintf("{--ADMIN_SURFBAR_NOTIFY_%s_SUBJECT--}",
732 strtoupper($messageType)
735 // Is the subject line there?
736 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
737 // Set default subject if following eval() wents wrong
738 $subject = '{%message,ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT=' . strtoupper($messageType) . '%}';
741 // Translate some data if present
742 $content = prepareSurfbarContentForTemplate($content);
744 // Send the notification out
745 return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
748 // Notify the user about the performed action
749 function doSurfbarNotifyMember ($messageType, $content) {
750 // Skip notification if userid is zero
751 if ($content['url_userid'] == '0') {
755 // Prepare template name
756 $templateName = sprintf("member_surfbar_%s", $messageType);
759 $subject = sprintf("{--MEMBER_SURFBAR_NOTIFY_%s_SUBJECT--}",
760 strtoupper($messageType)
763 // Is the subject line there?
764 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
765 // Set default subject if following eval() wents wrong
766 $subject = '{--MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT--}';
769 // Translate some data if present
770 $content = prepareSurfbarContentForTemplate($content);
773 $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
776 return sendEmail($content['url_userid'], $subject, $mailText);
779 // Translates some data for template usage
780 // @TODO Can't we use our new expression language instead of this ugly code?
781 function prepareSurfbarContentForTemplate ($content) {
783 if (isset($content['url_registered'])) $content['url_registered'] = generateDateTime($content['url_registered'], 2);
784 if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
786 // Return translated content
790 // Translates the limit
791 function translateSurfbarLimit ($limit) {
795 $return = '{--MEMBER_SURFBAR_UNLIMITED_VIEWS--}';
798 $return = '{%pipe,translateComma=' . $limit . '%}';
805 // Translate the URL status
806 function translateSurfbarUrlStatus ($status) {
807 // NULL must be handled carfefully
808 if ((is_null($status)) || (trim($status) == '')) {
809 // Is NULL, so return other language string
810 return '{--SURFBAR_URL_STATUS_NONE--}';
812 // Return regular result
813 return sprintf("{--SURFBAR_URL_STATUS_%s--}", strtoupper($status));
817 // Translates the given action into a link title for members
818 function translateMemberSurfbarActionToTitle ($action) {
820 if (!isset($GLOBALS[__FUNCTION__][$action])) {
821 // Construct default return string (unknown
822 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_TITLE=' . $action . '%}';
824 // ... and the id's name
825 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE';
828 if (isMessageIdValid($messageId)) {
830 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
835 return $GLOBALS[__FUNCTION__][$action];
838 // Translates the given action into a submit button for members
839 function translateMemberSurfbarActionToSubmit ($action) {
841 if (!isset($GLOBALS[__FUNCTION__][$action])) {
842 // Construct default return string (unknown
843 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_SUBMIT=' . $action . '%}';
845 // ... and the id's name
846 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT';
849 if (isMessageIdValid($messageId)) {
851 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
856 return $GLOBALS[__FUNCTION__][$action];
860 function determineSurfbarReward ($onlyMin = FALSE) {
861 // Static values are default
862 $reward = getConfig('surfbar_static_reward');
864 // Is there static or dynamic?
865 if (getSurfbarPaymentModel() == 'DYNAMIC') {
866 // "Calculate" dynamic reward
867 if ($onlyMin === TRUE) {
868 $reward += calculateSurfbarDynamicMininumValue();
870 $reward += calculateSurfbarDynamicAddValue();
879 function determineSurfbarCosts ($onlyMin=false) {
880 // Static costs is default
881 $costs = getConfig('surfbar_static_costs');
883 // Is there static or dynamic?
884 if (getSurfbarPaymentModel() == 'DYNAMIC') {
885 // "Calculate" dynamic costs
887 $costs += calculateSurfbarDynamicMininumValue();
889 $costs += calculateSurfbarDynamicAddValue();
897 // "Calculate" dynamic add
898 function calculateSurfbarDynamicAddValue () {
899 // Get min/max values
900 $min = calculateSurfbarDynamicMininumValue();
901 $max = calculateSurfbarDynamicMaximumValue();
903 // "Calculate" dynamic part and return it
904 return mt_rand($min, $max);
907 // Determine right template name
908 function determineSurfbarTemplateName() {
909 // Default is the frameset
910 $templateName = 'surfbar_frameset';
912 // Any frame set? ;-)
914 // Use the frame as a template name part... ;-)
915 $templateName = sprintf("surfbar_frame_%s",
916 getRequestElement('frame')
921 return $templateName;
925 * Check if the "reload lock" of the current user is full, call this function
926 * before you call ifSurfbarReloadLock().
928 function isSurfbarReloadFull () {
929 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is ' . getConfig('surfbar_static_lock') . ' - ENTERED!');
933 // Cache static reload lock
934 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
936 // Is there dynamic model?
937 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - BEFORE');
938 if (getSurfbarPaymentModel() == 'DYNAMIC') {
939 // "Calculate" dynamic lock
940 $GLOBALS['surfbar_cache']['surf_lock'] += calculateSurfbarDynamicAddValue();
942 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - AFTER');
945 $result = SQL_QUERY_ESC("SELECT
946 COUNT(l.`locks_id`) AS `cnt`
948 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
950 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
952 u.`url_id`=l.`locks_url_id`
954 l.`locks_userid`=%s AND
955 (UNIX_TIMESTAMP() - {%%pipe,getSurfbarSurfLock%%}) < UNIX_TIMESTAMP(l.`locks_last_surfed`) AND
957 ((UNIX_TIMESTAMP(l.`locks_last_surfed`) - u.`url_fixed_reload`) < 0 AND u.`url_fixed_reload` > 0) OR
958 u.`url_fixed_reload` = 0
961 array(getMemberId()), __FUNCTION__, __LINE__
965 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
968 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
969 // Then fix it to zero!
970 $GLOBALS['surfbar_cache']['user_locks'] = '0';
974 SQL_FREERESULT($result);
977 $total = getSurfbarTotalUrls();
979 // Are there some URLs in lock? Admins can always surf on own URLs!
980 $isFull = ((getSurfbarUserLocks() == $total) && ($total > 0));
983 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userLocks=' . getSurfbarUserLocks() . ',total=' . $total . 'isFull=' . intval($isFull) . ' - EXIT!');
987 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
988 function getSurfbarTotalUrls ($status = 'ACTIVE', $excludeUserId = NULL) {
989 // Determine depleted user account
990 $userids = determineSurfbarDepletedUserids();
992 // If we dont get any user ids back, there are no URLs
993 if (count($userids['url_userid']) == 0) {
994 // No user ids found, no URLs!
998 // Is the exlude userid set?
999 if (isValidUserId($excludeUserId)) {
1001 $userids['url_userid'][$excludeUserId] = $excludeUserId;
1004 // Get amount from database
1005 $result = SQL_QUERY_ESC("SELECT
1006 COUNT(`url_id`) AS cnt
1008 `{?_MYSQL_PREFIX?}_surfbar_urls`
1010 (`url_userid` NOT IN (".implode(', ', $userids['url_userid']).") OR `url_userid` IS NULL) AND
1013 array($status), __FUNCTION__, __LINE__
1017 list($count) = SQL_FETCHROW($result);
1020 SQL_FREERESULT($result);
1023 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $count . ' - EXIT!');
1029 // Check whether the user is allowed to book more URLs
1030 function ifSurfbarMemberAllowedMoreUrls ($userid = NULL) {
1031 // Is this admin and userid is zero or does the user has some URLs left to book?
1032 return (((is_null($userid)) && (isAdmin())) || (getSurfbarTotalUserUrls($userid, '', array('REJECTED')) < getSurfbarMaxOrder()));
1035 // Get total amount of URLs of given status for current user
1036 function getSurfbarTotalUserUrls ($userid = NULL, $status = '', $exclude = '') {
1037 // Is the user 0 and user is logged in?
1038 if ((is_null($userid)) && (isMember())) {
1039 // Then use this userid
1040 $userid = getMemberId();
1041 } elseif (is_null($userid)) {
1043 return (getSurfbarMaxOrder() + 1);
1046 // Default is all URLs
1049 // Is the status set?
1050 if (is_array($status)) {
1051 // Only URLs with these status
1052 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
1053 } elseif (!empty($status)) {
1054 // Only URLs with this status
1055 $add = sprintf(" AND `url_status`='%s'", $status);
1056 } elseif (is_array($exclude)) {
1057 // Exclude URLs with these status
1058 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
1059 } elseif (!empty($exclude)) {
1060 // Exclude URLs with this status
1061 $add = sprintf(" AND `url_status` != '%s'", $exclude);
1064 // Get amount from database
1065 $count = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', TRUE, $add);
1071 // Generate a validation code for the given id number
1072 function generateSurfbarValidationCode ($urlId, $salt = '') {
1073 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ' - ENTERED!');
1074 // Init hash with invalid value
1076 // Generate random hashed string
1077 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
1078 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.getSurfbarSalt().'', FALSE);
1080 // Use this as salt!
1081 $GLOBALS['surfbar_cache']['salt'] = $salt;
1082 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.getSurfbarSalt().'', FALSE);
1085 // Hash it with md5() and salt it with the random string
1086 $hashedCode = generateHash(md5($urlId . getEncryptSeparator() . getMemberId()), getSurfbarSalt());
1088 // Finally encrypt it PGP-like and return it
1089 $valHashedCode = encodeHashForCookie($hashedCode);
1091 // Return hashed value
1092 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ',urlId=' . $urlId . ',salt=' . $salt . ',valHashedCode=' . $valHashedCode . ' - EXIT!');
1093 return $valHashedCode;
1096 // Check validation code
1097 function isSurfbarValidationCodeValid ($urlId, $check, $salt) {
1098 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',check=' . $check . ',salt=' . $salt . ' - ENTERED!');
1100 $urlId = bigintval($urlId);
1102 // Now generate the code again
1103 $code = generateSurfbarValidationCode($urlId, $salt);
1105 // Return result of checking hashes and salts
1106 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',(code==check)=' . intval($code == $check) . ',(salt==salts_last_salt)=' . intval($salt == getSurfbarData('salts_last_salt')) . ' - EXIT!');
1107 return (($code == $check) && ($salt == getSurfbarData('salts_last_salt')));
1110 // Lockdown the userid/id combination (reload lock)
1111 function addSurfbarReloadLockById ($urlId) {
1112 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ' - ENTERED!');
1113 // Search for an entry
1114 $countLock = countSumTotalData(getMemberId(), 'surfbar_locks', 'locks_id', 'locks_userid', TRUE, ' AND `locks_url_id`=' . bigintval($urlId));
1116 // Is there no record?
1117 if ($countLock == 0) {
1118 // Just add it to the database
1119 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)',
1123 ), __FUNCTION__, __LINE__);
1126 // Remove the salt from database
1127 SQL_QUERY_ESC('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1',
1131 ), __FUNCTION__, __LINE__);
1133 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1136 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1137 function doSurfbarPayPoints () {
1138 // Remove it from the URL owner
1139 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getSurfbarUserid().',costs='.getSurfbarCosts() . ' - ENTERED!');
1140 if (isValidUserId(getSurfbarUserid())) {
1141 // Subtract points and ignore return status
1142 subtractPoints(sprintf("surfbar_%s", getSurfbarPaymentModel()), getSurfbarUserid(), getSurfbarCosts());
1145 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.getSurfbarReward());
1146 // Init referral system here
1147 initReferralSystem();
1149 // Book it to the user and ignore return status
1150 addPointsThroughReferralSystem(sprintf("surfbar:%s", getSurfbarPaymentModel()), getMemberId(), getSurfbarReward());
1151 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getSurfbarUserid().',costs='.getSurfbarCosts() . ' - EXIT!');
1154 // Updates the statistics of current URL/userid
1155 function updateInsertSurfbarStatisticsRecord () {
1159 // Get allowed views
1160 $allowed = getSurfbarViewsAllowed();
1162 // Is there a limit?
1164 // Then count views_max down!
1165 $add .= ',`url_views_max`=`url_views_max`-1';
1169 SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1' . $add . ' WHERE `url_id`=%s LIMIT 1',
1170 array(getSurfbarId()), __FUNCTION__, __LINE__);
1172 // Update the stats entry
1173 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',
1177 ), __FUNCTION__, __LINE__);
1179 // Was that update okay?
1180 if (SQL_HASZEROAFFECTED()) {
1181 // No, then insert entry
1182 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)',
1186 ), __FUNCTION__, __LINE__);
1189 // Update total/daily/weekly/monthly counter
1190 incrementConfigEntry('surfbar_total_counter');
1191 incrementConfigEntry('surfbar_daily_counter');
1192 incrementConfigEntry('surfbar_weekly_counter');
1193 incrementConfigEntry('surfbar_monthly_counter');
1195 // Update config as well
1196 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1199 // Update the salt for validation and statistics
1200 function updateSurfbarSaltStatistics () {
1202 generateSurfbarValidationCode(getSurfbarId());
1204 // Make sure only valid salts can pass
1205 if (getSurfbarSalt() == 'INVALID') {
1207 reportBug(__FUNCTION__, __LINE__, 'Invalid salt provided, id=' . getSurfbarId() . ',getMemberId()=' . getMemberId());
1210 // Update statistics record
1211 updateInsertSurfbarStatisticsRecord();
1213 // Simply store the salt from cache away in database...
1214 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1219 ), __FUNCTION__, __LINE__);
1222 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . getSurfbarSalt() . ',id=' . getSurfbarId() . ',userid=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - UPDATE!');
1225 if (SQL_HASZEROAFFECTED()) {
1226 // Insert missing entry!
1227 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1232 ), __FUNCTION__, __LINE__);
1236 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1238 // Return if the update was okay
1239 return (!SQL_HASZEROAFFECTED());
1242 // Check if the reload lock is active for given id
1243 function ifSurfbarReloadLock ($urlId) {
1244 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . ' - ENTERED!');
1246 $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1248 `{?_MYSQL_PREFIX?}_surfbar_locks`
1250 `locks_userid`=%s AND
1251 `locks_url_id`=%s AND
1252 (UNIX_TIMESTAMP() - ".getSurfbarSurfLock().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1254 `locks_last_surfed` ASC
1256 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1260 list($count) = SQL_FETCHROW($result);
1263 SQL_FREERESULT($result);
1266 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',count=' . $count . ',getSurfbarSurfLock()=' . getSurfbarSurfLock() . ' - EXIT!');
1267 return ($count == 1);
1270 // Determine which user hash no more points left
1271 function determineSurfbarDepletedUserids ($limit=0) {
1274 'url_userid' => array(),
1275 'points' => array(),
1276 'notified' => array(),
1279 // Is there a current user id?
1280 if ((isMember()) && ($limit == '0')) {
1281 // Then add this as well
1282 $userids['url_userid'][getMemberId()] = getMemberId();
1283 $userids['points'][getMemberId()] = getTotalPoints(getMemberId());
1284 $userids['notified'][getMemberId()] = '0';
1286 // Get all userid except logged in one
1287 $result = SQL_QUERY_ESC("SELECT
1288 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1290 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1292 `{?_MYSQL_PREFIX?}_user_data` AS d
1294 u.`url_userid`=d.`userid`
1296 u.`url_userid` NOT IN (%s) AND
1297 u.`url_userid` IS NOT NULL AND
1298 u.`url_status`='ACTIVE'
1302 u.`url_userid` ASC",
1303 array(getMemberId()), __FUNCTION__, __LINE__);
1306 $result = SQL_QUERY("SELECT
1307 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1309 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1311 `{?_MYSQL_PREFIX?}_user_data` AS d
1313 u.`url_userid`=d.`userid`
1315 u.`url_userid` > 0 AND
1316 u.`url_status`='ACTIVE'
1320 u.`url_userid` ASC", __FUNCTION__, __LINE__);
1324 while ($content = SQL_FETCHARRAY($result)) {
1326 $points = getTotalPoints($content['url_userid']);
1327 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ',points=' . $points);
1329 // Shall we add this to ignore?
1330 if ($points <= $limit) {
1332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ' has depleted points amount!');
1333 $userids['url_userid'][$content['url_userid']] = $content['url_userid'];
1334 $userids['points'][$content['url_userid']] = $points;
1335 $userids['notified'][$content['url_userid']] = $content['notified'];
1340 SQL_FREERESULT($result);
1343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UIDs::count=' . count($userids) . ' (with own userid=' . getMemberId() . ')');
1349 // Determine how many users are Online in surfbar
1350 function determineSurfbarTotalOnline () {
1351 // Count all users in surfbar modue and return the value
1352 $result = SQL_QUERY('SELECT
1355 `{?_MYSQL_PREFIX?}_surfbar_stats`
1357 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1359 `stats_userid` ASC', __FUNCTION__, __LINE__);
1362 $count = SQL_NUMROWS($result);
1365 SQL_FREERESULT($result);
1371 // Determine waiting time for one URL
1372 function determineSurfbarWaitingTime () {
1373 // Get fixed reload lock
1374 $fixed = getSurfbarFixedReload();
1376 // Is the fixed reload time set?
1382 // Static time is default
1383 $time = getConfig('surfbar_static_time');
1385 // Which payment model do we have?
1386 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1387 // "Calculate" dynamic time
1388 $time += calculateSurfbarDynamicAddValue();
1395 // Changes the status of an URL from given to other
1396 function changeSurfbarUrlStatus ($urlId, $prevStatus, $newStatus, $data = array()) {
1397 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',data[]=' . gettype($data) . ',newStatus=' . $newStatus . ' - ENTERED!');
1398 // Make new status always lower-case
1399 $newStatus = strtolower($newStatus);
1401 // Get URL data for status comparison if missing
1402 if ((!is_array($data)) || (count($data) == 0)) {
1403 // Fetch missing URL data
1404 $data = getSurfbarUrlData($urlId);
1408 $filterData = array(
1410 'prev_status' => $prevStatus,
1411 'new_status' => $newStatus,
1416 // Run pre filter chain
1417 $filterData = runFilterChain('pre_change_surfbar_url_status', $filterData);
1420 if (!is_null($filterData['abort'])) {
1422 return $filterData['abort'];
1425 // Update the status now
1426 // ---------- Comment out for debugging/developing member actions! ---------
1427 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_status`='%s' WHERE `url_id`=%s LIMIT 1",
1431 ), __FUNCTION__, __LINE__);
1432 // ---------- Comment out for debugging/developing member actions! ---------
1435 // ---------- Comment out for debugging/developing member actions! ---------
1436 if (SQL_AFFECTEDROWS() != 1) {
1437 // No, something went wrong
1440 // ---------- Comment out for debugging/developing member actions! ---------
1442 // Run post filter chain
1443 $filterData = runFilterChain('post_change_surfbar_url_status', $filterData);
1445 // Check if generic 'data' is there
1446 assert(isset($filterData['data']));
1449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - EXIT!');
1453 // Calculate minimum value for dynamic payment model
1454 function calculateSurfbarDynamicMininumValue () {
1455 // Addon is zero by default
1459 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1462 $totalUsers = getTotalConfirmedUser();
1465 $onlineUsers = determineSurfbarTotalOnline();
1468 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1471 $totalUrls = getSurfbarTotalUrls('ACTIVE', 0);
1473 // Get user's total URLs
1474 $userUrls = getSurfbarTotalUserUrls(0, 'ACTIVE');
1477 if ($totalUrls > 0) {
1478 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1480 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1487 // Calculate maximum value for dynamic payment model
1488 function calculateSurfbarDynamicMaximumValue () {
1489 // Addon is zero by default
1496 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1499 $totalUsers = getTotalConfirmedUser();
1502 $addon += abs($max * $percent * $totalUsers);
1505 $totalUrls = getSurfbarTotalUrls('ACTIVE', 0);
1508 $addon += abs($max * $percent * $totalUrls);
1514 // Calculate dynamic lock
1515 function calculateSurfbarDynamicLock () {
1516 // Default lock is 30 seconds
1520 $onlineUsers = determineSurfbarTotalOnline();
1523 $addon = abs(log($onlineUsers / $addon + 1));
1529 // "Getter" for lock ids array
1530 function getSurfbarLockIdsArray () {
1531 // Prepare some arrays
1536 // Get all id from locks within the timestamp
1537 $result = SQL_QUERY_ESC("SELECT
1540 UNIX_TIMESTAMP(`locks_last_surfed`) AS `last_surfed`
1542 `{?_MYSQL_PREFIX?}_surfbar_locks`
1546 `locks_id` ASC", array(getMemberId()),
1547 __FUNCTION__, __LINE__);
1550 while ($content = SQL_FETCHARRAY($result)) {
1552 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',rest='.(time() - $content['last_surfed']).'/'.getSurfbarSurfLock());
1554 // Skip entries that are too old
1555 if (($content['last_surfed'] > (time() - getSurfbarSurfLock())) && (!in_array($content['locks_url_id'], $ignored))) {
1557 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1559 // Add only if missing or bigger
1560 if ((!isset($IDs[$content['locks_url_id']])) || ($IDs[$content['locks_url_id']] > $content['last_surfed'])) {
1562 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1565 $IDs[$content['locks_url_id']] = $content['last_surfed'];
1566 $USE[$content['locks_url_id']] = $content['locks_id'];
1570 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1572 // Ignore these old entries!
1573 array_push($ignored, $content['locks_url_id']);
1574 unset($IDs[$content['locks_url_id']]);
1575 unset($USE[$content['locks_url_id']]);
1580 SQL_FREERESULT($result);
1586 // "Getter" for maximum random number
1587 function getSurfbarMaximumRandom ($userids, $add) {
1588 // Count max availabe entries
1589 $result = SQL_QUERY("SELECT
1592 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1594 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1596 sbu.url_id=sbs.salts_url_id
1598 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1600 sbu.url_id=l.locks_url_id
1602 sbu.url_userid NOT IN (" . implode(',', $userids) . ") AND
1603 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1604 sbu.url_status='ACTIVE'
1607 sbu.url_id ASC", __FUNCTION__, __LINE__);
1610 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1613 $maxRand = SQL_NUMROWS($result);
1616 SQL_FREERESULT($result);
1622 // Load all URLs of the current user and return it as an array
1623 function getSurfbarUserUrls () {
1625 $urlArray = array();
1628 $result = SQL_QUERY_ESC("SELECT
1633 u.`url_views_total`,
1635 u.`url_views_allowed`,
1636 UNIX_TIMESTAMP(u.`url_registered`) AS `url_registered`,
1637 UNIX_TIMESTAMP(u.`url_last_locked`) AS `url_last_locked`,
1640 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1642 u.`url_userid`=%s AND
1643 u.`url_status` != 'DELETED'
1646 array(getMemberId()), __FUNCTION__, __LINE__);
1648 // Are there entries?
1649 if (!SQL_HASZERONUMS($result)) {
1651 while ($row = SQL_FETCHARRAY($result)) {
1653 $urlArray[$row['url_id']] = $row;
1658 SQL_FREERESULT($result);
1664 // "Getter" for member action array for given status
1665 function getSurfbarArrayFromStatus ($status) {
1667 $returnArray = array();
1669 // Get all assigned actions
1670 $result = SQL_QUERY_ESC("SELECT `actions_action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1671 array($status), __FUNCTION__, __LINE__);
1673 // Some entries there?
1674 if (!SQL_HASZERONUMS($result)) {
1676 // @TODO This can be somehow rewritten
1677 while ($content = SQL_FETCHARRAY($result)) {
1678 array_push($returnArray, $content['actions_action']);
1683 SQL_FREERESULT($result);
1686 return $returnArray;
1689 // Reload to configured stop page
1690 function redirectToSurfbarStopPage ($page = 'stop') {
1691 // Internal or external?
1692 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'page=' . $page . ' - ENTERED!');
1693 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1694 // Reload to internal page
1695 redirectToUrl('surfbar.php?frame=' . $page);
1697 // Reload to external page
1698 redirectToConfiguredUrl('surfbar_pause_url');
1703 * Determine next id for surfbar or get data for given id, always call this
1704 * before you call other getters below this function!
1706 function determineSurfbarNextId ($urlId = NULL) {
1707 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ' - ENTERED!');
1708 // Default is no id and no random number
1713 if (is_null($urlId)) {
1714 // Get array with lock ids
1715 $USE = getSurfbarLockIdsArray();
1717 // Shall we add some URL ids to ignore?
1719 if (count($USE) > 0) {
1721 $add = " AND sbu.`url_id` NOT IN (";
1722 foreach ($USE as $url_id => $lid) {
1724 $add .= $url_id.',';
1727 // Add closing bracket
1728 $add = substr($add, 0, -1) . ')';
1731 // Determine depleted user account
1732 $userids = determineSurfbarDepletedUserids();
1734 // Get maximum randomness factor
1735 $maxRand = getSurfbarMaximumRandom($userids['url_userid'], $add);
1737 // If more than one URL can be called generate the random number!
1739 // Generate random number
1740 $randNum = mt_rand(0, ($maxRand - 1));
1743 // And query the database
1744 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.getSurfbarSurfLock());
1745 $result = SQL_QUERY_ESC("SELECT
1749 sbs.salts_last_salt,
1750 sbu.url_views_total,
1752 sbu.url_views_allowed,
1753 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1754 sbu.url_fixed_reload
1756 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1758 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1760 sbu.url_id=sbs.salts_url_id
1762 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1764 sbu.url_id=l.locks_url_id
1766 (sbu.`url_userid` NOT IN (".implode(',', $userids['url_userid']).") OR sbu.`url_userid` IS NULL) AND
1767 sbu.url_status='ACTIVE' AND
1768 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1773 l.locks_last_surfed ASC,
1776 array($randNum), __FUNCTION__, __LINE__
1779 // Get data from specified id number
1780 $result = SQL_QUERY_ESC("SELECT
1784 sbs.salts_last_salt,
1785 sbu.url_views_total,
1787 sbu.url_views_allowed,
1788 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1789 sbu.url_fixed_reload
1791 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1793 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1795 sbu.url_id=sbs.salts_url_id
1797 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1799 sbu.url_id=l.locks_url_id
1801 (sbu.url_userid != %s OR sbu.url_userid IS NULL) AND
1802 sbu.url_status='ACTIVE' AND
1804 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1806 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1810 // Is there an id number?
1811 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1812 if (SQL_NUMROWS($result) == 1) {
1814 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', FALSE);
1815 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1816 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', FALSE);
1818 // Determine waiting time
1819 $GLOBALS['surfbar_cache']['time'] = determineSurfbarWaitingTime();
1821 // Is the last salt there?
1822 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1823 // Then repair it wit the static!
1824 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', FALSE);
1825 $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1828 // Fix missing last_surfed
1829 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1831 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', FALSE);
1832 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1835 // Get base/fixed reward and costs
1836 $GLOBALS['surfbar_cache']['reward'] = determineSurfbarReward();
1837 $GLOBALS['surfbar_cache']['costs'] = determineSurfbarCosts();
1838 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.getSurfbarReward().'|costs='.getSurfbarCosts());
1840 // Only in dynamic model add the dynamic bonus!
1841 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1842 // Calculate dynamic reward/costs and add it
1843 $GLOBALS['surfbar_cache']['reward'] += calculateSurfbarDynamicAddValue();
1844 $GLOBALS['surfbar_cache']['costs'] += calculateSurfbarDynamicAddValue();
1845 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.getSurfbarReward().'|costs='.getSurfbarCosts());
1849 $nextId = getSurfbarId();
1853 SQL_FREERESULT($result);
1856 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',nextId=' . $nextId . ' - EXIT!');
1860 //-----------------------------------------------------------------------------
1862 //-----------------------------------------------------------------------------
1864 // "Getter" for surfbar_dynamic_percent
1865 function getSurfbarDynamicPercent () {
1867 if (!isset($GLOBALS[__FUNCTION__])) {
1869 $GLOBALS[__FUNCTION__] = getConfig('surfbar_dynamic_percent');
1873 return $GLOBALS[__FUNCTION__];
1876 // "Getter" for surfbar_static_reward
1877 function getSurfbarStaticReward () {
1879 if (!isset($GLOBALS[__FUNCTION__])) {
1881 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_reward');
1885 return $GLOBALS[__FUNCTION__];
1888 // "Getter" for surfbar_static_time
1889 function getSurfbarStaticTime () {
1891 if (!isset($GLOBALS[__FUNCTION__])) {
1893 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_time');
1897 return $GLOBALS[__FUNCTION__];
1900 // "Getter" for surfbar_max_order
1901 function getSurfbarMaxOrder () {
1903 if (!isset($GLOBALS[__FUNCTION__])) {
1905 $GLOBALS[__FUNCTION__] = getConfig('surfbar_max_order');
1909 return $GLOBALS[__FUNCTION__];
1912 // "Getter" for surfbar_payment_model
1913 function getSurfbarPaymentModel () {
1915 if (!isset($GLOBALS[__FUNCTION__])) {
1917 $GLOBALS[__FUNCTION__] = getConfig('surfbar_payment_model');
1921 return $GLOBALS[__FUNCTION__];
1924 // "Getter" for surfbar_stats_reload
1925 function getSurfbarStatsReload () {
1927 if (!isset($GLOBALS[__FUNCTION__])) {
1929 $GLOBALS[__FUNCTION__] = getConfig('surfbar_stats_reload');
1933 return $GLOBALS[__FUNCTION__];
1936 //------------------------------------------------------------------------------
1937 // Template helper functions
1938 //------------------------------------------------------------------------------
1940 // Template helper to generate a selection box for surfbar actions
1941 function doTemplateSurfbarActionsActionSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
1943 $actionsAction = array(
1944 0 => array('actions_action' => 'EDIT'),
1945 1 => array('actions_action' => 'DELETE'),
1946 2 => array('actions_action' => 'PAUSE'),
1947 3 => array('actions_action' => 'UNPAUSE'),
1948 4 => array('actions_action' => 'FRAMETEST'),
1949 5 => array('actions_action' => 'RETREAT'),
1950 6 => array('actions_action' => 'RESUBMIT'),
1951 7 => array('actions_action' => 'BOOKNOW')
1954 // Handle it over to generateSelectionBoxFromArray()
1955 $content = generateSelectionBoxFromArray($actionsAction, 'actions_action', 'actions_action', '', '_surfbar', '', $default, '', FALSE, TRUE);
1957 // Return prepared content
1961 // Template helper to generate a selection box for surfbar status
1962 function doTemplateSurfbarActionsStatusSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
1965 0 => array('actions_status' => 'PENDING'),
1966 1 => array('actions_status' => 'ACTIVE'),
1967 2 => array('actions_status' => 'LOCKED'),
1968 3 => array('actions_status' => 'STOPPED'),
1969 4 => array('actions_status' => 'REJECTED'),
1970 5 => array('actions_status' => 'DELETED'),
1971 6 => array('actions_status' => 'MIGRATED'),
1972 7 => array('actions_status' => 'DEPLETED')
1975 // Handle it over to generateSelectionBoxFromArray()
1976 $content = generateSelectionBoxFromArray($status, 'actions_status', 'actions_status', '', '_surfbar', '', $default, '', FALSE, TRUE);
1978 // Return prepared content
1982 // Template helper to generate a selection box for surfbar status
1983 function doTemplateSurfbarActionsNewStatusSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
1986 0 => array('actions_new_status' => 'PENDING'),
1987 1 => array('actions_new_status' => 'ACTIVE'),
1988 2 => array('actions_new_status' => 'LOCKED'),
1989 3 => array('actions_new_status' => 'STOPPED'),
1990 4 => array('actions_new_status' => 'REJECTED'),
1991 5 => array('actions_new_status' => 'DELETED'),
1992 6 => array('actions_new_status' => 'MIGRATED'),
1993 7 => array('actions_new_status' => 'DEPLETED')
1996 // Handle it over to generateSelectionBoxFromArray()
1997 $content = generateSelectionBoxFromArray($status, 'actions_new_status', 'actions_new_status', '', '_surfbar', '', $default, '', TRUE, TRUE);
1999 // Return prepared content
2003 //------------------------------------------------------------------------------
2004 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
2005 // THE $GLOBALS['surfbar_cache'] ARRAY!
2006 //------------------------------------------------------------------------------
2008 // Initializes the surfbar
2009 function initSurfbar () {
2011 $GLOBALS['surfbar_cache'] = array();
2014 // Private getter for data elements
2015 function getSurfbarData ($element) {
2016 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element=' . $element . ' - ENTERED!');
2021 // Is the entry there?
2022 if (!isset($GLOBALS['surfbar_cache'][$element])) {
2023 print('surfbar_cache=<pre>');
2024 print_r($GLOBALS['surfbar_cache']);
2026 reportBug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
2030 $data = $GLOBALS['surfbar_cache'][$element];
2033 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data . ' - EXIT!');
2037 // Getter for reward from cache
2038 function getSurfbarReward () {
2039 // Get data element and return its contents
2040 return getSurfbarData('reward');
2043 // Getter for costs from cache
2044 function getSurfbarCosts () {
2045 // Get data element and return its contents
2046 return getSurfbarData('costs');
2049 // Getter for URL from cache
2050 function getSurfbarUrl () {
2051 // Get data element and return its contents
2052 return getSurfbarData('url');
2055 // Getter for salt from cache
2056 function getSurfbarSalt () {
2057 // Get data element and return its contents
2058 return getSurfbarData('salt');
2061 // Getter for id from cache
2062 function getSurfbarId () {
2063 // Get data element and return its contents
2064 return getSurfbarData('url_id');
2067 // Getter for userid from cache
2068 function getSurfbarUserid () {
2069 // Get data element and return its contents
2070 return getSurfbarData('url_userid');
2073 // Getter for user reload locks
2074 function getSurfbarUserLocks () {
2075 // Get data element and return its contents
2076 return getSurfbarData('user_locks');
2079 // Getter for reload time
2080 function getSurfbarReloadTime () {
2081 // Get data element and return its contents
2082 return getSurfbarData('time');
2085 // Getter for allowed views
2086 function getSurfbarViewsAllowed () {
2087 // Get data element and return its contents
2088 return getSurfbarData('url_views_allowed');
2091 // Getter for maximum views
2092 function getSurfbarViewsMax () {
2093 // Get data element and return its contents
2094 return getSurfbarData('url_views_max');
2097 // Getter for fixed reload
2098 function getSurfbarFixedReload () {
2099 // Get data element and return its contents
2100 return getSurfbarData('url_fixed_reload');
2103 // Getter for surf lock
2104 function getSurfbarSurfLock () {
2105 // Get data element and return its contents
2106 return getSurfbarData('surf_lock');
2109 // Getter for new status
2110 function getSurfbarNewStatus () {
2111 // Get data element and return its contents
2112 return getSurfbarData('new_status');
2115 // Getter for last salt
2116 function getSurfbarLastSalt () {
2117 // Get data element and return its contents
2118 return getSurfbarData('salts_last_salt');