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