]> git.mxchange.org Git - mailer.git/blob - inc/libs/surfbar_functions.php
10a2ba6583693fc99c4f03c54ff0a6aac06abdeb
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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 - 2008 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
42         require($INC);
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 (!IS_ADMIN()) {
53                 // Not an admin
54                 DEBUG_LOG(__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                 DEBUG_LOG(__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                 DEBUG_LOG(__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                 DEBUG_LOG(__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                 DEBUG_LOG(__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                 DEBUG_LOG(__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, $uid) {
84         // Do some pre-checks
85         if (!IS_ADMIN()) {
86                 // Not an admin
87                 return false;
88         } elseif (!isUrlValid($url)) {
89                 // URL invalid
90                 return false;
91         } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
92                 // URL already found in surfbar!
93                 return false;
94         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
95                 // No more allowed!
96                 return false;
97         }
98
99         // Register the new URL
100         return SURFBAR_REGISTER_URL($url, $uid, '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 (!IS_ADMIN()) {
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 (!IS_ADMIN()) {
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 (!IS_MEMBER()) {
166                 // Not a member
167                 return false;
168         } elseif ((!isUrlValid($url)) && (!IS_ADMIN())) {
169                 // URL invalid
170                 return false;
171         } elseif (SURFBAR_LOOKUP_BY_URL($url, getUserId())) {
172                 // URL already found in surfbar!
173                 return false;
174         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getUserId())) {
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, getUserId(), '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_getModeAction_ARRAY($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 .= LOAD_TEMPLATE('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, $URLs) {
220         // By default no action is performed
221         $performed = false;
222
223         // Is this a member?
224         if (!IS_MEMBER()) {
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($URLs[$formData['id']])) {
231                 // ID not found in cache
232                 return false;
233         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
234                 // Action not allowed for current URL status
235                 return false;
236         }
237
238         // Secure action
239         $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
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                 $URLs[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
254
255                 // Extract URL data for call-back
256                 $urlData = array(merge_array($URLs[$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                 DEBUG_LOG(__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['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['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['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'] = $urlData['views_max'];
354
355         // Return status change
356         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['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['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
367         $urlData['registered']    = generateDateTime($urlData['registered'], '2');
368         $urlData['views_total']   = translateComma($urlData['views_total']);
369         $urlData['views_max']     = translateComma($urlData['views_max']);
370         $urlData['views_allowed'] = translateComma($urlData['views_allowed']);
371         $urlData['last_locked']   = generateDateTime($urlData['last_locked'], '2');
372
373         // Is the lock reason empty?
374         if (empty($urlData['lock_reason'])) {
375                 // Fix it to three dashes
376                 $urlData['lock_reason'] = '---';
377         } // END - if
378
379         // Include fields only for action 'edit'
380         if ($action == 'edit') {
381                 // Default is not limited
382                 $urlData['limited_yes'] = '';
383                 $urlData['limited_no']  = ' checked="checked"';
384                 $urlData['limited']     = 'false';
385
386                 // Is this URL limited?
387                 if ($urlData['views_max'] > 0) {
388                         // Then rewrite form data
389                         $urlData['limited_yes'] = ' checked="checked"';
390                         $urlData['limited_no']  = '';
391                         $urlData['limited']     = 'true';
392                 } // END - if
393         } // END - if
394
395         // Load the form and display it
396         LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
397
398         // All fine by default ... ;-)
399         return true;
400 }
401
402 // Execute choosen action
403 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
404         // By default nothing is executed
405         $executed = false;
406
407         // Is limitation "no" and "limit" is > 0?
408         if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == 'N') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
409                 // Set it to unlimited
410                 $urlData[$action]['limit'] = 0;
411         } // END - if
412
413         // Construct function name
414         $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
415
416         // Is 'userid' set and not 'uid' ?
417         if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
418                 // Auto-fix this
419                 $urlData['uid'] = $urlData['userid'];
420         } // END - if
421
422         // Is that function there?
423         if (function_exists($functionName)) {
424                 // Execute the function
425                 if (call_user_func_array($functionName, array($urlData)) == true) {
426                         // Update status as well
427                         $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
428                 } // END - if
429         } else {
430                 // Not found!
431                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
432         }
433
434         // Return status
435         return $executed;
436 }
437 // "Execute edit" function: Update changed data
438 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
439         // Default is nothing done
440         $status = false;
441
442         // Translate URLs for testing
443         $url1 = COMPILE_CODE($urlData['url']);
444         $url2 = COMPILE_CODE($urlData['edit']['url']);
445
446         // Has the URL or limit changed?
447         if (true) {
448                 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
449                 // Run the query
450                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET url='%s', views_allowed=%s, views_max=%s WHERE `id`=%s AND `status`='%s' LIMIT 1",
451                 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
452
453                 // All fine
454                 $status = true;
455         }
456
457         // Return status
458         return $status;
459 }
460 // "Execute delete" function: Does nothing...
461 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
462         // Nothing special to do (see above function for such "special actions" to perform)
463         return true;
464 }
465 //
466 // -----------------------------------------------------------------------------
467 //                           Self-maintenance functions
468 // -----------------------------------------------------------------------------
469 //
470 // Main function
471 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
472         // Handle URLs which limit has depleted so we can stop them
473         SURFBAR_HANDLE_DEPLETED_VIEWS();
474
475         // Handle low-points amounts
476         SURFBAR_HANDLE_LOW_POINTS();
477 }
478 // Handle URLs which limit has depleted
479 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
480         // Get all URLs
481         $urlArray = SURFBAR_GET_URL_DATA('0', 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
482
483         // Do we have some entries?
484         if (count($urlArray) > 0) {
485                 // Then handle all!
486                 foreach ($urlArray as $id => $urlData) {
487                         // Backup data
488                         $data = $urlData;
489
490                         // Rewrite array for next call
491                         $urlData[$id] = $data;
492
493                         // Handle the status
494                         SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
495                 } // END - foreach
496         } // END - if
497 }
498
499 // Alert users which have URLs booked and are low on points amount
500 function SURFBAR_HANDLE_LOW_POINTS () {
501         // Get all userids
502         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
503
504         // "Walk" through all URLs
505         foreach ($UIDs['uid'] as $uid => $dummy) {
506                 // Is the last notification far enougth away to notify again?
507                 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
508                         // Prepare content
509                         $content = array(
510                                 'uid'      => $uid,
511                                 'low'      => translateComma(getConfig('surfbar_warn_low_points')),
512                                 'points'   => translateComma($UIDs['points'][$uid]),
513                                 'notified' => generateDateTime($UIDs['notified'][$uid]),
514                                 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
515                         );
516
517                         // Notify this user
518                         SURFBAR_NOTIFY_USER('low_points', $content);
519
520                         // Update last notified
521                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE `userid`=%s LIMIT 1",
522                         array($uid), __FUNCTION__, __LINE__);
523                 } // END - if
524         } // END - foreach
525 }
526
527 //
528 // -----------------------------------------------------------------------------
529 //                               Generic functions
530 // -----------------------------------------------------------------------------
531 //
532
533 // Looks up by an URL
534 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
535         // Now lookup that given URL by itself
536         $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($uid)));
537
538         // Was it found?
539         return (count($urlArray) > 0);
540 }
541
542 // Load URL data by given search term and column
543 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'id', $order = 'id', $sort = 'ASC', $group = 'id', $add = '') {
544         // By default nothing is found
545         $GLOBALS['last_url_data'] = array();
546
547         // Is the column an id number?
548         if (($column == 'id') || ($column == 'userid')) {
549                 // Extra secure input
550                 $searchTerm = bigintval($searchTerm);
551         } // END - if
552
553         // If the column is 'id' there can be only one entry
554         $limit = '';
555         if ($column == 'id') {
556                 $limit = "LIMIT 1";
557         } // END - if
558
559         // Look up the record
560         $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed, fixed_reload
561 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
562 WHERE %s='%s'".$add."
563 ORDER BY %s %s
564 %s",
565         array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
566
567         // Is there at least one record?
568         if (SQL_NUMROWS($result) > 0) {
569                 // Then load all!
570                 while ($dataRow = SQL_FETCHARRAY($result)) {
571                         // Shall we group these results?
572                         if ($group == 'id') {
573                                 // Add the row by id as index
574                                 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
575                         } else {
576                                 // Group entries
577                                 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
578                         }
579                 } // END - while
580         } // END - if
581
582         // Free the result
583         SQL_FREERESULT($result);
584
585         // Return the result
586         return $GLOBALS['last_url_data'];
587 }
588
589 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
590 function SURFBAR_REGISTER_URL ($url, $uid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
591         // Make sure by the user registered URLs are always pending
592         if ($addMode == 'reg') {
593                 $status = 'PENDING';
594         } // END - if
595
596         // Prepare content
597         $content = merge_array($extraFields, array(
598                 'url'         => $url,
599                 'frametester' => FRAMETESTER($url),
600                 'uid'         => $uid,
601                 'status'      => $status,
602         ));
603
604         // Is limit/reload set?
605         if (!isset($config['limit'])) {
606                 $content['limit']  = 0;
607         } // END - if
608         if (!isset($config['reload'])) {
609                 $content['reload'] = 0;
610         } // END - if
611
612         // Insert the URL into database
613         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
614
615         // Is this ID valid?
616         if ($content['insert_id'] == 0) {
617                 // INSERT did not insert any data!
618                 return false;
619         } // END - if
620
621         // Translate status and limit
622         $content['limit'] = surfbarTranslateLimit($content['limit']);
623
624         // If in reg-mode we notify admin
625         if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
626                 // Notify admin even when he as unlocked an email
627                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
628         } // END - if
629
630         // Send mail to user
631         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
632
633         // Return the insert id
634         return $content['insert_id'];
635 }
636
637 // Inserts an url by given data array and return the insert id
638 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
639         // Get userid
640         $uid = bigintval($urlData['uid']);
641
642         // Is the id set?
643         if (empty($uid)) $uid = 0;
644
645         // Just run the insert query for now
646         SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_urls` (userid,url,status,views_max,views_allowed,fixed_reload) VALUES (%s,'%s','%s',%s,%s,%s)",
647         array(
648         $uid,
649         $urlData['url'],
650         $urlData['status'],
651         $urlData['limit'],
652         $urlData['limit'],
653         $urlData['reload']
654         ), __FUNCTION__, __LINE__
655         );
656
657         // Return insert id
658         return SQL_INSERTID();
659 }
660
661 // Notify admin(s) with a selected message and content
662 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
663         // Prepare template name
664         $templateName = sprintf("admin_surfbar_%s", $messageType);
665
666         // Prepare subject
667         $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
668         strtoupper($messageType)
669         ));
670
671         // Is the subject line there?
672         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
673                 // Set default subject if following eval() wents wrong
674                 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
675         } // END - if
676
677         // Translate some data if present
678         if (isset($content['status']))        $content['status']        = surfbarTranslateUserStatus($content['status']);
679         if (isset($content['registered']))    $content['registered']    = generateDateTime($content['registered'], '2');
680         if (isset($content['last_locked']))   $content['last_locked']   = generateDateTime($content['last_locked'], '2');
681         if (isset($content['views_total']))   $content['views_total']   = translateComma($content['views_total']);
682         if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
683         if (isset($content['views_max']))     $content['views_max']     = translateComma($content['views_max']);
684
685         // Send the notification out
686         return sendAdminNotification($subject, $templateName, $content, $content['uid']);
687 }
688
689 // Notify the user about the performed action
690 function SURFBAR_NOTIFY_USER ($messageType, $content) {
691         // Skip notification if userid is zero
692         if ($content['uid'] == 0) {
693                 return false;
694         } // END - if
695
696         // Prepare template name
697         $templateName = sprintf("member_surfbar_%s", $messageType);
698
699         // Prepare subject
700         $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
701         strtoupper($messageType)
702         ));
703
704         // Is the subject line there?
705         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
706                 // Set default subject if following eval() wents wrong
707                 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
708         } // END - if
709
710         // Translate some data if present
711         if (isset($content['status']))        $content['status']        = surfbarTranslateUserStatus($content['status']);
712         if (isset($content['registered']))    $content['registered']    = generateDateTime($content['registered'], '2');
713         if (isset($content['last_locked']))   $content['last_locked']   = generateDateTime($content['last_locked'], '2');
714         if (isset($content['views_total']))   $content['views_total']   = translateComma($content['views_total']);
715         if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
716         if (isset($content['views_max']))     $content['views_max']     = translateComma($content['views_max']);
717
718         // Load template
719         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
720
721         // Send the email
722         return sendEmail($content['uid'], $subject, $mailText);
723 }
724
725 // Translates the limit
726 function surfbarTranslateLimit ($limit) {
727         // Is this zero?
728         if ($limit == 0) {
729                 // Unlimited!
730                 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
731         } else {
732                 // Translate comma
733                 $return = translateComma($limit);
734         }
735
736         // Return value
737         return $return;
738 }
739
740 // Translate the URL status
741 function surfbarTranslateUserStatus ($status) {
742         // Create constant name
743         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
744
745         // Set default translated status
746         $statusTranslated = '!'.$constantName.'!';
747
748         // Is the constant there?
749         if (defined($constantName)) {
750                 // Then get it's value
751                 $statusTranslated = constant($constantName);
752         } // END - if
753
754         // Return result
755         return $statusTranslated;
756 }
757
758 // Determine reward
759 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
760         // Static values are default
761         $reward = getConfig('surfbar_static_reward');
762
763         // Do we have static or dynamic?
764         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
765                 // "Calculate" dynamic reward
766                 if ($onlyMin) {
767                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
768                 } else {
769                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
770                 }
771         } // END - if
772
773         // Return reward
774         return $reward;
775 }
776
777 // Determine costs
778 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
779         // Static costs is default
780         $costs  = getConfig('surfbar_static_costs');
781
782         // Do we have static or dynamic?
783         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
784                 // "Calculate" dynamic costs
785                 if ($onlyMin) {
786                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
787                 } else {
788                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
789                 }
790         } // END - if
791
792         // Return costs
793         return $costs;
794 }
795
796 // "Calculate" dynamic add
797 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
798         // Get min/max values
799         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
800         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
801
802         // "Calculate" dynamic part and return it
803         return mt_rand($min, $max);
804 }
805
806 // Determine right template name
807 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
808         // Default is the frameset
809         $templateName = "surfbar_frameset";
810
811         // Any frame set? ;-)
812         if (REQUEST_ISSET_GET('frame')) {
813                 // Use the frame as a template name part... ;-)
814                 $templateName = sprintf("surfbar_frame_%s",
815                 REQUEST_GET('frame')
816                 );
817         } // END - if
818
819         // Return result
820         return $templateName;
821 }
822
823 // Check if the "reload lock" of the current user is full, call this function
824 // before you call SURFBAR_CHECK_RELOAD_LOCK().
825 function SURFBAR_CHECK_RELOAD_FULL() {
826         // Default is full!
827         $isFull = true;
828
829         // Cache static reload lock
830         $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
831         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
832
833         // Do we have dynamic model?
834         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
835                 // "Calculate" dynamic lock
836                 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
837         } // END - if
838
839         // Ask the database
840         $result = SQL_QUERY_ESC("SELECT
841         COUNT(l.id) AS cnt
842 FROM
843         `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
844 INNER JOIN
845         `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
846 ON
847         u.id=l.url_id
848 WHERE
849         l.userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND (((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR u.fixed_reload = 0)
850 LIMIT 1",
851                 array(getUserId()), __FUNCTION__, __LINE__
852         );
853
854         // Fetch row
855         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
856
857         // Is it null?
858         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
859                 // Then fix it to zero!
860                 $GLOBALS['surfbar_cache']['user_locks'] = 0;
861         } // END - if
862
863         // Free result
864         SQL_FREERESULT($result);
865
866         // Get total URLs
867         $total = SURFBAR_GET_TOTAL_URLS();
868
869         // Do we have some URLs in lock? Admins can always surf on own URLs!
870         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
871         $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
872
873         // Return result
874         return $isFull;
875 }
876
877 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
878 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = 0) {
879         // Determine depleted user account
880         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
881
882         // If we dont get any user ids back, there are no URLs
883         if (count($UIDs['uid']) == 0) {
884                 // No user ids found, no URLs!
885                 return 0;
886         } // END - if
887
888         // Is the exlude userid set?
889         if ($excludeUserId > 0) {
890                 // Then add it
891                 $UIDs['uid'][$excludeUserId] = $excludeUserId;
892         } // END - if
893
894         // Get amount from database
895         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
896 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
897 WHERE `userid` NOT IN (".implode(', ', $UIDs['uid']).") AND `status`='%s'",
898                 array($status), __FUNCTION__, __LINE__
899         );
900
901         // Fetch row
902         list($cnt) = SQL_FETCHROW($result);
903
904         // Free result
905         SQL_FREERESULT($result);
906
907         // Return result
908         return $cnt;
909 }
910
911 // Check wether the user is allowed to book more URLs
912 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
913         // Is this admin and userid is zero or does the user has some URLs left to book?
914         return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, '', array("REJECTED")) < getConfig('surfbar_max_order')));
915 }
916
917 // Get total amount of URLs of given status for current user
918 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status = '',$exclude = '') {
919         // Is the user 0 and user is logged in?
920         if (($uid == 0) && (IS_MEMBER())) {
921                 // Then use this userid
922                 $uid = getUserId();
923         } elseif ($uid == 0) {
924                 // Error!
925                 return (getConfig('surfbar_max_order') + 1);
926         }
927
928         // Default is all URLs
929         $add = '';
930
931         // Is the status set?
932         if (is_array($status)) {
933                 // Only URLs with these status
934                 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
935         } elseif (!empty($status)) {
936                 // Only URLs with this status
937                 $add = sprintf(" AND `status`='%s'", $status);
938         } elseif (is_array($exclude)) {
939                 // Exclude URLs with these status
940                 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
941         } elseif (!empty($exclude)) {
942                 // Exclude URLs with this status
943                 $add = sprintf(" AND `status` != '%s'", $exclude);
944         }
945
946         // Get amount from database
947         $cnt = GET_TOTAL_DATA($uid, 'surfbar_urls', 'id', 'userid', true, $add);
948
949         // Return result
950         return $cnt;
951 }
952
953 // Generate a validation code for the given id number
954 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
955         // @TODO Invalid salt should be refused
956         $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
957
958         // Get code length from config
959         $length = getConfig('code_length');
960
961         // Fix length to 10
962         if ($length == 0) $length = 10;
963
964         // Generate a code until the length matches
965         $valCode = '';
966         while (strlen($valCode) != $length) {
967                 // Is the salt set?
968                 if (empty($salt)) {
969                         // Generate random hashed string
970                         $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
971                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
972                 } else {
973                         // Use this as salt!
974                         $GLOBALS['surfbar_cache']['salt'] = $salt;
975                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
976                 }
977
978                 // ... and now the validation code
979                 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getUserId());
980                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
981         } // END - while
982
983         // Hash it with md5() and salt it with the random string
984         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
985
986         // Finally encrypt it PGP-like and return it
987         $valHashedCode = generatePassString($hashedCode);
988
989         // Return hashed value
990         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
991         return $valHashedCode;
992 }
993
994 // Check validation code
995 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
996         // Secure id number
997         $urlId = bigintval($urlId);
998
999         // Now generate the code again
1000         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1001
1002         // Return result of checking hashes and salts
1003         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1004         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt.'|'.SURFBAR_GET_DATA('last_salt')."+++", false);
1005         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1006 }
1007
1008 // Lockdown the userid/id combination (reload lock)
1009 function SURFBAR_LOCKDOWN_ID ($urlId) {
1010         //* DEBUG: */ OUTPUT_HTML("LOCK!");
1011         ///* DEBUG: */ return;
1012         // Just add it to the database
1013         SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1014                 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1015
1016         // Remove the salt from database
1017         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1018                 array(bigintval($urlId), getUserId()), __FUNCTION__, __LINE__);
1019 }
1020
1021 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1022 function SURFBAR_PAY_POINTS () {
1023         // Remove it from the URL owner
1024         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1025         if (SURFBAR_GET_USERID() > 0) {
1026                 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1027         } // END - if
1028
1029         // Book it to the user
1030         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".getUserId().",reward=".SURFBAR_GET_REWARD()."", false);
1031         ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getUserId(), SURFBAR_GET_DATA('reward'));
1032 }
1033
1034 // Updates the statistics of current URL/userid
1035 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1036         // Init add
1037         $add = '';
1038
1039         // Get allowed views
1040         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1041
1042         // Do we have a limit?
1043         if ($allowed > 0) {
1044                 // Then count views_max down!
1045                 $add .= ", `views_max`=`views_max`-1";
1046         } // END - if
1047
1048         // Update URL stats
1049         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1050                 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1051
1052         // Update the stats entry
1053         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1054                 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1055
1056         // Was that update okay?
1057         if (SQL_AFFECTEDROWS() < 1) {
1058                 // No, then insert entry
1059                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1060                 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1061         } // END - if
1062
1063         // Update total/daily/weekly/monthly counter
1064         incrementConfigEntry('surfbar_total_counter');
1065         incrementConfigEntry('surfbar_daily_counter');
1066         incrementConfigEntry('surfbar_weekly_counter');
1067         incrementConfigEntry('surfbar_monthly_counter');
1068
1069         // Update config as well
1070         updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1071 }
1072
1073 // Update the salt for validation and statistics
1074 function SURFBAR_UPDATE_SALT_STATS () {
1075         // Update statistics record
1076         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1077
1078         // Simply store the salt from cache away in database...
1079         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1080                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getUserId()), __FUNCTION__, __LINE__);
1081
1082         // Debug message
1083         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".getUserId()."", false);
1084
1085         // Was that okay?
1086         if (SQL_AFFECTEDROWS() < 1) {
1087                 // Insert missing entry!
1088                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1089                         array(SURFBAR_GET_ID(), getUserId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1090         } // END - if
1091
1092         // Debug message
1093         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1094
1095         // Return if the update was okay
1096         return (SQL_AFFECTEDROWS() == 1);
1097 }
1098
1099 // Check if the reload lock is active for given id
1100 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1101         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1102         // Ask the database
1103         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1104 FROM
1105         `{!_MYSQL_PREFIX!}_surfbar_locks`
1106 WHERE
1107         `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1108 ORDER BY
1109         `last_surfed` ASC
1110 LIMIT 1",
1111                 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1112         );
1113
1114         // Fetch counter
1115         list($cnt) = SQL_FETCHROW($result);
1116
1117         // Free result
1118         SQL_FREERESULT($result);
1119
1120         // Return check
1121         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1122         return ($cnt == 1);
1123 }
1124
1125 // Determine which user hash no more points left
1126 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1127         // Init array
1128         $UIDs = array(
1129                 'uid'      => array(),
1130                 'points'   => array(),
1131                 'notified' => array(),
1132         );
1133
1134         // Do we have a current user id?
1135         if ((IS_MEMBER()) && ($limit == 0)) {
1136                 // Then add this as well
1137                 $UIDs['uid'][getUserId()]      = getUserId();
1138                 $UIDs['points'][getUserId()]   = GET_TOTAL_DATA(getUserId(), 'user_points', 'points') - GET_TOTAL_DATA(getUserId(), 'user_data', 'used_points');
1139                 $UIDs['notified'][getUserId()] = 0;
1140
1141                 // Get all userid except logged in one
1142                 $result = SQL_QUERY_ESC("SELECT
1143         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1144 FROM
1145         `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1146 INNER JOIN
1147         `{!_MYSQL_PREFIX!}_user_data` AS d
1148 ON
1149         u.userid=d.userid
1150 WHERE
1151         u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1152 GROUP BY
1153         u.userid
1154 ORDER BY
1155         u.userid ASC",
1156                         array(getUserId()), __FUNCTION__, __LINE__);
1157         } else {
1158                 // Get all userid
1159                 $result = SQL_QUERY("SELECT
1160         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1161 FROM
1162         `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1163 INNER JOIN
1164         `{!_MYSQL_PREFIX!}_user_data` AS d
1165 ON
1166         u.userid=d.userid
1167 WHERE
1168         u.`status`='ACTIVE'
1169 GROUP BY
1170         u.userid
1171 ORDER BY
1172         u.userid ASC", __FUNCTION__, __LINE__);
1173         }
1174
1175         // Load all userid
1176         while ($content = SQL_FETCHARRAY($result)) {
1177                 // Get total points
1178                 $points = GET_TOTAL_DATA($content['userid'], 'user_points', 'points') - GET_TOTAL_DATA($content['userid'], 'user_data', 'used_points');
1179                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']},points={$points}", false);
1180
1181                 // Shall we add this to ignore?
1182                 if ($points <= $limit) {
1183                         // Ignore this one!
1184                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']} has depleted points amount!", false);
1185                         $UIDs['uid'][$content['userid']]      = $content['userid'];
1186                         $UIDs['points'][$content['userid']]   = $points;
1187                         $UIDs['notified'][$content['userid']] = $content['notified'];
1188                 } // END - if
1189         } // END - while
1190
1191         // Free result
1192         SQL_FREERESULT($result);
1193
1194         // Debug message
1195         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getUserId().')', false);
1196
1197         // Return result
1198         return $UIDs;
1199 }
1200
1201 // Determine how many users are Online in surfbar
1202 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1203         // Count all users in surfbar modue and return the value
1204         $result = SQL_QUERY_ESC("SELECT id
1205 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1206 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1207 GROUP BY userid",
1208         array(getConfig('online_timeout')), __FUNCTION__, __LINE__);
1209
1210         // Fetch count
1211         $cnt = SQL_NUMROWS($result);
1212
1213         // Free result
1214         SQL_FREERESULT($result);
1215
1216         // Return result
1217         return $cnt;
1218 }
1219
1220 // Determine waiting time for one URL
1221 function SURFBAR_DETERMINE_WAIT_TIME () {
1222         // Get fixed reload lock
1223         $fixed = SURFBAR_GET_FIXED_RELOAD();
1224
1225         // Is the fixed reload time set?
1226         if ($fixed > 0) {
1227                 // Return it
1228                 return $fixed;
1229         } // END - if
1230
1231         // Static time is default
1232         $time = getConfig('surfbar_static_time');
1233
1234         // Which payment model do we have?
1235         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1236                 // "Calculate" dynamic time
1237                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1238         } // END - if
1239
1240         // Return value
1241         return $time;
1242 }
1243
1244 // Changes the status of an URL from given to other
1245 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1246         // Make new status always lower-case
1247         $newStatus = strtolower($newStatus);
1248
1249         // Get URL data for status comparison if missing
1250         if ((!is_array($data)) || (count($data) == 0)) {
1251                 // Fetch missing URL data
1252                 $data = SURFBAR_GET_URL_DATA($urlId);
1253         } // END - if
1254
1255         // Is the new status set?
1256         if ((!is_string($newStatus)) || (empty($newStatus))) {
1257                 // Abort here, but fine!
1258                 return true;
1259         } // END - if
1260
1261         // Is the status like prevStatus is saying?
1262         if ($data[$urlId]['status'] != $prevStatus) {
1263                 // No, then abort here
1264                 return false;
1265         } // END - if
1266
1267
1268         // Update the status now
1269         // ---------- Comment out for debugging/developing member actions! ---------
1270         //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1271         //      array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1272         // ---------- Comment out for debugging/developing member actions! ---------
1273
1274         // Was that fine?
1275         // ---------- Comment out for debugging/developing member actions! ---------
1276         //if (SQL_AFFECTEDROWS() != 1) {
1277         //      // No, something went wrong
1278         //      return false;
1279         //} // END - if
1280         // ---------- Comment out for debugging/developing member actions! ---------
1281
1282         // Prepare content for notification routines
1283         $data[$urlId]['uid']         = $data[$urlId]['userid'];
1284         $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1285         $data[$urlId]['reward']      = translateComma(getConfig('surfbar_static_reward'));
1286         $data[$urlId]['costs']       = translateComma(getConfig('surfbar_static_costs'));
1287
1288         // Do some dirty fixing here:
1289         if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1290                 // Fix for template change
1291                 $newStatus = 'continued';
1292         } // END - if
1293
1294         // Send admin notification
1295         SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1296
1297         // Send user notification
1298         SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1299
1300         // All done!
1301         return true;
1302 }
1303
1304 // Calculate minimum value for dynamic payment model
1305 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1306         // Addon is zero by default
1307         $addon = 0;
1308
1309         // Percentage part
1310         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1311
1312         // Get total users
1313         $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1314
1315         // Get online users
1316         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1317
1318         // Calculate addon
1319         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1320
1321         // Get total URLs
1322         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1323
1324         // Get user's total URLs
1325         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1326
1327         // Calculate addon
1328         if ($totalUrls > 0) {
1329                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1330         } else {
1331                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1332         }
1333
1334         // Return addon
1335         return $addon;
1336 }
1337
1338 // Calculate maximum value for dynamic payment model
1339 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1340         // Addon is zero by default
1341         $addon = 0;
1342
1343         // Maximum value
1344         $max = log(2);
1345
1346         // Percentage part
1347         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1348
1349         // Get total users
1350         $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1351
1352         // Calculate addon
1353         $addon += abs($max * $percent * $totalUsers);
1354
1355         // Get total URLs
1356         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1357
1358         // Calculate addon
1359         $addon += abs($max * $percent * $totalUrls);
1360
1361         // Return addon
1362         return $addon;
1363 }
1364
1365 // Calculate dynamic lock
1366 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1367         // Default lock is 30 seconds
1368         $addon = 30;
1369
1370         // Get online users
1371         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1372
1373         // Calculate lock
1374         $addon = abs(log($onlineUsers / $addon + 1));
1375
1376         // Return value
1377         return $addon;
1378 }
1379
1380 // "Getter" for lock ids array
1381 function SURFBAR_GET_LOCK_IDS () {
1382         // Prepare some arrays
1383         $IDs = array();
1384         $USE = array();
1385         $ignored = array();
1386
1387         // Get all id from locks within the timestamp
1388         $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1389 FROM
1390         {!_MYSQL_PREFIX!}_surfbar_locks
1391 WHERE
1392         userid=%s
1393 ORDER BY
1394         id ASC", array(getUserId()),
1395         __FUNCTION__, __LINE__);
1396
1397         // Load all entries
1398         while ($content = SQL_FETCHARRAY($result)) {
1399                 // Debug message
1400                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$content['id']},url={$content['url_id']},rest=".(time() - $last).'/'.SURFBAR_GET_SURF_LOCK()."", false);
1401
1402                 // Skip entries that are too old
1403                 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1404                         // Debug message
1405                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1406
1407                         // Add only if missing or bigger
1408                         if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $last)) {
1409                                 // Debug message
1410                                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1411
1412                                 // Add this ID
1413                                 $IDs[$content['url_id']] = $last;
1414                                 $USE[$content['url_id']] = $content['id'];
1415                         } // END - if
1416                 } else {
1417                         // Debug message
1418                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1419
1420                         // Ignore these old entries!
1421                         $ignored[] = $content['url_id'];
1422                         unset($IDs[$content['url_id']]);
1423                         unset($USE[$content['url_id']]);
1424                 }
1425         } // END - while
1426
1427         // Free result
1428         SQL_FREERESULT($result);
1429
1430         // Return array
1431         return $USE;
1432 }
1433
1434 // "Getter" for maximum random number
1435 function SURFBAR_GET_MAX_RANDOM ($UIDs, $add) {
1436         // Count max availabe entries
1437         $result = SQL_QUERY("SELECT sbu.id AS cnt
1438 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1439 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1440 ON sbu.id=sbs.url_id
1441 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1442 ON sbu.id=l.url_id
1443 WHERE sbu.userid NOT IN (".implode(',', $UIDs).") AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0)) AND sbu.`status`='ACTIVE'".$add."
1444 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1445
1446         // Log last query
1447         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1448
1449         // Fetch max rand
1450         $maxRand = SQL_NUMROWS($result);
1451
1452         // Free result
1453         SQL_FREERESULT($result);
1454
1455         // Return value
1456         return $maxRand;
1457 }
1458
1459 // Load all URLs of the current user and return it as an array
1460 function SURFBAR_GET_USER_URLS () {
1461         // Init array
1462         $URLs = array();
1463
1464         // Begin the query
1465         $result = SQL_QUERY_ESC("SELECT u.id, u.userid, u.url, u.views_total, u.views_max, u.views_allowed, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
1466 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1467 WHERE u.userid=%s AND u.status != 'DELETED'
1468 ORDER BY u.id ASC",
1469         array(getUserId()), __FUNCTION__, __LINE__);
1470
1471         // Are there entries?
1472         if (SQL_NUMROWS($result) > 0) {
1473                 // Load all rows
1474                 while ($row = SQL_FETCHARRAY($result)) {
1475                         // Add the row
1476                         $URLs[$row['id']] = $row;
1477                 } // END - while
1478         } // END - if
1479
1480         // Free result
1481         SQL_FREERESULT($result);
1482
1483         // Return the array
1484         return $URLs;
1485 }
1486
1487 // "Getter" for member action array for given status
1488 function SURFBAR_getModeAction_ARRAY ($status) {
1489         // Init array
1490         $returnArray = array();
1491
1492         // Get all assigned actions
1493         $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1494         array($status), __FUNCTION__, __LINE__);
1495
1496         // Some entries there?
1497         if (SQL_NUMROWS($result) > 0) {
1498                 // Load all actions
1499                 // @TODO This can be somehow rewritten
1500                 while ($content = SQL_FETCHARRAY($result)) {
1501                         $returnArray[] = $content['action'];
1502                 } // END - if
1503         } // END - if
1504
1505         // Free result
1506         SQL_FREERESULT($result);
1507
1508         // Return result
1509         return $returnArray;
1510 }
1511
1512 // Reload to configured stop page
1513 function SURFBAR_RELOAD_TO_STOP_PAGE ($page="stop") {
1514         // Internal or external?
1515         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1516                 // Reload to internal page
1517                 redirectToUrl('surfbar.php?frame=' . $page);
1518         } else {
1519                 // Reload to external page
1520                 redirectToConfiguredUrl('surfbar_pause_url');
1521         }
1522 }
1523
1524 // Determine next id for surfbar or get data for given id, always call this before you call other
1525 // getters below this function!!!
1526 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1527         // Default is no id and no random number
1528         $nextId = 0;
1529         $randNum = 0;
1530
1531         // Is the ID set?
1532         if ($urlId == 0) {
1533                 // Get array with lock ids
1534                 $USE = SURFBAR_GET_LOCK_IDS();
1535
1536                 // Shall we add some URL ids to ignore?
1537                 $add = '';
1538                 if (count($USE) > 0) {
1539                         // Ignore some!
1540                         $add = " AND sbu.id NOT IN (";
1541                         foreach ($USE as $url_id => $lid) {
1542                                 // Add URL id
1543                                 $add .= $url_id.',';
1544                         } // END - foreach
1545
1546                         // Add closing bracket
1547                         $add = substr($add, 0, -1) . ')';
1548                 } // END - if
1549
1550                 // Determine depleted user account
1551                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1552
1553                 // Get maximum randomness factor
1554                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $add);
1555
1556                 // If more than one URL can be called generate the random number!
1557                 if ($maxRand > 1) {
1558                         // Generate random number
1559                         $randNum = mt_rand(0, ($maxRand - 1));
1560                 } // END - if
1561
1562                 // And query the database
1563                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1564                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed, sbu.fixed_reload
1565 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1566 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1567 ON sbu.id=sbs.url_id
1568 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1569 ON sbu.id=l.url_id
1570 WHERE sbu.userid NOT IN (".implode(',', $UIDs['uid']).") AND sbu.`status`='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$add."
1571 GROUP BY sbu.id
1572 ORDER BY l.last_surfed ASC, sbu.id ASC
1573 LIMIT %s,1",
1574                 array($randNum), __FUNCTION__, __LINE__
1575                 );
1576         } else {
1577                 // Get data from specified id number
1578                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed, sbu.fixed_reload
1579 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1580 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1581 ON sbu.id=sbs.url_id
1582 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1583 ON sbu.id=l.url_id
1584 WHERE sbu.userid != %s AND sbu.`status`='ACTIVE' AND sbu.id=%s AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))
1585 LIMIT 1",
1586                 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1587                 );
1588         }
1589
1590         // Is there an id number?
1591         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1592         if (SQL_NUMROWS($result) == 1) {
1593                 // Load/cache data
1594                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['surfbar_cache']).") - BEFORE", false);
1595                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1596                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['surfbar_cache']).") - AFTER", false);
1597
1598                 // Determine waiting time
1599                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1600
1601                 // Is the last salt there?
1602                 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1603                         // Then repair it wit the static!
1604                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1605                         $GLOBALS['surfbar_cache']['last_salt'] = '';
1606                 } // END - if
1607
1608                 // Fix missing last_surfed
1609                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1610                         // Fix it here
1611                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1612                         $GLOBALS['surfbar_cache']['last_surfed'] = 0;
1613                 } // END - if
1614
1615                 // Get base/fixed reward and costs
1616                 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1617                 $GLOBALS['surfbar_cache']['costs']  = SURFBAR_DETERMINE_COSTS();
1618                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1619
1620                 // Only in dynamic model add the dynamic bonus!
1621                 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1622                         // Calculate dynamic reward/costs and add it
1623                         $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1624                         $GLOBALS['surfbar_cache']['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1625                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1626                 } // END - if
1627
1628                 // Now get the id
1629                 $nextId = SURFBAR_GET_ID();
1630         } // END - if
1631
1632         // Free result
1633         SQL_FREERESULT($result);
1634
1635         // Return result
1636         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1637         return $nextId;
1638 }
1639
1640 // -----------------------------------------------------------------------------
1641 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1642 // THE $GLOBALS['surfbar_cache'] ARRAY!
1643 // -----------------------------------------------------------------------------
1644
1645 // Initializes the surfbar
1646 function SURFBAR_INIT () {
1647         // Init cache array
1648         $GLOBALS['surfbar_cache'] = array();
1649 }
1650
1651 // Private getter for data elements
1652 function SURFBAR_GET_DATA ($element) {
1653         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1654
1655         // Default is null
1656         $data = null;
1657
1658         // Is the entry there?
1659         if (isset($GLOBALS['surfbar_cache'][$element])) {
1660                 // Then take it
1661                 $data = $GLOBALS['surfbar_cache'][$element];
1662         } else { // END - if
1663                 print("<pre>");
1664                 print_r($GLOBALS['surfbar_cache']);
1665                 print("</pre>");
1666                 debug_report_bug();
1667         }
1668
1669         // Return result
1670         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1671         return $data;
1672 }
1673
1674 // Getter for reward from cache
1675 function SURFBAR_GET_REWARD () {
1676         // Get data element and return its contents
1677         return SURFBAR_GET_DATA('reward');
1678 }
1679
1680 // Getter for costs from cache
1681 function SURFBAR_GET_COSTS () {
1682         // Get data element and return its contents
1683         return SURFBAR_GET_DATA('costs');
1684 }
1685
1686 // Getter for URL from cache
1687 function SURFBAR_GET_URL () {
1688         // Get data element and return its contents
1689         return SURFBAR_GET_DATA('url');
1690 }
1691
1692 // Getter for salt from cache
1693 function SURFBAR_GET_SALT () {
1694         // Get data element and return its contents
1695         return SURFBAR_GET_DATA('salt');
1696 }
1697
1698 // Getter for id from cache
1699 function SURFBAR_GET_ID () {
1700         // Get data element and return its contents
1701         return SURFBAR_GET_DATA('id');
1702 }
1703
1704 // Getter for userid from cache
1705 function SURFBAR_GET_USERID () {
1706         // Get data element and return its contents
1707         return SURFBAR_GET_DATA('userid');
1708 }
1709
1710 // Getter for user reload locks
1711 function SURFBAR_GET_USER_LOCKS () {
1712         // Get data element and return its contents
1713         return SURFBAR_GET_DATA('user_locks');
1714 }
1715
1716 // Getter for reload time
1717 function SURFBAR_GET_RELOAD_TIME () {
1718         // Get data element and return its contents
1719         return SURFBAR_GET_DATA('time');
1720 }
1721
1722 // Getter for allowed views
1723 function SURFBAR_GET_VIEWS_ALLOWED () {
1724         // Get data element and return its contents
1725         return SURFBAR_GET_DATA('views_allowed');
1726 }
1727
1728 // Getter for fixed reload
1729 function SURFBAR_GET_FIXED_RELOAD () {
1730         // Get data element and return its contents
1731         return SURFBAR_GET_DATA('fixed_reload');
1732 }
1733
1734 // Getter for surf lock
1735 function SURFBAR_GET_SURF_LOCK () {
1736         // Get data element and return its contents
1737         return SURFBAR_GET_DATA('surf_lock');
1738 }
1739
1740 // Getter for new status
1741 function SURFBAR_GET_NEW_STATUS () {
1742         // Get data element and return its contents
1743         return SURFBAR_GET_DATA('new_status');
1744 }
1745
1746 // [EOF]
1747 ?>