New debugging function debugOutput() introduced, some rewrites to EL:
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/31/2008 *
4  * ===================                          Last change: 08/31/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : surfbar_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for surfbar                            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Surfbar                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 }
44
45 // -----------------------------------------------------------------------------
46 //                               Admin functions
47 // -----------------------------------------------------------------------------
48 //
49 // Admin has added an URL with given user id and so on
50 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
51         // Do some pre-checks
52         if (!isAdmin()) {
53                 // Not an admin
54                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
55                 return false;
56         } elseif (!isUrlValid($url)) {
57                 // URL invalid
58                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
59                 return false;
60         } elseif (SURFBAR_LOOKUP_BY_URL($url, 0)) {
61                 // URL already found in surfbar!
62                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Already added.", $url, $limit, $reload));
63                 return false;
64         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
65                 // No more allowed!
66                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
67                 return false;
68         } elseif ('' . ($limit + 0) . '' != '' . $limit . '') {
69                 // Invalid limit entered
70                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid limit entered.", $url, $limit, $reload));
71                 return false;
72         } elseif ('' . ($reload + 0) . '' != '' . $reload . '') {
73                 // Invalid amount entered
74                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid reload entered.", $url, $limit, $reload));
75                 return false;
76         }
77
78         // Register the new URL
79         return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
80 }
81
82 // Admin unlocked an email so we can migrate the URL
83 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
84         // Do some pre-checks
85         if (!isAdmin()) {
86                 // Not an admin
87                 return false;
88         } elseif (!isUrlValid($url)) {
89                 // URL invalid
90                 return false;
91         } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
92                 // URL already found in surfbar!
93                 return false;
94         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
95                 // No more allowed!
96                 return false;
97         }
98
99         // Register the new URL
100         return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
101 }
102
103 // Admin function for unlocking URLs
104 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
105         // Is this an admin or invalid array?
106         if (!isAdmin()) {
107                 // Not admin or invalid ids array
108                 return false;
109         } elseif (!is_array($IDs)) {
110                 // No array
111                 return false;
112         } elseif (count($IDs) == 0) {
113                 // Empty array
114                 return false;
115         }
116
117         // Set to true to make AND expression valid if first URL got unlocked
118         $done = true;
119
120         // Update the status for all ids
121         foreach ($IDs as $id => $dummy) {
122                 // Test all ids through (ignores failed)
123                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
124         } // END - if
125
126         // Return total status
127         return $done;
128 }
129
130 // Admin function for rejecting URLs
131 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
132         // Is this an admin or invalid array?
133         if (!isAdmin()) {
134                 // Not admin or invalid ids array
135                 return false;
136         } elseif (!is_array($IDs)) {
137                 // No array
138                 return false;
139         } elseif (count($IDs) == 0) {
140                 // Empty array
141                 return false;
142         }
143
144         // Set to true to make AND expression valid if first URL got unlocked
145         $done = true;
146
147         // Update the status for all ids
148         foreach ($IDs as $id => $dummy) {
149                 // Test all ids through (ignores failed)
150                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
151         } // END - if
152
153         // Return total status
154         return $done;
155 }
156
157 //
158 // -----------------------------------------------------------------------------
159 //                               Member functions
160 // -----------------------------------------------------------------------------
161 //
162 // Member has added an URL
163 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
164         // Do some pre-checks
165         if (!isMember()) {
166                 // Not a member
167                 return false;
168         } elseif ((!isUrlValid($url)) && (!isAdmin())) {
169                 // URL invalid
170                 return false;
171         } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
172                 // URL already found in surfbar!
173                 return false;
174         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
175                 // No more allowed!
176                 return false;
177         } elseif (''.($limit + 0).'' != ''.$limit.'') {
178                 // Invalid amount entered
179                 return false;
180         }
181
182         // Register the new URL
183         return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
184 }
185
186 // Create list of actions depending on status for the user
187 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
188         // Load all actions in an array for given status
189         $actionArray = SURFBAR_GET_ARRAY_FROM_STATUS($status);
190
191         // Init HTML code
192         $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
193 <tr>\n";
194
195         // Calculate width
196         $width = round(100 / count($actionArray));
197
198         // "Walk" through all actions and create forms
199         foreach ($actionArray as $actionId => $action) {
200                 // Add form for this action
201                 $OUT .= loadTemplate('member_surfbar_list_form', true, array(
202                         'width'    => $width,
203                         'id'       => bigintval($urlId),
204                         'action'   => strtolower($action),
205                         'title'    => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE--}',
206                         'submit'   => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT--}',
207                 ));
208         } // END - foreach
209
210         // Close table
211         $OUT .= "</tr>
212 </table>\n";
213
214         // Return code
215         return $OUT;
216 }
217
218 // Do the member form request
219 function SURFBAR_MEMBER_DO_FORM ($formData, $urlArray) {
220         // By default no action is performed
221         $performed = false;
222
223         // Is this a member?
224         if (!isMember()) {
225                 // No member!
226                 return false;
227         } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
228                 // Important form elements are missing!
229                 return false;
230         } elseif (!isset($urlArray[$formData['id']])) {
231                 // id not found in cache
232                 return false;
233         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $urlArray[$formData['id']]['url_status'])) {
234                 // Action not allowed for current URL status
235                 return false;
236         }
237
238         // Secure action
239         $action = secureString($formData['action']);
240
241         // Has it changed?
242         if ($action != $formData['action']) {
243                 // Invalid data in action found
244                 return false;
245         } // END - if
246
247         // Create the function name for selected action
248         $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
249
250         // Is the function there?
251         if (function_exists($functionName)) {
252                 // Add new status
253                 $urlArray[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
254
255                 // Extract URL data for call-back
256                 $urlData = array(merge_array($urlArray[$formData['id']], array($action => $formData)));
257
258                 // Action found so execute it
259                 $performed = call_user_func_array($functionName, $urlData);
260         } else {
261                 // Log invalid request
262                 logDebugMessage(__FUNCTION__, __LINE__, "action={$formData['action']},id={$formData['id']},function={$functionName}");
263                 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
264         }
265
266         // Return status
267         return $performed;
268 }
269
270 // Validate if the requested action can be performed on current URL status
271 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
272         // Search for the requested action/status combination in database
273         $result = SQL_QUERY_ESC("SELECT new_status FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
274         array($action, $status), __FUNCTION__, __LINE__);
275
276         // Is the entry there?
277         $isValid = (SQL_NUMROWS($result) == 1);
278
279         // Fetch the new status if found
280         if ($isValid) {
281                 // Load new status
282                 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
283         } // END - if
284
285         // Free result
286         SQL_FREERESULT($result);
287
288         // Return status
289         return $isValid;
290 }
291
292 //
293 // -----------------------------------------------------------------------------
294 //                               Member actions
295 // -----------------------------------------------------------------------------
296 //
297 // Retreat a booked URL
298 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
299         // Create the data array for next function call
300         $data = array(
301                 $urlData['id'] => $urlData
302         );
303
304         // Simply change the status here
305         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
306 }
307
308 // Book an URL now (from migration)
309 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
310         // Create the data array for next function call
311         $data = array(
312                 $urlData['id'] => $urlData
313         );
314
315         // Simply change the status here
316         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
317 }
318
319 // Show edit form or do the changes
320 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
321         // Is the "execute" flag there?
322         if (isset($urlData['edit']['execute'])) {
323                 // Execute the changes
324                 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
325         } // END - if
326
327         // Display form
328         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
329 }
330
331 // Show delete form or do the changes
332 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
333         // Is the "execute" flag there?
334         if (isset($urlData['delete']['execute'])) {
335                 // Execute the changes
336                 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
337         } // END - if
338
339         // Display form
340         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
341 }
342
343 // Pause active banner
344 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
345         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
346 }
347
348 // Unpause stopped banner
349 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
350         // Fix missing entry for template
351         $urlData['edit'] = $urlData['unpause'];
352         $urlData['edit']['url'] = $urlData['url'];
353         $urlData['edit']['limit'] = SURFBAR_GET_VIEWS_MAX();
354
355         // Return status change
356         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
357 }
358
359 // Resubmit locked URL
360 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
361         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
362 }
363
364 // Display selected "action form"
365 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
366         // Translate some data if present
367         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
368
369         // Is the lock reason empty?
370         if (empty($urlData['url_lock_reason'])) {
371                 // Fix it to three dashes
372                 $urlData['url_lock_reason'] = '---';
373         } // END - if
374
375         // Include fields only for action 'edit'
376         if ($action == 'edit') {
377                 // Default is not limited
378                 $urlData['limited_y'] = '';
379                 $urlData['limited_n'] = ' checked="checked"';
380                 $urlData['limited']   = 'false';
381
382                 // Is this URL limited?
383                 if (SURFBAR_GET_VIEWS_MAX() > 0) {
384                         // Then rewrite form data
385                         $urlData['limited_y'] = ' checked="checked"';
386                         $urlData['limited_n'] = '';
387                         $urlData['limited']   = 'true';
388                 } // END - if
389         } // END - if
390
391         // Load the form and display it
392         loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
393
394         // All fine by default ... ;-)
395         return true;
396 }
397
398 // Execute choosen action
399 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
400         // By default nothing is executed
401         $executed = false;
402
403         // Is limitation "no" and "limit" is > 0?
404         if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
405                 // Set it to unlimited
406                 $urlData[$action]['limit'] = '0';
407         } // END - if
408
409         // Construct function name
410         $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
411
412         // Is that function there?
413         if (function_exists($functionName)) {
414                 // Execute the function
415                 if (call_user_func_array($functionName, array($urlData)) == true) {
416                         // Update status as well
417                         $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
418                 } // END - if
419         } else {
420                 // Not found!
421                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
422         }
423
424         // Return status
425         return $executed;
426 }
427 // "Execute edit" function: Update changed data
428 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
429         // Default is nothing done
430         $status = false;
431
432         // Has the URL or limit changed?
433         if (true) {
434                 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
435                 // Run the query
436                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url`='%s', `url_views_allowed`=%s, `url_views_max`=%s WHERE `url_id`=%s AND `status`='%s' LIMIT 1",
437                         array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['url_status']), __FUNCTION__, __LINE__);
438
439                 // All fine
440                 $status = true;
441         } // END - if
442
443         // Return status
444         return $status;
445 }
446 // "Execute delete" function: Does nothing...
447 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
448         // Nothing special to do (see above function for such "special actions" to perform)
449         return true;
450 }
451 //
452 // -----------------------------------------------------------------------------
453 //                           Self-maintenance functions
454 // -----------------------------------------------------------------------------
455 //
456 // Main function
457 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
458         // Handle URLs which limit has depleted so we can stop them
459         SURFBAR_HANDLE_DEPLETED_VIEWS();
460
461         // Handle low-points amounts
462         SURFBAR_HANDLE_LOW_POINTS();
463 }
464 // Handle URLs which limit has depleted
465 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
466         // Get all URLs
467         $urlArray = SURFBAR_GET_URL_DATA(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
468
469         // Do we have some entries?
470         if (count($urlArray) > 0) {
471                 // Then handle all!
472                 foreach ($urlArray as $id => $urlData) {
473                         // Backup data
474                         $data = $urlData;
475
476                         // Rewrite array for next call
477                         $urlData[$id] = $data;
478
479                         // Handle the status
480                         SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
481                 } // END - foreach
482         } // END - if
483 }
484
485 // Alert users which have URLs booked and are low on points amount
486 function SURFBAR_HANDLE_LOW_POINTS () {
487         // Get all userids
488         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
489
490         // "Walk" through all URLs
491         foreach ($userids['url_userid'] as $userid => $dummy) {
492                 // Is the last notification far enougth away to notify again?
493                 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
494                         // Prepare content
495                         $content = array(
496                                 'url_userid' => $userid,
497                                 'points'     => $userids['points'][$userid],
498                                 'notified'   => $userids['notified'][$userid]
499                         );
500
501                         // Notify this user
502                         SURFBAR_NOTIFY_USER('low_points', $content);
503
504                         // Update last notified
505                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
506                                 array($userid), __FUNCTION__, __LINE__);
507                 } // END - if
508         } // END - foreach
509 }
510
511 //
512 // -----------------------------------------------------------------------------
513 //                               Generic functions
514 // -----------------------------------------------------------------------------
515 //
516
517 // Looks up by an URL
518 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
519         // Now lookup that given URL by itself
520         $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
521
522         // Was it found?
523         return (count($urlArray) > 0);
524 }
525
526 // Load URL data by given search term and column
527 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
528         // By default nothing is found
529         $GLOBALS['last_url_data'] = array();
530
531         // Is the column an id number?
532         if (($column == 'url_id') || ($column == 'url_userid')) {
533                 // Extra secure input
534                 $searchTerm = bigintval($searchTerm);
535         } // END - if
536
537         // If the column is 'id' there can be only one entry
538         $limit = '';
539         if ($column == 'id') {
540                 $limit = "LIMIT 1";
541         } // END - if
542
543         // Look up the record
544         $result = SQL_QUERY_ESC("SELECT
545         `url_id`,
546         `url_userid`,
547         `url`,
548         `url_views_total`,
549         `url_views_max`,
550         `url_views_allowed`,
551         `url_status`,
552         UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
553         UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
554         `url_lock_reason`,
555         `url_views_max`,
556         `url_views_allowed`,
557         `url_fixed_reload`
558 FROM
559         `{?_MYSQL_PREFIX?}_surfbar_urls`
560 WHERE
561         `%s`='%s'" . $add . "
562 ORDER BY
563         `%s` %s
564 %s",
565                 array(
566                         $column,
567                         $searchTerm,
568                         $order,
569                         $sort,
570                         $limit
571                 ), __FUNCTION__, __LINE__);
572
573         // Is there at least one record?
574         if (SQL_NUMROWS($result) > 0) {
575                 // Then load all!
576                 while ($dataRow = SQL_FETCHARRAY($result)) {
577                         // Shall we group these results?
578                         if ($group == 'url_id') {
579                                 // Add the row by id as index
580                                 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
581                         } else {
582                                 // Group entries
583                                 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
584                         }
585                 } // END - while
586         } // END - if
587
588         // Free the result
589         SQL_FREERESULT($result);
590
591         // Return the result
592         return $GLOBALS['last_url_data'];
593 }
594
595 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
596 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
597         // Make sure by the user registered URLs are always pending
598         if ($addMode == 'reg') {
599                 $status = 'PENDING';
600         } // END - if
601
602         // Prepare content
603         $content = merge_array($extraFields, array(
604                 'url'         => $url,
605                 'frametester' => generateFrametesterUrl($url),
606                 'url_userid'  => $userid,
607                 'url_status'  => $status,
608         ));
609
610         // Is limit/reload set?
611         if (!isset($config['limit'])) {
612                 $content['limit']  = '0';
613         } // END - if
614         if (!isset($config['reload'])) {
615                 $content['reload'] = '0';
616         } // END - if
617
618         // Insert the URL into database
619         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
620
621         // Is this id valid?
622         if ($content['insert_id'] == '0') {
623                 // INSERT did not insert any data!
624                 return false;
625         } // END - if
626
627         // If in reg-mode we notify admin
628         if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
629                 // Notify admin even when he as unlocked an email
630                 SURFBAR_NOTIFY_ADMIN('url_' . $addMode, $content);
631         } // END - if
632
633         // Send mail to user
634         SURFBAR_NOTIFY_USER('url_' . $addMode, $content);
635
636         // Return the insert id
637         return $content['insert_id'];
638 }
639
640 // Inserts an url by given data array and return the insert id
641 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
642         // Get userid
643         $userid = bigintval($urlData['url_userid']);
644
645         // Is the id set?
646         if (empty($userid)) $userid = '0';
647
648         // Just run the insert query for now
649         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)",
650                 array(
651                         $userid,
652                         $urlData['url'],
653                         $urlData['url_status'],
654                         $urlData['limit'],
655                         $urlData['limit'],
656                         $urlData['reload']
657                 ), __FUNCTION__, __LINE__
658         );
659
660         // Return insert id
661         return SQL_INSERTID();
662 }
663
664 // Notify admin(s) with a selected message and content
665 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
666         // Prepare template name
667         $templateName = sprintf("admin_surfbar_%s", $messageType);
668
669         // Prepare subject
670         $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
671                 strtoupper($messageType)
672         ));
673
674         // Is the subject line there?
675         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
676                 // Set default subject if following eval() wents wrong
677                 $subject = getMaskedMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT', strtoupper($messageType));
678         } // END - if
679
680         // Translate some data if present
681         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
682
683         // Send the notification out
684         return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
685 }
686
687 // Notify the user about the performed action
688 function SURFBAR_NOTIFY_USER ($messageType, $content) {
689         // Skip notification if userid is zero
690         if ($content['url_userid'] == '0') {
691                 return false;
692         } // END - if
693
694         // Prepare template name
695         $templateName = sprintf("member_surfbar_%s", $messageType);
696
697         // Prepare subject
698         $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
699                 strtoupper($messageType)
700         ));
701
702         // Is the subject line there?
703         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
704                 // Set default subject if following eval() wents wrong
705                 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
706         } // END - if
707
708         // Translate some data if present
709         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
710
711         // Load template
712         $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
713
714         // Send the email
715         return sendEmail($content['url_userid'], $subject, $mailText);
716 }
717
718 // Translates some data for template usage
719 // @TODO Can't we use our new expression language instead of this ugly code?
720 function SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE ($content) {
721         // Prepare some code
722         if (isset($content['url_registered']))  $content['url_registered']  = generateDateTime($content['url_registered'], 2);
723         if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
724
725         // Return translated content
726         return $content;
727 }
728
729 // Translates the limit
730 function translateSurfbarLimit ($limit) {
731         // Is this zero?
732         if ($limit == '0') {
733                 // Unlimited!
734                 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
735         } else {
736                 // Translate comma
737                 $return = translateComma($limit);
738         }
739
740         // Return value
741         return $return;
742 }
743
744 // Translate the URL status
745 function translateSurfbarUrlStatus ($status) {
746         // Create constant name
747         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
748
749         // Get message
750         $statusTranslated = getMessage($constantName);
751
752         // Return result
753         return $statusTranslated;
754 }
755
756 // Determine reward
757 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
758         // Static values are default
759         $reward = getConfig('surfbar_static_reward');
760
761         // Do we have static or dynamic?
762         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
763                 // "Calculate" dynamic reward
764                 if ($onlyMin) {
765                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
766                 } else {
767                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
768                 }
769         } // END - if
770
771         // Return reward
772         return $reward;
773 }
774
775 // Determine costs
776 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
777         // Static costs is default
778         $costs  = getConfig('surfbar_static_costs');
779
780         // Do we have static or dynamic?
781         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
782                 // "Calculate" dynamic costs
783                 if ($onlyMin) {
784                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
785                 } else {
786                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
787                 }
788         } // END - if
789
790         // Return costs
791         return $costs;
792 }
793
794 // "Calculate" dynamic add
795 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
796         // Get min/max values
797         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
798         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
799
800         // "Calculate" dynamic part and return it
801         return mt_rand($min, $max);
802 }
803
804 // Determine right template name
805 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
806         // Default is the frameset
807         $templateName = "surfbar_frameset";
808
809         // Any frame set? ;-)
810         if (isGetRequestParameterSet('frame')) {
811                 // Use the frame as a template name part... ;-)
812                 $templateName = sprintf("surfbar_frame_%s",
813                         getRequestParameter('frame')
814                 );
815         } // END - if
816
817         // Return result
818         return $templateName;
819 }
820
821 // Check if the "reload lock" of the current user is full, call this function
822 // before you call SURFBAR_CHECK_RELOAD_LOCK().
823 function SURFBAR_CHECK_RELOAD_FULL() {
824         // Default is full!
825         $isFull = true;
826
827         // Cache static reload lock
828         $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
829         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
830
831         // Do we have dynamic model?
832         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
833                 // "Calculate" dynamic lock
834                 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
835         } // END - if
836
837         // Ask the database
838         $result = SQL_QUERY_ESC("SELECT
839         COUNT(l.locks_id) AS cnt
840 FROM
841         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
842 INNER JOIN
843         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
844 ON
845         u.url_id=l.locks_url_id
846 WHERE
847         l.locks_userid=%s AND
848         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.locks_last_surfed) AND
849         (
850                 ((UNIX_TIMESTAMP(l.locks_last_surfed) - u.url_fixed_reload) < 0 AND u.url_fixed_reload > 0) OR
851                 u.url_fixed_reload = '0'
852         )
853 LIMIT 1",
854                 array(getMemberId()), __FUNCTION__, __LINE__
855         );
856
857         // Fetch row
858         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
859
860         // Is it null?
861         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
862                 // Then fix it to zero!
863                 $GLOBALS['surfbar_cache']['user_locks'] = '0';
864         } // END - if
865
866         // Free result
867         SQL_FREERESULT($result);
868
869         // Get total URLs
870         $total = SURFBAR_GET_TOTAL_URLS();
871
872         // Do we have some URLs in lock? Admins can always surf on own URLs!
873         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
874         $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
875
876         // Return result
877         return $isFull;
878 }
879
880 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
881 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
882         // Determine depleted user account
883         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
884
885         // If we dont get any user ids back, there are no URLs
886         if (count($userids['url_userid']) == 0) {
887                 // No user ids found, no URLs!
888                 return 0;
889         } // END - if
890
891         // Is the exlude userid set?
892         if ($excludeUserId > 0) {
893                 // Then add it
894                 $userids['url_userid'][$excludeUserId] = $excludeUserId;
895         } // END - if
896
897         // Get amount from database
898         $result = SQL_QUERY_ESC("SELECT
899         COUNT(`url_id`) AS cnt
900 FROM
901         `{?_MYSQL_PREFIX?}_surfbar_urls`
902 WHERE
903         `url_userid` NOT IN (".implode(', ', $userids['url_userid']).") AND
904         `url_status`='%s'
905 LIMIT 1",
906                 array($status), __FUNCTION__, __LINE__
907         );
908
909         // Fetch row
910         list($cnt) = SQL_FETCHROW($result);
911
912         // Free result
913         SQL_FREERESULT($result);
914
915         // Return result
916         return $cnt;
917 }
918
919 // Check wether the user is allowed to book more URLs
920 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
921         // Is this admin and userid is zero or does the user has some URLs left to book?
922         return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
923 }
924
925 // Get total amount of URLs of given status for current user
926 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '', $exclude = '') {
927         // Is the user 0 and user is logged in?
928         if (($userid == '0') && (isMember())) {
929                 // Then use this userid
930                 $userid = getMemberId();
931         } elseif ($userid == '0') {
932                 // Error!
933                 return (getConfig('surfbar_max_order') + 1);
934         }
935
936         // Default is all URLs
937         $add = '';
938
939         // Is the status set?
940         if (is_array($status)) {
941                 // Only URLs with these status
942                 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
943         } elseif (!empty($status)) {
944                 // Only URLs with this status
945                 $add = sprintf(" AND `url_status`='%s'", $status);
946         } elseif (is_array($exclude)) {
947                 // Exclude URLs with these status
948                 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
949         } elseif (!empty($exclude)) {
950                 // Exclude URLs with this status
951                 $add = sprintf(" AND `url_status` != '%s'", $exclude);
952         }
953
954         // Get amount from database
955         $cnt = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
956
957         // Return result
958         return $cnt;
959 }
960
961 // Generate a validation code for the given id number
962 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
963         // @TODO Invalid salt should be refused
964         $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
965
966         // Get code length from config
967         $length = getConfig('code_length');
968
969         // Fix length to 10
970         if ($length == '0') $length = 10;
971
972         // Generate a code until the length matches
973         $valCode = '';
974         while (strlen($valCode) != $length) {
975                 // Is the salt set?
976                 if (empty($salt)) {
977                         // Generate random hashed string
978                         $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
979                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
980                 } else {
981                         // Use this as salt!
982                         $GLOBALS['surfbar_cache']['salt'] = $salt;
983                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
984                 }
985
986                 // ... and now the validation code
987                 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
988                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
989         } // END - while
990
991         // Hash it with md5() and salt it with the random string
992         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
993
994         // Finally encrypt it PGP-like and return it
995         $valHashedCode = encodeHashForCookie($hashedCode);
996
997         // Return hashed value
998         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
999         return $valHashedCode;
1000 }
1001
1002 // Check validation code
1003 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
1004         // Secure id number
1005         $urlId = bigintval($urlId);
1006
1007         // Now generate the code again
1008         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1009
1010         // Return result of checking hashes and salts
1011         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1012         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('salts_last_salt').'+++', false);
1013         return (($code == $check) && ($salt == SURFBAR_GET_DATA('salts_last_salt')));
1014 }
1015
1016 // Lockdown the userid/id combination (reload lock)
1017 function SURFBAR_LOCKDOWN_ID ($urlId) {
1018         //* DEBUG: */ debugOutput('LOCK!');
1019         ///* DEBUG: */ return;
1020         // Just add it to the database
1021         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)",
1022                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1023
1024         // Remove the salt from database
1025         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1026                 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1027 }
1028
1029 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1030 function SURFBAR_PAY_POINTS () {
1031         // Remove it from the URL owner
1032         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1033         if (SURFBAR_GET_USERID() > 0) {
1034                 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1035         } // END - if
1036
1037         // Book it to the user
1038         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1039         addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1040 }
1041
1042 // Updates the statistics of current URL/userid
1043 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1044         // Init add
1045         $add = '';
1046
1047         // Get allowed views
1048         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1049
1050         // Do we have a limit?
1051         if ($allowed > 0) {
1052                 // Then count views_max down!
1053                 $add .= ", `views_max`=`views_max`-1";
1054         } // END - if
1055
1056         // Update URL stats
1057         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1".$add." WHERE `url_id`=%s LIMIT 1",
1058                 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1059
1060         // Update the stats entry
1061         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",
1062                 array(
1063                         getMemberId(),
1064                         SURFBAR_GET_ID()
1065                 ), __FUNCTION__, __LINE__);
1066
1067         // Was that update okay?
1068         if (SQL_AFFECTEDROWS() < 1) {
1069                 // No, then insert entry
1070                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)",
1071                         array(
1072                                 getMemberId(),
1073                                 SURFBAR_GET_ID()
1074                         ), __FUNCTION__, __LINE__);
1075         } // END - if
1076
1077         // Update total/daily/weekly/monthly counter
1078         incrementConfigEntry('surfbar_total_counter');
1079         incrementConfigEntry('surfbar_daily_counter');
1080         incrementConfigEntry('surfbar_weekly_counter');
1081         incrementConfigEntry('surfbar_monthly_counter');
1082
1083         // Update config as well
1084         updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1085 }
1086
1087 // Update the salt for validation and statistics
1088 function SURFBAR_UPDATE_SALT_STATS () {
1089         // Update statistics record
1090         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1091
1092         // Simply store the salt from cache away in database...
1093         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1094                 array(
1095                         SURFBAR_GET_SALT(),
1096                         SURFBAR_GET_ID(),
1097                         getMemberId()
1098                 ), __FUNCTION__, __LINE__);
1099
1100         // Debug message
1101         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1102
1103         // Was that okay?
1104         if (SQL_AFFECTEDROWS() < 1) {
1105                 // Insert missing entry!
1106                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1107                         array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1108         } // END - if
1109
1110         // Debug message
1111         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1112
1113         // Return if the update was okay
1114         return (SQL_AFFECTEDROWS() == 1);
1115 }
1116
1117 // Check if the reload lock is active for given id
1118 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1119         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1120         // Ask the database
1121         $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1122 FROM
1123         `{?_MYSQL_PREFIX?}_surfbar_locks`
1124 WHERE
1125         `locks_userid`=%s AND
1126         `locks_url_id`=%s AND
1127         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1128 ORDER BY
1129         `locks_last_surfed` ASC
1130 LIMIT 1",
1131                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1132         );
1133
1134         // Fetch counter
1135         list($cnt) = SQL_FETCHROW($result);
1136
1137         // Free result
1138         SQL_FREERESULT($result);
1139
1140         // Return check
1141         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1142         return ($cnt == 1);
1143 }
1144
1145 // Determine which user hash no more points left
1146 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1147         // Init array
1148         $userids = array(
1149                 'url_userid'   => array(),
1150                 'points'       => array(),
1151                 'notified'     => array(),
1152         );
1153
1154         // Do we have a current user id?
1155         if ((isMember()) && ($limit == '0')) {
1156                 // Then add this as well
1157                 $userids['url_userid'][getMemberId()]      = getMemberId();
1158                 $userids['points'][getMemberId()]   = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1159                 $userids['notified'][getMemberId()] = '0';
1160
1161                 // Get all userid except logged in one
1162                 $result = SQL_QUERY_ESC("SELECT
1163         u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1164 FROM
1165         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1166 INNER JOIN
1167         `{?_MYSQL_PREFIX?}_user_data` AS d
1168 ON
1169         u.url_userid=d.userid
1170 WHERE
1171         u.url_userid NOT IN (%s,0) AND u.url_status='ACTIVE'
1172 GROUP BY
1173         u.url_userid
1174 ORDER BY
1175         u.url_userid ASC",
1176                         array(getMemberId()), __FUNCTION__, __LINE__);
1177         } else {
1178                 // Get all userid
1179                 $result = SQL_QUERY("SELECT
1180         u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1181 FROM
1182         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1183 INNER JOIN
1184         `{?_MYSQL_PREFIX?}_user_data` AS d
1185 ON
1186         u.url_userid=d.userid
1187 WHERE
1188         u.url_status='ACTIVE'
1189 GROUP BY
1190         u.url_userid
1191 ORDER BY
1192         u.url_userid ASC", __FUNCTION__, __LINE__);
1193         }
1194
1195         // Load all userid
1196         while ($content = SQL_FETCHARRAY($result)) {
1197                 // Get total points
1198                 $points = countSumTotalData($content['url_userid'], 'user_points', 'points') - countSumTotalData($content['url_userid'], 'user_data', 'used_points');
1199                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['url_userid']},points={$points}", false);
1200
1201                 // Shall we add this to ignore?
1202                 if ($points <= $limit) {
1203                         // Ignore this one!
1204                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['url_userid']} has depleted points amount!", false);
1205                         $userids['url_userid'][$content['url_userid']]      = $content['url_userid'];
1206                         $userids['points'][$content['url_userid']]   = $points;
1207                         $userids['notified'][$content['url_userid']] = $content['notified'];
1208                 } // END - if
1209         } // END - while
1210
1211         // Free result
1212         SQL_FREERESULT($result);
1213
1214         // Debug message
1215         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1216
1217         // Return result
1218         return $userids;
1219 }
1220
1221 // Determine how many users are Online in surfbar
1222 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1223         // Count all users in surfbar modue and return the value
1224         $result = SQL_QUERY("SELECT
1225         `stats_id`
1226 FROM
1227         `{?_MYSQL_PREFIX?}_surfbar_stats`
1228 WHERE
1229         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1230 GROUP BY
1231         `stats_userid` ASC", __FUNCTION__, __LINE__);
1232
1233         // Fetch count
1234         $cnt = SQL_NUMROWS($result);
1235
1236         // Free result
1237         SQL_FREERESULT($result);
1238
1239         // Return result
1240         return $cnt;
1241 }
1242
1243 // Determine waiting time for one URL
1244 function SURFBAR_DETERMINE_WAIT_TIME () {
1245         // Get fixed reload lock
1246         $fixed = SURFBAR_GET_FIXED_RELOAD();
1247
1248         // Is the fixed reload time set?
1249         if ($fixed > 0) {
1250                 // Return it
1251                 return $fixed;
1252         } // END - if
1253
1254         // Static time is default
1255         $time = getConfig('surfbar_static_time');
1256
1257         // Which payment model do we have?
1258         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1259                 // "Calculate" dynamic time
1260                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1261         } // END - if
1262
1263         // Return value
1264         return $time;
1265 }
1266
1267 // Changes the status of an URL from given to other
1268 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1269         // Make new status always lower-case
1270         $newStatus = strtolower($newStatus);
1271
1272         // Get URL data for status comparison if missing
1273         if ((!is_array($data)) || (count($data) == 0)) {
1274                 // Fetch missing URL data
1275                 $data = SURFBAR_GET_URL_DATA($urlId);
1276         } // END - if
1277
1278         // Is the new status set?
1279         if ((!is_string($newStatus)) || (empty($newStatus))) {
1280                 // Abort here, but fine!
1281                 return true;
1282         } // END - if
1283
1284         // Is the status like prevStatus is saying?
1285         if ($data[$urlId]['url_status'] != $prevStatus) {
1286                 // No, then abort here
1287                 return false;
1288         } // END - if
1289
1290
1291         // Update the status now
1292         // ---------- Comment out for debugging/developing member actions! ---------
1293         //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `url_id`=%s LIMIT 1",
1294         //      array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1295         // ---------- Comment out for debugging/developing member actions! ---------
1296
1297         // Was that fine?
1298         // ---------- Comment out for debugging/developing member actions! ---------
1299         //if (SQL_AFFECTEDROWS() != 1) {
1300         //      // No, something went wrong
1301         //      return false;
1302         //} // END - if
1303         // ---------- Comment out for debugging/developing member actions! ---------
1304
1305         // Prepare content for notification routines
1306         $data[$urlId]['url_userid']  = $data[$urlId]['url_userid'];
1307         $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1308         $data[$urlId]['reward']      = translateComma(getConfig('surfbar_static_reward'));
1309         $data[$urlId]['costs']       = translateComma(getConfig('surfbar_static_costs'));
1310
1311         // Do some dirty fixing here:
1312         if (($data[$urlId]['url_status'] == 'STOPPED') && ($newStatus == 'pending')) {
1313                 // Fix for template change
1314                 $newStatus = 'continued';
1315         } // END - if
1316
1317         // Send admin notification
1318         SURFBAR_NOTIFY_ADMIN('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1319
1320         // Send user notification
1321         SURFBAR_NOTIFY_USER('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1322
1323         // All done!
1324         return true;
1325 }
1326
1327 // Calculate minimum value for dynamic payment model
1328 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1329         // Addon is zero by default
1330         $addon = '0';
1331
1332         // Percentage part
1333         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1334
1335         // Get total users
1336         $totalUsers = getTotalConfirmedUser();
1337
1338         // Get online users
1339         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1340
1341         // Calculate addon
1342         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1343
1344         // Get total URLs
1345         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1346
1347         // Get user's total URLs
1348         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1349
1350         // Calculate addon
1351         if ($totalUrls > 0) {
1352                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1353         } else {
1354                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1355         }
1356
1357         // Return addon
1358         return $addon;
1359 }
1360
1361 // Calculate maximum value for dynamic payment model
1362 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1363         // Addon is zero by default
1364         $addon = '0';
1365
1366         // Maximum value
1367         $max = log(2);
1368
1369         // Percentage part
1370         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1371
1372         // Get total users
1373         $totalUsers = getTotalConfirmedUser();
1374
1375         // Calculate addon
1376         $addon += abs($max * $percent * $totalUsers);
1377
1378         // Get total URLs
1379         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1380
1381         // Calculate addon
1382         $addon += abs($max * $percent * $totalUrls);
1383
1384         // Return addon
1385         return $addon;
1386 }
1387
1388 // Calculate dynamic lock
1389 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1390         // Default lock is 30 seconds
1391         $addon = 30;
1392
1393         // Get online users
1394         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1395
1396         // Calculate lock
1397         $addon = abs(log($onlineUsers / $addon + 1));
1398
1399         // Return value
1400         return $addon;
1401 }
1402
1403 // "Getter" for lock ids array
1404 function SURFBAR_GET_LOCK_IDS () {
1405         // Prepare some arrays
1406         $IDs = array();
1407         $USE = array();
1408         $ignored = array();
1409
1410         // Get all id from locks within the timestamp
1411         $result = SQL_QUERY_ESC("SELECT `locks_id`, `locks_url_id`, UNIX_TIMESTAMP(`locks_last_surfed`) AS last_surfed
1412 FROM
1413         `{?_MYSQL_PREFIX?}_surfbar_locks`
1414 WHERE
1415         `locks_userid`=%s
1416 ORDER BY
1417         `locks_id` ASC", array(getMemberId()),
1418         __FUNCTION__, __LINE__);
1419
1420         // Load all entries
1421         while ($content = SQL_FETCHARRAY($result)) {
1422                 // Debug message
1423                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1424
1425                 // Skip entries that are too old
1426                 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1427                         // Debug message
1428                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1429
1430                         // Add only if missing or bigger
1431                         if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1432                                 // Debug message
1433                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1434
1435                                 // Add this id
1436                                 $IDs[$content['url_id']] = $content['last_surfed'];
1437                                 $USE[$content['url_id']] = $content['id'];
1438                         } // END - if
1439                 } else {
1440                         // Debug message
1441                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1442
1443                         // Ignore these old entries!
1444                         $ignored[] = $content['url_id'];
1445                         unset($IDs[$content['url_id']]);
1446                         unset($USE[$content['url_id']]);
1447                 }
1448         } // END - while
1449
1450         // Free result
1451         SQL_FREERESULT($result);
1452
1453         // Return array
1454         return $USE;
1455 }
1456
1457 // "Getter" for maximum random number
1458 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1459         // Count max availabe entries
1460         $result = SQL_QUERY("SELECT
1461         sbu.url_id AS cnt
1462 FROM
1463         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1464 LEFT JOIN
1465         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1466 ON
1467         sbu.url_id=sbs.salts_url_id
1468 LEFT JOIN
1469         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1470 ON
1471         sbu.url_id=l.locks_url_id
1472 WHERE
1473         sbu.url_userid NOT IN (".implode(',', $userids).") AND
1474         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1475         sbu.url_status='ACTIVE'
1476         ".$add."
1477 GROUP BY
1478         sbu.url_id ASC", __FUNCTION__, __LINE__);
1479
1480         // Log last query
1481         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1482
1483         // Fetch max rand
1484         $maxRand = SQL_NUMROWS($result);
1485
1486         // Free result
1487         SQL_FREERESULT($result);
1488
1489         // Return value
1490         return $maxRand;
1491 }
1492
1493 // Load all URLs of the current user and return it as an array
1494 function SURFBAR_GET_USER_URLS () {
1495         // Init array
1496         $urlArray = array();
1497
1498         // Begin the query
1499         $result = SQL_QUERY_ESC("SELECT
1500         u.url_id,
1501         u.url_userid,
1502         u.url,
1503         u.url_status,
1504         u.url_views_total,
1505         u.url_views_max,
1506         u.url_views_allowed,
1507         UNIX_TIMESTAMP(u.url_registered) AS `url_registered`,
1508         UNIX_TIMESTAMP(u.url_last_locked) AS `url_last_locked`,
1509         u.url_lock_reason
1510 FROM
1511         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1512 WHERE
1513         u.url_userid=%s AND
1514         u.url_status != 'DELETED'
1515 ORDER BY
1516         u.url_id ASC",
1517         array(getMemberId()), __FUNCTION__, __LINE__);
1518
1519         // Are there entries?
1520         if (SQL_NUMROWS($result) > 0) {
1521                 // Load all rows
1522                 while ($row = SQL_FETCHARRAY($result)) {
1523                         // Add the row
1524                         $urlArray[$row['id']] = $row;
1525                 } // END - while
1526         } // END - if
1527
1528         // Free result
1529         SQL_FREERESULT($result);
1530
1531         // Return the array
1532         return $urlArray;
1533 }
1534
1535 // "Getter" for member action array for given status
1536 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1537         // Init array
1538         $returnArray = array();
1539
1540         // Get all assigned actions
1541         $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1542                 array($status), __FUNCTION__, __LINE__);
1543
1544         // Some entries there?
1545         if (SQL_NUMROWS($result) > 0) {
1546                 // Load all actions
1547                 // @TODO This can be somehow rewritten
1548                 while ($content = SQL_FETCHARRAY($result)) {
1549                         $returnArray[] = $content['action'];
1550                 } // END - if
1551         } // END - if
1552
1553         // Free result
1554         SQL_FREERESULT($result);
1555
1556         // Return result
1557         return $returnArray;
1558 }
1559
1560 // Reload to configured stop page
1561 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1562         // Internal or external?
1563         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1564                 // Reload to internal page
1565                 redirectToUrl('surfbar.php?frame=' . $page);
1566         } else {
1567                 // Reload to external page
1568                 redirectToConfiguredUrl('surfbar_pause_url');
1569         }
1570 }
1571
1572 // Determine next id for surfbar or get data for given id, always call this before you call other
1573 // getters below this function!!!
1574 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1575         // Default is no id and no random number
1576         $nextId = '0';
1577         $randNum = '0';
1578
1579         // Is the id set?
1580         if ($urlId == '0') {
1581                 // Get array with lock ids
1582                 $USE = SURFBAR_GET_LOCK_IDS();
1583
1584                 // Shall we add some URL ids to ignore?
1585                 $add = '';
1586                 if (count($USE) > 0) {
1587                         // Ignore some!
1588                         $add = " AND sbu.url_id NOT IN (";
1589                         foreach ($USE as $url_id => $lid) {
1590                                 // Add URL id
1591                                 $add .= $url_id.',';
1592                         } // END - foreach
1593
1594                         // Add closing bracket
1595                         $add = substr($add, 0, -1) . ')';
1596                 } // END - if
1597
1598                 // Determine depleted user account
1599                 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1600
1601                 // Get maximum randomness factor
1602                 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['url_userid'], $add);
1603
1604                 // If more than one URL can be called generate the random number!
1605                 if ($maxRand > 1) {
1606                         // Generate random number
1607                         $randNum = mt_rand(0, ($maxRand - 1));
1608                 } // END - if
1609
1610                 // And query the database
1611                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1612                 $result = SQL_QUERY_ESC("SELECT
1613         sbu.url_id,
1614         sbu.url_userid,
1615         sbu.url,
1616         sbs.salts_last_salt,
1617         sbu.url_views_total,
1618         sbu.url_views_max,
1619         sbu.url_views_allowed,
1620         UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1621         sbu.url_fixed_reload
1622 FROM
1623         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1624 LEFT JOIN
1625         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1626 ON
1627         sbu.url_id=sbs.salts_url_id
1628 LEFT JOIN
1629         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1630 ON
1631         sbu.url_id=l.locks_url_id
1632 WHERE
1633         sbu.url_userid NOT IN (".implode(',', $userids['url_userid']).") AND
1634         sbu.url_status='ACTIVE' AND
1635         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1636         ".$add."
1637 GROUP BY
1638         sbu.url_id
1639 ORDER BY
1640         l.locks_last_surfed ASC,
1641         sbu.url_id ASC
1642 LIMIT %s,1",
1643                         array($randNum), __FUNCTION__, __LINE__
1644                 );
1645         } else {
1646                 // Get data from specified id number
1647                 $result = SQL_QUERY_ESC("SELECT
1648         sbu.url_id,
1649         sbu.url_userid,
1650         sbu.url,
1651         sbs.salts_last_salt,
1652         sbu.url_views_total,
1653         sbu.url_views_max,
1654         sbu.url_views_allowed,
1655         UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1656         sbu.url_fixed_reload
1657 FROM
1658         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1659 LEFT JOIN
1660         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1661 ON
1662         sbu.url_id=sbs.salts_url_id
1663 LEFT JOIN
1664         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1665 ON
1666         sbu.url_id=l.locks_url_id
1667 WHERE
1668         sbu.url_userid != %s AND
1669         sbu.url_status='ACTIVE' AND
1670         sbu.url_id=%s AND
1671         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1672 LIMIT 1",
1673                         array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1674                 );
1675         }
1676
1677         // Is there an id number?
1678         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1679         if (SQL_NUMROWS($result) == 1) {
1680                 // Load/cache data
1681                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1682                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1683                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1684
1685                 // Determine waiting time
1686                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1687
1688                 // Is the last salt there?
1689                 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1690                         // Then repair it wit the static!
1691                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1692                         $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1693                 } // END - if
1694
1695                 // Fix missing last_surfed
1696                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1697                         // Fix it here
1698                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1699                         $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1700                 } // END - if
1701
1702                 // Get base/fixed reward and costs
1703                 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1704                 $GLOBALS['surfbar_cache']['costs']  = SURFBAR_DETERMINE_COSTS();
1705                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1706
1707                 // Only in dynamic model add the dynamic bonus!
1708                 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1709                         // Calculate dynamic reward/costs and add it
1710                         $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1711                         $GLOBALS['surfbar_cache']['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1712                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1713                 } // END - if
1714
1715                 // Now get the id
1716                 $nextId = SURFBAR_GET_ID();
1717         } // END - if
1718
1719         // Free result
1720         SQL_FREERESULT($result);
1721
1722         // Return result
1723         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1724         return $nextId;
1725 }
1726
1727 // -----------------------------------------------------------------------------
1728 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1729 // THE $GLOBALS['surfbar_cache'] ARRAY!
1730 // -----------------------------------------------------------------------------
1731
1732 // Initializes the surfbar
1733 function SURFBAR_INIT () {
1734         // Init cache array
1735         $GLOBALS['surfbar_cache'] = array();
1736 }
1737
1738 // Private getter for data elements
1739 function SURFBAR_GET_DATA ($element) {
1740         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1741
1742         // Default is null
1743         $data = null;
1744
1745         // Is the entry there?
1746         if (isset($GLOBALS['surfbar_cache'][$element])) {
1747                 // Then take it
1748                 $data = $GLOBALS['surfbar_cache'][$element];
1749         } else { // END - if
1750                 print('<pre>');
1751                 print_r($GLOBALS['surfbar_cache']);
1752                 print('</pre>');
1753                 debug_report_bug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
1754         }
1755
1756         // Return result
1757         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data, false);
1758         return $data;
1759 }
1760
1761 // Getter for reward from cache
1762 function SURFBAR_GET_REWARD () {
1763         // Get data element and return its contents
1764         return SURFBAR_GET_DATA('reward');
1765 }
1766
1767 // Getter for costs from cache
1768 function SURFBAR_GET_COSTS () {
1769         // Get data element and return its contents
1770         return SURFBAR_GET_DATA('costs');
1771 }
1772
1773 // Getter for URL from cache
1774 function SURFBAR_GET_URL () {
1775         // Get data element and return its contents
1776         return SURFBAR_GET_DATA('url');
1777 }
1778
1779 // Getter for salt from cache
1780 function SURFBAR_GET_SALT () {
1781         // Get data element and return its contents
1782         return SURFBAR_GET_DATA('salt');
1783 }
1784
1785 // Getter for id from cache
1786 function SURFBAR_GET_ID () {
1787         // Get data element and return its contents
1788         return SURFBAR_GET_DATA('url_id');
1789 }
1790
1791 // Getter for userid from cache
1792 function SURFBAR_GET_USERID () {
1793         // Get data element and return its contents
1794         return SURFBAR_GET_DATA('url_userid');
1795 }
1796
1797 // Getter for user reload locks
1798 function SURFBAR_GET_USER_LOCKS () {
1799         // Get data element and return its contents
1800         return SURFBAR_GET_DATA('user_locks');
1801 }
1802
1803 // Getter for reload time
1804 function SURFBAR_GET_RELOAD_TIME () {
1805         // Get data element and return its contents
1806         return SURFBAR_GET_DATA('time');
1807 }
1808
1809 // Getter for allowed views
1810 function SURFBAR_GET_VIEWS_ALLOWED () {
1811         // Get data element and return its contents
1812         return SURFBAR_GET_DATA('url_views_allowed');
1813 }
1814
1815 // Getter for maximum views
1816 function SURFBAR_GET_VIEWS_MAX () {
1817         // Get data element and return its contents
1818         return SURFBAR_GET_DATA('url_views_max');
1819 }
1820
1821 // Getter for fixed reload
1822 function SURFBAR_GET_FIXED_RELOAD () {
1823         // Get data element and return its contents
1824         return SURFBAR_GET_DATA('url_fixed_reload');
1825 }
1826
1827 // Getter for surf lock
1828 function SURFBAR_GET_SURF_LOCK () {
1829         // Get data element and return its contents
1830         return SURFBAR_GET_DATA('surf_lock');
1831 }
1832
1833 // Getter for new status
1834 function SURFBAR_GET_NEW_STATUS () {
1835         // Get data element and return its contents
1836         return SURFBAR_GET_DATA('new_status');
1837 }
1838
1839 // [EOF]
1840 ?>