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