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)) {
263 $urlArray[$formData['url_id']]['new_status'] = gerSurfbarNewStatus('new_status');
265 // Extract URL data for call-back
266 $urlData = array(merge_array($urlArray[$formData['url_id']], array($action => $formData)));
268 // Action found so execute it
269 $performed = call_user_func_array($functionName, $urlData);
271 // Log invalid request
272 reportBug(__FUNCTION__, __LINE__, 'Invalid member action! action=' . $formData['action'] . ',url_id=' . $formData['url_id'] . ',function=' . $functionName);
279 // Getter for surfbar_actions table by given id number
280 function getSurfbarActionsDataById ($columnName, $id) {
282 if (!isset($GLOBALS[__FUNCTION__][$id][$columnName])) {
283 // Default is not found
284 $GLOBALS[__FUNCTION__][$id][$columnName] = '*INVALID*';
287 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_id`=%s LIMIT 1",
291 ), __FUNCTION__, __LINE__);
293 // Is there an entry?
294 if (SQL_NUMROWS($result) == 1) {
296 list($GLOBALS[__FUNCTION__][$id][$columnName]) = SQL_FETCHROW($result);
300 SQL_FREERESULT($result);
304 return $GLOBALS[__FUNCTION__][$id][$columnName];
307 // Validate if the requested action can be performed on current URL status
308 function isSurfbarMemberActionStatusValid ($action, $status) {
309 // Search for the requested action/status combination in database
310 $result = SQL_QUERY_ESC("SELECT `actions_new_status` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_action`='%s' AND `actions_status`='%s' LIMIT 1",
314 ), __FUNCTION__, __LINE__);
316 // Is the entry there?
317 $isValid = (SQL_NUMROWS($result) == 1);
320 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'action=' . $action . ',status=' . $status . ',isValid=' . intval($isValid));
322 // Fetch the new status if found
323 if ($isValid === true) {
325 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
329 SQL_FREERESULT($result);
335 //------------------------------------------------------------------------------
337 //------------------------------------------------------------------------------
339 // Retreat a booked URL
340 function doSurfbarMemberRetreatAction ($urlData) {
341 // Create the data array for next function call
343 $urlData['url_id'] => $urlData
346 // Simply change the status here
347 return changeSurfbarUrlStatus ($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], $data);
350 // Book an URL now (from migration)
351 function doSurfbarMemberBooknowAction ($urlData) {
352 // Create the data array for next function call
354 $urlData['url_id'] => $urlData
357 // Simply change the status here
358 return changeSurfbarUrlStatus ($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], $data);
361 // Show edit form or do the changes
362 function doSurfbarMemberEditAction ($urlData) {
363 // Is the "execute" flag there?
364 if (isset($urlData['edit']['execute'])) {
365 // Execute the changes
366 return executeSurfbarMemberAction('edit', $urlData);
370 return displaySurfbarMemberActionForm('edit', $urlData);
373 // Show delete form or do the changes
374 function doSurfbarMemberDeleteAction ($urlData) {
375 // Is the "execute" flag there?
376 if (isset($urlData['delete']['execute'])) {
377 // Execute the changes
378 return executeSurfbarMemberAction('delete', $urlData);
382 return displaySurfbarMemberActionForm('delete', $urlData);
385 // Pause active banner
386 function doSurfbarMemberPauseAction ($urlData) {
387 return changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
390 // Unpause stopped banner
391 function doSurfbarMemberUnpauseAction ($urlData) {
392 // Fix missing entry for template
393 $urlData['edit'] = $urlData['unpause'];
394 $urlData['edit']['url'] = $urlData['url'];
395 $urlData['edit']['limit'] = gerSurfbarViewsMax();
397 // Return status change
398 return changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
401 // Resubmit locked URL
402 function doSurfbarMemberResubmitAction ($urlData) {
403 return changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
406 // Display selected "action form"
407 function displaySurfbarMemberActionForm ($action, $urlData) {
408 // Translate some data if present
409 $content = prepareSurfbarContentForTemplate($content);
411 // Include fields only for action 'edit'
412 if ($action == 'edit') {
413 // Default is not limited
414 $urlData['limited_yes'] = '';
415 $urlData['limited_no'] = ' checked="checked"';
416 $urlData['limited'] = 'false';
418 // Is this URL limited?
419 if (gerSurfbarViewsMax() > 0) {
420 // Then rewrite form data
421 $urlData['limited_yes'] = ' checked="checked"';
422 $urlData['limited_no'] = '';
423 $urlData['limited'] = 'true';
427 // Load the form and display it
428 loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
430 // All fine by default ... ;-)
434 // Execute choosen action
435 function executeSurfbarMemberAction ($action, $urlData) {
436 // By default nothing is executed
439 // Is limitation "no" and "limit" is > 0?
440 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
441 // Set it to unlimited
442 $urlData[$action]['limit'] = '0';
445 // Construct function name
446 $functionName = sprintf("executeSurfbarMember%sAction", firstCharUpperCase($action));
448 // Is that function there?
449 if (function_exists($functionName)) {
450 // Execute the function
451 if (call_user_func_array($functionName, array($urlData)) == true) {
452 // Update status as well
453 $executed = changeSurfbarUrlStatus($urlData['url_id'], $urlData['url_status'], $urlData['new_status'], array($urlData['url_id'] => $urlData));
457 reportBug(__FUNCTION__, __LINE__, 'Callback function ' . $functionName . ' does not exist.');
464 // "Execute edit" function: Update changed data
465 function executeSurfbarMemberEditAction ($urlData) {
466 // Default is nothing done
469 // Has the URL or limit changed?
471 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
473 SQL_QUERY_ESC("UPDATE
474 `{?_MYSQL_PREFIX?}_surfbar_urls`
477 `url_views_allowed`=%s,
485 $urlData['edit']['limit'],
486 $urlData['edit']['limit'],
488 $urlData['url_status']
489 ), __FUNCTION__, __LINE__);
499 // "Execute delete" function: Does nothing...
500 function executeSurfbarMemberDeleteAction ($urlData) {
501 // Nothing special to do (see above function for such "special actions" to perform)
505 //------------------------------------------------------------------------------
506 // Self-maintenance functions
507 //------------------------------------------------------------------------------
510 function doSurfbarSelfMaintenance () {
511 // Handle URLs which limit has depleted so we can stop them
512 doHandleSurfbarDepletedViews();
514 // Handle low-points amounts
515 doHandleSurfbarLowPoints();
518 // Handle URLs which limit has depleted
519 function doHandleSurfbarDepletedViews () {
521 $urlArray = getSurfbarUrlData(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
523 // Are there some entries?
524 if (count($urlArray) > 0) {
526 foreach ($urlArray as $id => $urlData) {
530 // Rewrite array for next call
536 changeSurfbarUrlStatus($id, 'ACTIVE', 'DEPLETED', $urlData);
541 // Alert users which have URLs booked and are low on points amount
542 function doHandleSurfbarLowPoints () {
544 $userids = determineSurfbarDepletedUserids(getConfig('surfbar_warn_low_points'));
546 // "Walk" through all URLs
547 foreach ($userids['url_userid'] as $userid => $dummy) {
548 // Is the last notification far enougth away to notify again?
549 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
552 'url_userid' => $userid,
553 'points' => $userids['points'][$userid],
554 'notified' => $userids['notified'][$userid]
558 doSurfbarNotifyMember('low_points', $content);
560 // Update last notified
561 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
562 array($userid), __FUNCTION__, __LINE__);
568 //------------------------------------------------------------------------------
570 //------------------------------------------------------------------------------
573 // Looks up by an URL
574 function ifSurfbarHasUrlUserId ($url, $userid) {
575 // Now lookup that given URL by itself
576 $urlArray = getSurfbarUrlData($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
579 return (count($urlArray) > 0);
582 // Load URL data by given search term and column
583 function getSurfbarUrlData ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
584 // By default nothing is found
585 $GLOBALS['last_url_data'] = array();
587 // Is the column an id number?
588 if (($column == 'url_id') || ($column == 'url_userid')) {
589 // Extra secure input
590 $searchTerm = bigintval($searchTerm);
593 // If the column is 'url_id' there can be only one entry
595 if ($column == 'url_id') {
599 // Look up the record
600 $result = SQL_QUERY_ESC("SELECT
608 UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
609 UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
615 `{?_MYSQL_PREFIX?}_surfbar_urls`
617 `%s`='%s'" . $add . "
627 ), __FUNCTION__, __LINE__);
629 // Is there at least one record?
630 if (!SQL_HASZERONUMS($result)) {
632 while ($dataRow = SQL_FETCHARRAY($result)) {
633 // Shall we group these results?
634 if ($group == 'url_id') {
635 // Add the row by id as index
636 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
639 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
645 SQL_FREERESULT($result);
648 return $GLOBALS['last_url_data'];
651 // Registers an URL with the surfbar. You should have called ifSurfbarHasUrlUserId() first!
652 function doSurfbarRegisterUrl ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
653 // Make sure by the user registered URLs are always pending
654 if ($addMode == 'reg') {
659 $content = merge_array($extraFields, array(
661 'url_userid' => $userid,
662 'url_status' => $status,
665 // Is limit/reload set?
666 if (!isset($content['limit'])) {
667 $content['limit'] = '0';
669 if (!isset($content['reload'])) {
670 $content['reload'] = '0';
673 // Insert the URL into database
674 $content['insert_id'] = insertSurfbarUrlByArray($content);
677 if ($content['insert_id'] == '0') {
678 // INSERT did not insert any data!
682 // If in reg-mode we notify admin
683 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
684 // Notify admin even when he as unlocked an email
685 doSurfbarNotifyAdmin('url_' . $addMode, $content);
689 doSurfbarNotifyMember('url_' . $addMode, $content);
691 // Return the insert id
692 return $content['insert_id'];
695 // Inserts an url by given data array and return the insert id
696 function insertSurfbarUrlByArray ($urlData) {
698 $userid = bigintval($urlData['url_userid']);
701 if (empty($userid)) {
705 // Just run the insert query for now
706 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)",
710 $urlData['url_status'],
714 ), __FUNCTION__, __LINE__
718 return SQL_INSERTID();
721 // Notify admin(s) with a selected message and content
722 function doSurfbarNotifyAdmin ($messageType, $content) {
723 // Prepare template name
724 $templateName = sprintf("admin_surfbar_%s", $messageType);
727 $subject = sprintf("{--ADMIN_SURFBAR_NOTIFY_%s_SUBJECT--}",
728 strtoupper($messageType)
731 // Is the subject line there?
732 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
733 // Set default subject if following eval() wents wrong
734 $subject = '{%message,ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT=' . strtoupper($messageType) . '%}';
737 // Translate some data if present
738 $content = prepareSurfbarContentForTemplate($content);
740 // Send the notification out
741 return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
744 // Notify the user about the performed action
745 function doSurfbarNotifyMember ($messageType, $content) {
746 // Skip notification if userid is zero
747 if ($content['url_userid'] == '0') {
751 // Prepare template name
752 $templateName = sprintf("member_surfbar_%s", $messageType);
755 $subject = sprintf("{--MEMBER_SURFBAR_NOTIFY_%s_SUBJECT--}",
756 strtoupper($messageType)
759 // Is the subject line there?
760 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
761 // Set default subject if following eval() wents wrong
762 $subject = '{--MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT--}';
765 // Translate some data if present
766 $content = prepareSurfbarContentForTemplate($content);
769 $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
772 return sendEmail($content['url_userid'], $subject, $mailText);
775 // Translates some data for template usage
776 // @TODO Can't we use our new expression language instead of this ugly code?
777 function prepareSurfbarContentForTemplate ($content) {
779 if (isset($content['url_registered'])) $content['url_registered'] = generateDateTime($content['url_registered'], 2);
780 if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
782 // Return translated content
786 // Translates the limit
787 function translateSurfbarLimit ($limit) {
791 $return = '{--MEMBER_SURFBAR_UNLIMITED_VIEWS--}';
794 $return = '{%pipe,translateComma=' . $limit . '%}';
801 // Translate the URL status
802 function translateSurfbarUrlStatus ($status) {
803 // NULL must be handled carfefully
804 if ((is_null($status)) || (trim($status) == '')) {
805 // Is NULL, so return other language string
806 return '{--SURFBAR_URL_STATUS_NONE--}';
808 // Return regular result
809 return sprintf("{--SURFBAR_URL_STATUS_%s--}", strtoupper($status));
813 // Translates the given action into a link title for members
814 function translateMemberSurfbarActionToTitle ($action) {
816 if (!isset($GLOBALS[__FUNCTION__][$action])) {
817 // Construct default return string (unknown
818 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_TITLE=' . $action . '%}';
820 // ... and the id's name
821 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE';
824 if (isMessageIdValid($messageId)) {
826 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
831 return $GLOBALS[__FUNCTION__][$action];
834 // Translates the given action into a submit button for members
835 function translateMemberSurfbarActionToSubmit ($action) {
837 if (!isset($GLOBALS[__FUNCTION__][$action])) {
838 // Construct default return string (unknown
839 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_SUBMIT=' . $action . '%}';
841 // ... and the id's name
842 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT';
845 if (isMessageIdValid($messageId)) {
847 $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
852 return $GLOBALS[__FUNCTION__][$action];
856 function determineSurfbarReward ($onlyMin = false) {
857 // Static values are default
858 $reward = getConfig('surfbar_static_reward');
860 // Is there static or dynamic?
861 if (getSurfbarPaymentModel() == 'DYNAMIC') {
862 // "Calculate" dynamic reward
863 if ($onlyMin === true) {
864 $reward += calculateSurfbarDynamicMininumValue();
866 $reward += calculateSurfbarDynamicAddValue();
875 function determineSurfbarCosts ($onlyMin=false) {
876 // Static costs is default
877 $costs = getConfig('surfbar_static_costs');
879 // Is there static or dynamic?
880 if (getSurfbarPaymentModel() == 'DYNAMIC') {
881 // "Calculate" dynamic costs
883 $costs += calculateSurfbarDynamicMininumValue();
885 $costs += calculateSurfbarDynamicAddValue();
893 // "Calculate" dynamic add
894 function calculateSurfbarDynamicAddValue () {
895 // Get min/max values
896 $min = calculateSurfbarDynamicMininumValue();
897 $max = calculateSurfbarDynamicMaximumValue();
899 // "Calculate" dynamic part and return it
900 return mt_rand($min, $max);
903 // Determine right template name
904 function determineSurfbarTemplateName() {
905 // Default is the frameset
906 $templateName = 'surfbar_frameset';
908 // Any frame set? ;-)
910 // Use the frame as a template name part... ;-)
911 $templateName = sprintf("surfbar_frame_%s",
912 getRequestElement('frame')
917 return $templateName;
921 * Check if the "reload lock" of the current user is full, call this function
922 * before you call ifSurfbarReloadLock().
924 function isSurfbarReloadFull () {
925 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is ' . getConfig('surfbar_static_lock') . ' - ENTERED!');
929 // Cache static reload lock
930 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
932 // Is there dynamic model?
933 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - BEFORE');
934 if (getSurfbarPaymentModel() == 'DYNAMIC') {
935 // "Calculate" dynamic lock
936 $GLOBALS['surfbar_cache']['surf_lock'] += calculateSurfbarDynamicAddValue();
938 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - AFTER');
941 $result = SQL_QUERY_ESC("SELECT
942 COUNT(l.`locks_id`) AS `cnt`
944 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
946 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
948 u.`url_id`=l.`locks_url_id`
950 l.`locks_userid`=%s AND
951 (UNIX_TIMESTAMP() - {%%pipe,gerSurfbarSurfLock%%}) < UNIX_TIMESTAMP(l.`locks_last_surfed`) AND
953 ((UNIX_TIMESTAMP(l.`locks_last_surfed`) - u.`url_fixed_reload`) < 0 AND u.`url_fixed_reload` > 0) OR
954 u.`url_fixed_reload` = 0
957 array(getMemberId()), __FUNCTION__, __LINE__
961 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
964 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
965 // Then fix it to zero!
966 $GLOBALS['surfbar_cache']['user_locks'] = '0';
970 SQL_FREERESULT($result);
973 $total = getSurfbarTotalUrls();
975 // Are there some URLs in lock? Admins can always surf on own URLs!
976 $isFull = ((getSurfbarUserLocks() == $total) && ($total > 0));
979 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userLocks=' . getSurfbarUserLocks() . ',total=' . $total . 'isFull=' . intval($isFull) . ' - EXIT!');
983 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
984 function getSurfbarTotalUrls ($status = 'ACTIVE', $excludeUserId = NULL) {
985 // Determine depleted user account
986 $userids = determineSurfbarDepletedUserids();
988 // If we dont get any user ids back, there are no URLs
989 if (count($userids['url_userid']) == 0) {
990 // No user ids found, no URLs!
994 // Is the exlude userid set?
995 if (isValidUserId($excludeUserId)) {
997 $userids['url_userid'][$excludeUserId] = $excludeUserId;
1000 // Get amount from database
1001 $result = SQL_QUERY_ESC("SELECT
1002 COUNT(`url_id`) AS cnt
1004 `{?_MYSQL_PREFIX?}_surfbar_urls`
1006 (`url_userid` NOT IN (".implode(', ', $userids['url_userid']).") OR `url_userid` IS NULL) AND
1009 array($status), __FUNCTION__, __LINE__
1013 list($count) = SQL_FETCHROW($result);
1016 SQL_FREERESULT($result);
1019 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $count . ' - EXIT!');
1025 // Check whether the user is allowed to book more URLs
1026 function ifSurfbarMemberAllowedMoreUrls ($userid = NULL) {
1027 // Is this admin and userid is zero or does the user has some URLs left to book?
1028 return (((is_null($userid)) && (isAdmin())) || (getSurfbarTotalUserUrls($userid, '', array('REJECTED')) < getSurfbarMaxOrder()));
1031 // Get total amount of URLs of given status for current user
1032 function getSurfbarTotalUserUrls ($userid = NULL, $status = '', $exclude = '') {
1033 // Is the user 0 and user is logged in?
1034 if ((is_null($userid)) && (isMember())) {
1035 // Then use this userid
1036 $userid = getMemberId();
1037 } elseif (is_null($userid)) {
1039 return (getSurfbarMaxOrder() + 1);
1042 // Default is all URLs
1045 // Is the status set?
1046 if (is_array($status)) {
1047 // Only URLs with these status
1048 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
1049 } elseif (!empty($status)) {
1050 // Only URLs with this status
1051 $add = sprintf(" AND `url_status`='%s'", $status);
1052 } elseif (is_array($exclude)) {
1053 // Exclude URLs with these status
1054 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
1055 } elseif (!empty($exclude)) {
1056 // Exclude URLs with this status
1057 $add = sprintf(" AND `url_status` != '%s'", $exclude);
1060 // Get amount from database
1061 $count = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
1067 // Generate a validation code for the given id number
1068 function generateSurfbarValidationCode ($urlId, $salt = '') {
1069 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ' - ENTERED!');
1070 // Init hash with invalid value
1072 // Generate random hashed string
1073 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
1074 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.gerSurfbarSalt().'', false);
1076 // Use this as salt!
1077 $GLOBALS['surfbar_cache']['salt'] = $salt;
1078 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.gerSurfbarSalt().'', false);
1081 // Hash it with md5() and salt it with the random string
1082 $hashedCode = generateHash(md5($urlId . getEncryptSeparator() . getMemberId()), gerSurfbarSalt());
1084 // Finally encrypt it PGP-like and return it
1085 $valHashedCode = encodeHashForCookie($hashedCode);
1087 // Return hashed value
1088 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ',urlId=' . $urlId . ',salt=' . $salt . ',valHashedCode=' . $valHashedCode . ' - EXIT!');
1089 return $valHashedCode;
1092 // Check validation code
1093 function isSurfbarValidationCodeValid ($urlId, $check, $salt) {
1094 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',check=' . $check . ',salt=' . $salt . ' - ENTERED!');
1096 $urlId = bigintval($urlId);
1098 // Now generate the code again
1099 $code = generateSurfbarValidationCode($urlId, $salt);
1101 // Return result of checking hashes and salts
1102 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',(code==check)=' . intval($code == $check) . ',(salt==salts_last_salt)=' . intval($salt == getSurfbarData('salts_last_salt')) . ' - EXIT!');
1103 return (($code == $check) && ($salt == getSurfbarData('salts_last_salt')));
1106 // Lockdown the userid/id combination (reload lock)
1107 function addSurfbarReloadLockById ($urlId) {
1108 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ' - ENTERED!');
1109 // Search for an entry
1110 $countLock = countSumTotalData(getMemberId(), 'surfbar_locks', 'locks_id', 'locks_userid', true, ' AND `locks_url_id`=' . bigintval($urlId));
1112 // Is there no record?
1113 if ($countLock == 0) {
1114 // Just add it to the database
1115 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)',
1119 ), __FUNCTION__, __LINE__);
1122 // Remove the salt from database
1123 SQL_QUERY_ESC('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1',
1127 ), __FUNCTION__, __LINE__);
1129 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1132 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1133 function doSurfbarPayPoints () {
1134 // Remove it from the URL owner
1135 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.gerSurfbarUserid().',costs='.gerSurfbarCosts() . ' - ENTERED!');
1136 if (isValidUserId(gerSurfbarUserid())) {
1137 // Subtract points and ignore return status
1138 subtractPoints(sprintf("surfbar_%s", getSurfbarPaymentModel()), gerSurfbarUserid(), gerSurfbarCosts());
1141 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.gerSurfbarReward());
1142 // Init referral system here
1143 initReferralSystem();
1145 // Book it to the user and ignore return status
1146 addPointsThroughReferralSystem(sprintf("surfbar:%s", getSurfbarPaymentModel()), getMemberId(), gerSurfbarReward());
1147 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.gerSurfbarUserid().',costs='.gerSurfbarCosts() . ' - EXIT!');
1150 // Updates the statistics of current URL/userid
1151 function updateInsertSurfbarStatisticsRecord () {
1155 // Get allowed views
1156 $allowed = gerSurfbarViewsAllowed();
1158 // Is there a limit?
1160 // Then count views_max down!
1161 $add .= ',`url_views_max`=`url_views_max`-1';
1165 SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1' . $add . ' WHERE `url_id`=%s LIMIT 1',
1166 array(gerSurfbarId()), __FUNCTION__, __LINE__);
1168 // Update the stats entry
1169 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',
1173 ), __FUNCTION__, __LINE__);
1175 // Was that update okay?
1176 if (SQL_HASZEROAFFECTED()) {
1177 // No, then insert entry
1178 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)',
1182 ), __FUNCTION__, __LINE__);
1185 // Update total/daily/weekly/monthly counter
1186 incrementConfigEntry('surfbar_total_counter');
1187 incrementConfigEntry('surfbar_daily_counter');
1188 incrementConfigEntry('surfbar_weekly_counter');
1189 incrementConfigEntry('surfbar_monthly_counter');
1191 // Update config as well
1192 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1195 // Update the salt for validation and statistics
1196 function updateSurfbarSaltStatistics () {
1198 generateSurfbarValidationCode(gerSurfbarId());
1200 // Make sure only valid salts can pass
1201 if (gerSurfbarSalt() == 'INVALID') {
1203 reportBug(__FUNCTION__, __LINE__, 'Invalid salt provided, id=' . gerSurfbarId() . ',getMemberId()=' . getMemberId());
1206 // Update statistics record
1207 updateInsertSurfbarStatisticsRecord();
1209 // Simply store the salt from cache away in database...
1210 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1215 ), __FUNCTION__, __LINE__);
1218 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . gerSurfbarSalt() . ',id=' . gerSurfbarId() . ',userid=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - UPDATE!');
1221 if (SQL_HASZEROAFFECTED()) {
1222 // Insert missing entry!
1223 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1228 ), __FUNCTION__, __LINE__);
1232 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1234 // Return if the update was okay
1235 return (!SQL_HASZEROAFFECTED());
1238 // Check if the reload lock is active for given id
1239 function ifSurfbarReloadLock ($urlId) {
1240 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . ' - ENTERED!');
1242 $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1244 `{?_MYSQL_PREFIX?}_surfbar_locks`
1246 `locks_userid`=%s AND
1247 `locks_url_id`=%s AND
1248 (UNIX_TIMESTAMP() - ".gerSurfbarSurfLock().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1250 `locks_last_surfed` ASC
1252 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1256 list($count) = SQL_FETCHROW($result);
1259 SQL_FREERESULT($result);
1262 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',count=' . $count . ',gerSurfbarSurfLock()=' . gerSurfbarSurfLock() . ' - EXIT!');
1263 return ($count == 1);
1266 // Determine which user hash no more points left
1267 function determineSurfbarDepletedUserids ($limit=0) {
1270 'url_userid' => array(),
1271 'points' => array(),
1272 'notified' => array(),
1275 // Is there a current user id?
1276 if ((isMember()) && ($limit == '0')) {
1277 // Then add this as well
1278 $userids['url_userid'][getMemberId()] = getMemberId();
1279 $userids['points'][getMemberId()] = getTotalPoints(getMemberId());
1280 $userids['notified'][getMemberId()] = '0';
1282 // Get all userid except logged in one
1283 $result = SQL_QUERY_ESC("SELECT
1284 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1286 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1288 `{?_MYSQL_PREFIX?}_user_data` AS d
1290 u.`url_userid`=d.`userid`
1292 u.`url_userid` NOT IN (%s) AND
1293 u.`url_userid` IS NOT NULL AND
1294 u.`url_status`='ACTIVE'
1298 u.`url_userid` ASC",
1299 array(getMemberId()), __FUNCTION__, __LINE__);
1302 $result = SQL_QUERY("SELECT
1303 u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1305 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1307 `{?_MYSQL_PREFIX?}_user_data` AS d
1309 u.`url_userid`=d.`userid`
1311 u.`url_userid` > 0 AND
1312 u.`url_status`='ACTIVE'
1316 u.`url_userid` ASC", __FUNCTION__, __LINE__);
1320 while ($content = SQL_FETCHARRAY($result)) {
1322 $points = getTotalPoints($content['url_userid']);
1323 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ',points=' . $points);
1325 // Shall we add this to ignore?
1326 if ($points <= $limit) {
1328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ' has depleted points amount!');
1329 $userids['url_userid'][$content['url_userid']] = $content['url_userid'];
1330 $userids['points'][$content['url_userid']] = $points;
1331 $userids['notified'][$content['url_userid']] = $content['notified'];
1336 SQL_FREERESULT($result);
1339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UIDs::count=' . count($userids) . ' (with own userid=' . getMemberId() . ')');
1345 // Determine how many users are Online in surfbar
1346 function determineSurfbarTotalOnline () {
1347 // Count all users in surfbar modue and return the value
1348 $result = SQL_QUERY('SELECT
1351 `{?_MYSQL_PREFIX?}_surfbar_stats`
1353 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1355 `stats_userid` ASC', __FUNCTION__, __LINE__);
1358 $count = SQL_NUMROWS($result);
1361 SQL_FREERESULT($result);
1367 // Determine waiting time for one URL
1368 function determineSurfbarWaitingTime () {
1369 // Get fixed reload lock
1370 $fixed = getSurfbarFixedReload();
1372 // Is the fixed reload time set?
1378 // Static time is default
1379 $time = getConfig('surfbar_static_time');
1381 // Which payment model do we have?
1382 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1383 // "Calculate" dynamic time
1384 $time += calculateSurfbarDynamicAddValue();
1391 // Changes the status of an URL from given to other
1392 function changeSurfbarUrlStatus ($urlId, $prevStatus, $newStatus, $data = array()) {
1393 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',data[]=' . gettype($data) . ',newStatus=' . $newStatus . ' - ENTERED!');
1394 // Make new status always lower-case
1395 $newStatus = strtolower($newStatus);
1397 // Get URL data for status comparison if missing
1398 if ((!is_array($data)) || (count($data) == 0)) {
1399 // Fetch missing URL data
1400 $data = getSurfbarUrlData($urlId);
1404 $filterData = array(
1406 'prev_status' => $prevStatus,
1407 'new_status' => $newStatus,
1412 // Run pre filter chain
1413 $filterData = runFilterChain('pre_change_surfbar_url_status', $filterData);
1416 if (!is_null($filterData['abort'])) {
1418 return $filterData['abort'];
1421 // Update the status now
1422 // ---------- Comment out for debugging/developing member actions! ---------
1423 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_status`='%s' WHERE `url_id`=%s LIMIT 1",
1427 ), __FUNCTION__, __LINE__);
1428 // ---------- Comment out for debugging/developing member actions! ---------
1431 // ---------- Comment out for debugging/developing member actions! ---------
1432 if (SQL_AFFECTEDROWS() != 1) {
1433 // No, something went wrong
1436 // ---------- Comment out for debugging/developing member actions! ---------
1438 // Run post filter chain
1439 $filterData = runFilterChain('post_change_surfbar_url_status', $filterData);
1441 // Check if generic 'data' is there
1442 assert(isset($filterData['data']));
1445 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - EXIT!');
1449 // Calculate minimum value for dynamic payment model
1450 function calculateSurfbarDynamicMininumValue () {
1451 // Addon is zero by default
1455 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1458 $totalUsers = getTotalConfirmedUser();
1461 $onlineUsers = determineSurfbarTotalOnline();
1464 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1467 $totalUrls = getSurfbarTotalUrls('ACTIVE', 0);
1469 // Get user's total URLs
1470 $userUrls = getSurfbarTotalUserUrls(0, 'ACTIVE');
1473 if ($totalUrls > 0) {
1474 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1476 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1483 // Calculate maximum value for dynamic payment model
1484 function calculateSurfbarDynamicMaximumValue () {
1485 // Addon is zero by default
1492 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1495 $totalUsers = getTotalConfirmedUser();
1498 $addon += abs($max * $percent * $totalUsers);
1501 $totalUrls = getSurfbarTotalUrls('ACTIVE', 0);
1504 $addon += abs($max * $percent * $totalUrls);
1510 // Calculate dynamic lock
1511 function calculateSurfbarDynamicLock () {
1512 // Default lock is 30 seconds
1516 $onlineUsers = determineSurfbarTotalOnline();
1519 $addon = abs(log($onlineUsers / $addon + 1));
1525 // "Getter" for lock ids array
1526 function getSurfbarLockIdsArray () {
1527 // Prepare some arrays
1532 // Get all id from locks within the timestamp
1533 $result = SQL_QUERY_ESC("SELECT
1536 UNIX_TIMESTAMP(`locks_last_surfed`) AS `last_surfed`
1538 `{?_MYSQL_PREFIX?}_surfbar_locks`
1542 `locks_id` ASC", array(getMemberId()),
1543 __FUNCTION__, __LINE__);
1546 while ($content = SQL_FETCHARRAY($result)) {
1548 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',rest='.(time() - $content['last_surfed']).'/'.gerSurfbarSurfLock());
1550 // Skip entries that are too old
1551 if (($content['last_surfed'] > (time() - gerSurfbarSurfLock())) && (!in_array($content['locks_url_id'], $ignored))) {
1553 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1555 // Add only if missing or bigger
1556 if ((!isset($IDs[$content['locks_url_id']])) || ($IDs[$content['locks_url_id']] > $content['last_surfed'])) {
1558 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1561 $IDs[$content['locks_url_id']] = $content['last_surfed'];
1562 $USE[$content['locks_url_id']] = $content['locks_id'];
1566 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1568 // Ignore these old entries!
1569 array_push($ignored, $content['locks_url_id']);
1570 unset($IDs[$content['locks_url_id']]);
1571 unset($USE[$content['locks_url_id']]);
1576 SQL_FREERESULT($result);
1582 // "Getter" for maximum random number
1583 function getSurfbarMaximumRandom ($userids, $add) {
1584 // Count max availabe entries
1585 $result = SQL_QUERY("SELECT
1588 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1590 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1592 sbu.url_id=sbs.salts_url_id
1594 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1596 sbu.url_id=l.locks_url_id
1598 sbu.url_userid NOT IN (" . implode(',', $userids) . ") AND
1599 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1600 sbu.url_status='ACTIVE'
1603 sbu.url_id ASC", __FUNCTION__, __LINE__);
1606 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1609 $maxRand = SQL_NUMROWS($result);
1612 SQL_FREERESULT($result);
1618 // Load all URLs of the current user and return it as an array
1619 function getSurfbarUserUrls () {
1621 $urlArray = array();
1624 $result = SQL_QUERY_ESC("SELECT
1629 u.`url_views_total`,
1631 u.`url_views_allowed`,
1632 UNIX_TIMESTAMP(u.`url_registered`) AS `url_registered`,
1633 UNIX_TIMESTAMP(u.`url_last_locked`) AS `url_last_locked`,
1636 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1638 u.`url_userid`=%s AND
1639 u.`url_status` != 'DELETED'
1642 array(getMemberId()), __FUNCTION__, __LINE__);
1644 // Are there entries?
1645 if (!SQL_HASZERONUMS($result)) {
1647 while ($row = SQL_FETCHARRAY($result)) {
1649 $urlArray[$row['url_id']] = $row;
1654 SQL_FREERESULT($result);
1660 // "Getter" for member action array for given status
1661 function getSurfbarArrayFromStatus ($status) {
1663 $returnArray = array();
1665 // Get all assigned actions
1666 $result = SQL_QUERY_ESC("SELECT `actions_action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1667 array($status), __FUNCTION__, __LINE__);
1669 // Some entries there?
1670 if (!SQL_HASZERONUMS($result)) {
1672 // @TODO This can be somehow rewritten
1673 while ($content = SQL_FETCHARRAY($result)) {
1674 array_push($returnArray, $content['actions_action']);
1679 SQL_FREERESULT($result);
1682 return $returnArray;
1685 // Reload to configured stop page
1686 function redirectToSurfbarStopPage ($page = 'stop') {
1687 // Internal or external?
1688 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'page=' . $page . ' - ENTERED!');
1689 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1690 // Reload to internal page
1691 redirectToUrl('surfbar.php?frame=' . $page);
1693 // Reload to external page
1694 redirectToConfiguredUrl('surfbar_pause_url');
1699 * Determine next id for surfbar or get data for given id, always call this
1700 * before you call other getters below this function!
1702 function determineSurfbarNextId ($urlId = NULL) {
1703 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ' - ENTERED!');
1704 // Default is no id and no random number
1709 if (is_null($urlId)) {
1710 // Get array with lock ids
1711 $USE = getSurfbarLockIdsArray();
1713 // Shall we add some URL ids to ignore?
1715 if (count($USE) > 0) {
1717 $add = " AND sbu.`url_id` NOT IN (";
1718 foreach ($USE as $url_id => $lid) {
1720 $add .= $url_id.',';
1723 // Add closing bracket
1724 $add = substr($add, 0, -1) . ')';
1727 // Determine depleted user account
1728 $userids = determineSurfbarDepletedUserids();
1730 // Get maximum randomness factor
1731 $maxRand = getSurfbarMaximumRandom($userids['url_userid'], $add);
1733 // If more than one URL can be called generate the random number!
1735 // Generate random number
1736 $randNum = mt_rand(0, ($maxRand - 1));
1739 // And query the database
1740 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.gerSurfbarSurfLock());
1741 $result = SQL_QUERY_ESC("SELECT
1745 sbs.salts_last_salt,
1746 sbu.url_views_total,
1748 sbu.url_views_allowed,
1749 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1750 sbu.url_fixed_reload
1752 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1754 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1756 sbu.url_id=sbs.salts_url_id
1758 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1760 sbu.url_id=l.locks_url_id
1762 (sbu.`url_userid` NOT IN (".implode(',', $userids['url_userid']).") OR sbu.`url_userid` IS NULL) AND
1763 sbu.url_status='ACTIVE' AND
1764 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1769 l.locks_last_surfed ASC,
1772 array($randNum), __FUNCTION__, __LINE__
1775 // Get data from specified id number
1776 $result = SQL_QUERY_ESC("SELECT
1780 sbs.salts_last_salt,
1781 sbu.url_views_total,
1783 sbu.url_views_allowed,
1784 UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1785 sbu.url_fixed_reload
1787 `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1789 `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1791 sbu.url_id=sbs.salts_url_id
1793 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1795 sbu.url_id=l.locks_url_id
1797 (sbu.url_userid != %s OR sbu.url_userid IS NULL) AND
1798 sbu.url_status='ACTIVE' AND
1800 (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1802 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1806 // Is there an id number?
1807 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1808 if (SQL_NUMROWS($result) == 1) {
1810 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1811 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1812 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1814 // Determine waiting time
1815 $GLOBALS['surfbar_cache']['time'] = determineSurfbarWaitingTime();
1817 // Is the last salt there?
1818 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1819 // Then repair it wit the static!
1820 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1821 $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1824 // Fix missing last_surfed
1825 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1827 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1828 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1831 // Get base/fixed reward and costs
1832 $GLOBALS['surfbar_cache']['reward'] = determineSurfbarReward();
1833 $GLOBALS['surfbar_cache']['costs'] = determineSurfbarCosts();
1834 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.gerSurfbarReward().'|costs='.gerSurfbarCosts());
1836 // Only in dynamic model add the dynamic bonus!
1837 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1838 // Calculate dynamic reward/costs and add it
1839 $GLOBALS['surfbar_cache']['reward'] += calculateSurfbarDynamicAddValue();
1840 $GLOBALS['surfbar_cache']['costs'] += calculateSurfbarDynamicAddValue();
1841 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.gerSurfbarReward().'|costs='.gerSurfbarCosts());
1845 $nextId = gerSurfbarId();
1849 SQL_FREERESULT($result);
1852 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',nextId=' . $nextId . ' - EXIT!');
1856 //-----------------------------------------------------------------------------
1858 //-----------------------------------------------------------------------------
1860 // "Getter" for surfbar_dynamic_percent
1861 function getSurfbarDynamicPercent () {
1863 if (!isset($GLOBALS[__FUNCTION__])) {
1865 $GLOBALS[__FUNCTION__] = getConfig('surfbar_dynamic_percent');
1869 return $GLOBALS[__FUNCTION__];
1872 // "Getter" for surfbar_static_reward
1873 function getSurfbarStaticReward () {
1875 if (!isset($GLOBALS[__FUNCTION__])) {
1877 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_reward');
1881 return $GLOBALS[__FUNCTION__];
1884 // "Getter" for surfbar_static_time
1885 function getSurfbarStaticTime () {
1887 if (!isset($GLOBALS[__FUNCTION__])) {
1889 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_time');
1893 return $GLOBALS[__FUNCTION__];
1896 // "Getter" for surfbar_max_order
1897 function getSurfbarMaxOrder () {
1899 if (!isset($GLOBALS[__FUNCTION__])) {
1901 $GLOBALS[__FUNCTION__] = getConfig('surfbar_max_order');
1905 return $GLOBALS[__FUNCTION__];
1908 // "Getter" for surfbar_payment_model
1909 function getSurfbarPaymentModel () {
1911 if (!isset($GLOBALS[__FUNCTION__])) {
1913 $GLOBALS[__FUNCTION__] = getConfig('surfbar_payment_model');
1917 return $GLOBALS[__FUNCTION__];
1920 //------------------------------------------------------------------------------
1921 // Template helper functions
1922 //------------------------------------------------------------------------------
1924 // Template helper to generate a selection box for surfbar actions
1925 function doTemplateSurfbarActionsActionSelectionBox ($templateName, $clear = false, $default = NULL) {
1927 $actionsAction = array(
1928 0 => array('actions_action' => 'EDIT'),
1929 1 => array('actions_action' => 'DELETE'),
1930 2 => array('actions_action' => 'PAUSE'),
1931 3 => array('actions_action' => 'UNPAUSE'),
1932 4 => array('actions_action' => 'FRAMETEST'),
1933 5 => array('actions_action' => 'RETREAT'),
1934 6 => array('actions_action' => 'RESUBMIT'),
1935 7 => array('actions_action' => 'BOOKNOW')
1938 // Handle it over to generateSelectionBoxFromArray()
1939 $content = generateSelectionBoxFromArray($actionsAction, 'surfbar_actions_action', 'actions_action', '', '', '', $default, '', false, true);
1941 // Return prepared content
1945 // Template helper to generate a selection box for surfbar status
1946 function doTemplateSurfbarActionsStatusSelectionBox ($templateName, $clear = false, $default = NULL) {
1949 0 => array('actions_status' => 'PENDING'),
1950 1 => array('actions_status' => 'ACTIVE'),
1951 2 => array('actions_status' => 'LOCKED'),
1952 3 => array('actions_status' => 'STOPPED'),
1953 4 => array('actions_status' => 'REJECTED'),
1954 5 => array('actions_status' => 'DELETED'),
1955 6 => array('actions_status' => 'MIGRATED'),
1956 7 => array('actions_status' => 'DEPLETED')
1959 // Handle it over to generateSelectionBoxFromArray()
1960 $content = generateSelectionBoxFromArray($status, 'surfbar_actions_status', 'actions_status', '', '', '', $default, '', false, true);
1962 // Return prepared content
1966 // Template helper to generate a selection box for surfbar status
1967 function doTemplateSurfbarActionsNewStatusSelectionBox ($templateName, $clear = false, $default = NULL) {
1970 0 => array('actions_new_status' => 'PENDING'),
1971 1 => array('actions_new_status' => 'ACTIVE'),
1972 2 => array('actions_new_status' => 'LOCKED'),
1973 3 => array('actions_new_status' => 'STOPPED'),
1974 4 => array('actions_new_status' => 'REJECTED'),
1975 5 => array('actions_new_status' => 'DELETED'),
1976 6 => array('actions_new_status' => 'MIGRATED'),
1977 7 => array('actions_new_status' => 'DEPLETED')
1980 // Handle it over to generateSelectionBoxFromArray()
1981 $content = generateSelectionBoxFromArray($status, 'surfbar_actions_new_status', 'actions_new_status', '', '', '', $default, '', true, true);
1983 // Return prepared content
1987 //------------------------------------------------------------------------------
1988 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1989 // THE $GLOBALS['surfbar_cache'] ARRAY!
1990 //------------------------------------------------------------------------------
1992 // Initializes the surfbar
1993 function initSurfbar () {
1995 $GLOBALS['surfbar_cache'] = array();
1998 // Private getter for data elements
1999 function getSurfbarData ($element) {
2000 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element=' . $element . ' - ENTERED!');
2005 // Is the entry there?
2006 if ((isset($GLOBALS['surfbar_cache'][$element])) || (is_null($GLOBALS['surfbar_cache'][$element]))) {
2008 $data = $GLOBALS['surfbar_cache'][$element];
2009 } else { // END - if
2010 print('surfbar_cache=<pre>');
2011 print_r($GLOBALS['surfbar_cache']);
2013 reportBug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
2017 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data . ' - EXIT!');
2021 // Getter for reward from cache
2022 function gerSurfbarReward () {
2023 // Get data element and return its contents
2024 return getSurfbarData('reward');
2027 // Getter for costs from cache
2028 function gerSurfbarCosts () {
2029 // Get data element and return its contents
2030 return getSurfbarData('costs');
2033 // Getter for URL from cache
2034 function gerSurfbarUrl () {
2035 // Get data element and return its contents
2036 return getSurfbarData('url');
2039 // Getter for salt from cache
2040 function gerSurfbarSalt () {
2041 // Get data element and return its contents
2042 return getSurfbarData('salt');
2045 // Getter for id from cache
2046 function gerSurfbarId () {
2047 // Get data element and return its contents
2048 return getSurfbarData('url_id');
2051 // Getter for userid from cache
2052 function gerSurfbarUserid () {
2053 // Get data element and return its contents
2054 return getSurfbarData('url_userid');
2057 // Getter for user reload locks
2058 function getSurfbarUserLocks () {
2059 // Get data element and return its contents
2060 return getSurfbarData('user_locks');
2063 // Getter for reload time
2064 function gerSurfbarReloadTime () {
2065 // Get data element and return its contents
2066 return getSurfbarData('time');
2069 // Getter for allowed views
2070 function gerSurfbarViewsAllowed () {
2071 // Get data element and return its contents
2072 return getSurfbarData('url_views_allowed');
2075 // Getter for maximum views
2076 function gerSurfbarViewsMax () {
2077 // Get data element and return its contents
2078 return getSurfbarData('url_views_max');
2081 // Getter for fixed reload
2082 function getSurfbarFixedReload () {
2083 // Get data element and return its contents
2084 return getSurfbarData('url_fixed_reload');
2087 // Getter for surf lock
2088 function gerSurfbarSurfLock () {
2089 // Get data element and return its contents
2090 return getSurfbarData('surf_lock');
2093 // Getter for new status
2094 function gerSurfbarNewStatus () {
2095 // Get data element and return its contents
2096 return getSurfbarData('new_status');
2099 // Getter for last salt
2100 function gerSurfbarLastSalt () {
2101 // Get data element and return its contents
2102 return getSurfbarData('salts_last_salt');