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