]> git.mxchange.org Git - mailer.git/blob - inc/libs/surfbar_functions.php
More rewrites to make lesser use of getMessage()
[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_NUMROWS($result) > 0) {
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                 'frametester' => generateFrametesterUrl($url),
600                 'url_userid'  => $userid,
601                 'url_status'  => $status,
602         ));
603
604         // Is limit/reload set?
605         if (!isset($config['limit'])) {
606                 $content['limit']  = '0';
607         } // END - if
608         if (!isset($config['reload'])) {
609                 $content['reload'] = '0';
610         } // END - if
611
612         // Insert the URL into database
613         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
614
615         // Is this id valid?
616         if ($content['insert_id'] == '0') {
617                 // INSERT did not insert any data!
618                 return false;
619         } // END - if
620
621         // If in reg-mode we notify admin
622         if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
623                 // Notify admin even when he as unlocked an email
624                 SURFBAR_NOTIFY_ADMIN('url_' . $addMode, $content);
625         } // END - if
626
627         // Send mail to user
628         SURFBAR_NOTIFY_USER('url_' . $addMode, $content);
629
630         // Return the insert id
631         return $content['insert_id'];
632 }
633
634 // Inserts an url by given data array and return the insert id
635 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
636         // Get userid
637         $userid = bigintval($urlData['url_userid']);
638
639         // Is the id set?
640         if (empty($userid)) $userid = '0';
641
642         // Just run the insert query for now
643         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)",
644                 array(
645                         $userid,
646                         $urlData['url'],
647                         $urlData['url_status'],
648                         $urlData['limit'],
649                         $urlData['limit'],
650                         $urlData['reload']
651                 ), __FUNCTION__, __LINE__
652         );
653
654         // Return insert id
655         return SQL_INSERTID();
656 }
657
658 // Notify admin(s) with a selected message and content
659 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
660         // Prepare template name
661         $templateName = sprintf("admin_surfbar_%s", $messageType);
662
663         // Prepare subject
664         $subject = sprintf("{--ADMIN_SURFBAR_NOTIFY_%s_SUBJECT--}",
665                 strtoupper($messageType)
666         );
667
668         // Is the subject line there?
669         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
670                 // Set default subject if following eval() wents wrong
671                 $subject = getMaskedMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT', strtoupper($messageType));
672         } // END - if
673
674         // Translate some data if present
675         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
676
677         // Send the notification out
678         return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
679 }
680
681 // Notify the user about the performed action
682 function SURFBAR_NOTIFY_USER ($messageType, $content) {
683         // Skip notification if userid is zero
684         if ($content['url_userid'] == '0') {
685                 return false;
686         } // END - if
687
688         // Prepare template name
689         $templateName = sprintf("member_surfbar_%s", $messageType);
690
691         // Prepare subject
692         $subject = sprintf("{--MEMBER_SURFBAR_NOTIFY_%s_SUBJECT--}",
693                 strtoupper($messageType)
694         );
695
696         // Is the subject line there?
697         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
698                 // Set default subject if following eval() wents wrong
699                 $subject = '{--MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT--}';
700         } // END - if
701
702         // Translate some data if present
703         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
704
705         // Load template
706         $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
707
708         // Send the email
709         return sendEmail($content['url_userid'], $subject, $mailText);
710 }
711
712 // Translates some data for template usage
713 // @TODO Can't we use our new expression language instead of this ugly code?
714 function SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE ($content) {
715         // Prepare some code
716         if (isset($content['url_registered']))  $content['url_registered']  = generateDateTime($content['url_registered'], 2);
717         if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
718
719         // Return translated content
720         return $content;
721 }
722
723 // Translates the limit
724 function translateSurfbarLimit ($limit) {
725         // Is this zero?
726         if ($limit == '0') {
727                 // Unlimited!
728                 $return = '{--MEMBER_SURFBAR_UNLIMITED_VIEWS--}';
729         } else {
730                 // Translate comma
731                 $return = translateComma($limit);
732         }
733
734         // Return value
735         return $return;
736 }
737
738 // Translate the URL status
739 function translateSurfbarUrlStatus ($status) {
740         // Return result
741         return sprintf("{--SURFBAR_URL_STATUS_%s--}", strtoupper($status));
742 }
743
744 // Determine reward
745 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
746         // Static values are default
747         $reward = getConfig('surfbar_static_reward');
748
749         // Do we have static or dynamic?
750         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
751                 // "Calculate" dynamic reward
752                 if ($onlyMin) {
753                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
754                 } else {
755                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
756                 }
757         } // END - if
758
759         // Return reward
760         return $reward;
761 }
762
763 // Determine costs
764 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
765         // Static costs is default
766         $costs  = getConfig('surfbar_static_costs');
767
768         // Do we have static or dynamic?
769         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
770                 // "Calculate" dynamic costs
771                 if ($onlyMin) {
772                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
773                 } else {
774                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
775                 }
776         } // END - if
777
778         // Return costs
779         return $costs;
780 }
781
782 // "Calculate" dynamic add
783 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
784         // Get min/max values
785         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
786         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
787
788         // "Calculate" dynamic part and return it
789         return mt_rand($min, $max);
790 }
791
792 // Determine right template name
793 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
794         // Default is the frameset
795         $templateName = "surfbar_frameset";
796
797         // Any frame set? ;-)
798         if (isGetRequestParameterSet('frame')) {
799                 // Use the frame as a template name part... ;-)
800                 $templateName = sprintf("surfbar_frame_%s",
801                         getRequestParameter('frame')
802                 );
803         } // END - if
804
805         // Return result
806         return $templateName;
807 }
808
809 // Check if the "reload lock" of the current user is full, call this function
810 // before you call SURFBAR_CHECK_RELOAD_LOCK().
811 function SURFBAR_CHECK_RELOAD_FULL() {
812         // Default is full!
813         $isFull = true;
814
815         // Cache static reload lock
816         $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
817         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
818
819         // Do we have dynamic model?
820         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
821                 // "Calculate" dynamic lock
822                 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
823         } // END - if
824
825         // Ask the database
826         $result = SQL_QUERY_ESC("SELECT
827         COUNT(l.locks_id) AS cnt
828 FROM
829         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
830 INNER JOIN
831         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
832 ON
833         u.url_id=l.locks_url_id
834 WHERE
835         l.locks_userid=%s AND
836         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.locks_last_surfed) AND
837         (
838                 ((UNIX_TIMESTAMP(l.locks_last_surfed) - u.url_fixed_reload) < 0 AND u.url_fixed_reload > 0) OR
839                 u.url_fixed_reload = '0'
840         )
841 LIMIT 1",
842                 array(getMemberId()), __FUNCTION__, __LINE__
843         );
844
845         // Fetch row
846         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
847
848         // Is it null?
849         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
850                 // Then fix it to zero!
851                 $GLOBALS['surfbar_cache']['user_locks'] = '0';
852         } // END - if
853
854         // Free result
855         SQL_FREERESULT($result);
856
857         // Get total URLs
858         $total = SURFBAR_GET_TOTAL_URLS();
859
860         // Do we have some URLs in lock? Admins can always surf on own URLs!
861         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
862         $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
863
864         // Return result
865         return $isFull;
866 }
867
868 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
869 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
870         // Determine depleted user account
871         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
872
873         // If we dont get any user ids back, there are no URLs
874         if (count($userids['url_userid']) == 0) {
875                 // No user ids found, no URLs!
876                 return 0;
877         } // END - if
878
879         // Is the exlude userid set?
880         if ($excludeUserId > 0) {
881                 // Then add it
882                 $userids['url_userid'][$excludeUserId] = $excludeUserId;
883         } // END - if
884
885         // Get amount from database
886         $result = SQL_QUERY_ESC("SELECT
887         COUNT(`url_id`) AS cnt
888 FROM
889         `{?_MYSQL_PREFIX?}_surfbar_urls`
890 WHERE
891         `url_userid` NOT IN (".implode(', ', $userids['url_userid']).") AND
892         `url_status`='%s'
893 LIMIT 1",
894                 array($status), __FUNCTION__, __LINE__
895         );
896
897         // Fetch row
898         list($cnt) = SQL_FETCHROW($result);
899
900         // Free result
901         SQL_FREERESULT($result);
902
903         // Return result
904         return $cnt;
905 }
906
907 // Check wether the user is allowed to book more URLs
908 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
909         // Is this admin and userid is zero or does the user has some URLs left to book?
910         return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
911 }
912
913 // Get total amount of URLs of given status for current user
914 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '', $exclude = '') {
915         // Is the user 0 and user is logged in?
916         if (($userid == '0') && (isMember())) {
917                 // Then use this userid
918                 $userid = getMemberId();
919         } elseif ($userid == '0') {
920                 // Error!
921                 return (getConfig('surfbar_max_order') + 1);
922         }
923
924         // Default is all URLs
925         $add = '';
926
927         // Is the status set?
928         if (is_array($status)) {
929                 // Only URLs with these status
930                 $add = sprintf(" AND `url_status` IN('%s')", implode("','", $status));
931         } elseif (!empty($status)) {
932                 // Only URLs with this status
933                 $add = sprintf(" AND `url_status`='%s'", $status);
934         } elseif (is_array($exclude)) {
935                 // Exclude URLs with these status
936                 $add = sprintf(" AND `url_status` NOT IN('%s')", implode("','", $exclude));
937         } elseif (!empty($exclude)) {
938                 // Exclude URLs with this status
939                 $add = sprintf(" AND `url_status` != '%s'", $exclude);
940         }
941
942         // Get amount from database
943         $cnt = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
944
945         // Return result
946         return $cnt;
947 }
948
949 // Generate a validation code for the given id number
950 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
951         // @TODO Invalid salt should be refused
952         $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
953
954         // Get code length from config
955         $length = getConfig('code_length');
956
957         // Fix length to 10
958         if ($length == '0') $length = 10;
959
960         // Generate a code until the length matches
961         $valCode = '';
962         while (strlen($valCode) != $length) {
963                 // Is the salt set?
964                 if (empty($salt)) {
965                         // Generate random hashed string
966                         $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
967                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
968                 } else {
969                         // Use this as salt!
970                         $GLOBALS['surfbar_cache']['salt'] = $salt;
971                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
972                 }
973
974                 // ... and now the validation code
975                 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
976                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
977         } // END - while
978
979         // Hash it with md5() and salt it with the random string
980         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
981
982         // Finally encrypt it PGP-like and return it
983         $valHashedCode = encodeHashForCookie($hashedCode);
984
985         // Return hashed value
986         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
987         return $valHashedCode;
988 }
989
990 // Check validation code
991 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
992         // Secure id number
993         $urlId = bigintval($urlId);
994
995         // Now generate the code again
996         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
997
998         // Return result of checking hashes and salts
999         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1000         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('salts_last_salt').'+++', false);
1001         return (($code == $check) && ($salt == SURFBAR_GET_DATA('salts_last_salt')));
1002 }
1003
1004 // Lockdown the userid/id combination (reload lock)
1005 function SURFBAR_LOCKDOWN_ID ($urlId) {
1006         //* DEBUG: */ debugOutput('LOCK!');
1007         ///* DEBUG: */ return;
1008         // Just add it to the database
1009         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`, `locks_url_id`) VALUES (%s, %s)",
1010                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1011
1012         // Remove the salt from database
1013         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1014                 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1015 }
1016
1017 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1018 function SURFBAR_PAY_POINTS () {
1019         // Remove it from the URL owner
1020         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1021         if (SURFBAR_GET_USERID() > 0) {
1022                 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1023         } // END - if
1024
1025         // Book it to the user
1026         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1027         addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1028 }
1029
1030 // Updates the statistics of current URL/userid
1031 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1032         // Init add
1033         $add = '';
1034
1035         // Get allowed views
1036         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1037
1038         // Do we have a limit?
1039         if ($allowed > 0) {
1040                 // Then count views_max down!
1041                 $add .= ", `views_max`=`views_max`-1";
1042         } // END - if
1043
1044         // Update URL stats
1045         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1".$add." WHERE `url_id`=%s LIMIT 1",
1046                 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1047
1048         // Update the stats entry
1049         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `stats_count`=`stats_count`+1 WHERE `stats_userid`=%s AND `stats_url_id`=%s LIMIT 1",
1050                 array(
1051                         getMemberId(),
1052                         SURFBAR_GET_ID()
1053                 ), __FUNCTION__, __LINE__);
1054
1055         // Was that update okay?
1056         if (SQL_AFFECTEDROWS() < 1) {
1057                 // No, then insert entry
1058                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`, `stats_url_id`, `stats_count`) VALUES (%s,%s,1)",
1059                         array(
1060                                 getMemberId(),
1061                                 SURFBAR_GET_ID()
1062                         ), __FUNCTION__, __LINE__);
1063         } // END - if
1064
1065         // Update total/daily/weekly/monthly counter
1066         incrementConfigEntry('surfbar_total_counter');
1067         incrementConfigEntry('surfbar_daily_counter');
1068         incrementConfigEntry('surfbar_weekly_counter');
1069         incrementConfigEntry('surfbar_monthly_counter');
1070
1071         // Update config as well
1072         updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1073 }
1074
1075 // Update the salt for validation and statistics
1076 function SURFBAR_UPDATE_SALT_STATS () {
1077         // Update statistics record
1078         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1079
1080         // Simply store the salt from cache away in database...
1081         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1082                 array(
1083                         SURFBAR_GET_SALT(),
1084                         SURFBAR_GET_ID(),
1085                         getMemberId()
1086                 ), __FUNCTION__, __LINE__);
1087
1088         // Debug message
1089         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1090
1091         // Was that okay?
1092         if (SQL_AFFECTEDROWS() < 1) {
1093                 // Insert missing entry!
1094                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`, `salts_userid`, `salts_last_salt`) VALUES (%s, %s, '%s')",
1095                         array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1096         } // END - if
1097
1098         // Debug message
1099         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1100
1101         // Return if the update was okay
1102         return (SQL_AFFECTEDROWS() == 1);
1103 }
1104
1105 // Check if the reload lock is active for given id
1106 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1107         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1108         // Ask the database
1109         $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1110 FROM
1111         `{?_MYSQL_PREFIX?}_surfbar_locks`
1112 WHERE
1113         `locks_userid`=%s AND
1114         `locks_url_id`=%s AND
1115         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1116 ORDER BY
1117         `locks_last_surfed` ASC
1118 LIMIT 1",
1119                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1120         );
1121
1122         // Fetch counter
1123         list($cnt) = SQL_FETCHROW($result);
1124
1125         // Free result
1126         SQL_FREERESULT($result);
1127
1128         // Return check
1129         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1130         return ($cnt == 1);
1131 }
1132
1133 // Determine which user hash no more points left
1134 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1135         // Init array
1136         $userids = array(
1137                 'url_userid'   => array(),
1138                 'points'       => array(),
1139                 'notified'     => array(),
1140         );
1141
1142         // Do we have a current user id?
1143         if ((isMember()) && ($limit == '0')) {
1144                 // Then add this as well
1145                 $userids['url_userid'][getMemberId()]      = getMemberId();
1146                 $userids['points'][getMemberId()]   = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1147                 $userids['notified'][getMemberId()] = '0';
1148
1149                 // Get all userid except logged in one
1150                 $result = SQL_QUERY_ESC("SELECT
1151         u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1152 FROM
1153         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1154 INNER JOIN
1155         `{?_MYSQL_PREFIX?}_user_data` AS d
1156 ON
1157         u.url_userid=d.userid
1158 WHERE
1159         u.url_userid NOT IN (%s,0) AND u.url_status='ACTIVE'
1160 GROUP BY
1161         u.url_userid
1162 ORDER BY
1163         u.url_userid ASC",
1164                         array(getMemberId()), __FUNCTION__, __LINE__);
1165         } else {
1166                 // Get all userid
1167                 $result = SQL_QUERY("SELECT
1168         u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1169 FROM
1170         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1171 INNER JOIN
1172         `{?_MYSQL_PREFIX?}_user_data` AS d
1173 ON
1174         u.url_userid=d.userid
1175 WHERE
1176         u.url_status='ACTIVE'
1177 GROUP BY
1178         u.url_userid
1179 ORDER BY
1180         u.url_userid ASC", __FUNCTION__, __LINE__);
1181         }
1182
1183         // Load all userid
1184         while ($content = SQL_FETCHARRAY($result)) {
1185                 // Get total points
1186                 $points = countSumTotalData($content['url_userid'], 'user_points', 'points') - countSumTotalData($content['url_userid'], 'user_data', 'used_points');
1187                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['url_userid']},points={$points}", false);
1188
1189                 // Shall we add this to ignore?
1190                 if ($points <= $limit) {
1191                         // Ignore this one!
1192                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['url_userid']} has depleted points amount!", false);
1193                         $userids['url_userid'][$content['url_userid']]      = $content['url_userid'];
1194                         $userids['points'][$content['url_userid']]   = $points;
1195                         $userids['notified'][$content['url_userid']] = $content['notified'];
1196                 } // END - if
1197         } // END - while
1198
1199         // Free result
1200         SQL_FREERESULT($result);
1201
1202         // Debug message
1203         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1204
1205         // Return result
1206         return $userids;
1207 }
1208
1209 // Determine how many users are Online in surfbar
1210 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1211         // Count all users in surfbar modue and return the value
1212         $result = SQL_QUERY("SELECT
1213         `stats_id`
1214 FROM
1215         `{?_MYSQL_PREFIX?}_surfbar_stats`
1216 WHERE
1217         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1218 GROUP BY
1219         `stats_userid` ASC", __FUNCTION__, __LINE__);
1220
1221         // Fetch count
1222         $cnt = SQL_NUMROWS($result);
1223
1224         // Free result
1225         SQL_FREERESULT($result);
1226
1227         // Return result
1228         return $cnt;
1229 }
1230
1231 // Determine waiting time for one URL
1232 function SURFBAR_DETERMINE_WAIT_TIME () {
1233         // Get fixed reload lock
1234         $fixed = SURFBAR_GET_FIXED_RELOAD();
1235
1236         // Is the fixed reload time set?
1237         if ($fixed > 0) {
1238                 // Return it
1239                 return $fixed;
1240         } // END - if
1241
1242         // Static time is default
1243         $time = getConfig('surfbar_static_time');
1244
1245         // Which payment model do we have?
1246         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1247                 // "Calculate" dynamic time
1248                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1249         } // END - if
1250
1251         // Return value
1252         return $time;
1253 }
1254
1255 // Changes the status of an URL from given to other
1256 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1257         // Make new status always lower-case
1258         $newStatus = strtolower($newStatus);
1259
1260         // Get URL data for status comparison if missing
1261         if ((!is_array($data)) || (count($data) == 0)) {
1262                 // Fetch missing URL data
1263                 $data = SURFBAR_GET_URL_DATA($urlId);
1264         } // END - if
1265
1266         // Is the new status set?
1267         if ((!is_string($newStatus)) || (empty($newStatus))) {
1268                 // Abort here, but fine!
1269                 return true;
1270         } // END - if
1271
1272         // Is the status like prevStatus is saying?
1273         if ($data[$urlId]['url_status'] != $prevStatus) {
1274                 // No, then abort here
1275                 return false;
1276         } // END - if
1277
1278
1279         // Update the status now
1280         // ---------- Comment out for debugging/developing member actions! ---------
1281         //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `url_id`=%s LIMIT 1",
1282         //      array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1283         // ---------- Comment out for debugging/developing member actions! ---------
1284
1285         // Was that fine?
1286         // ---------- Comment out for debugging/developing member actions! ---------
1287         //if (SQL_AFFECTEDROWS() != 1) {
1288         //      // No, something went wrong
1289         //      return false;
1290         //} // END - if
1291         // ---------- Comment out for debugging/developing member actions! ---------
1292
1293         // Prepare content for notification routines
1294         $data[$urlId]['url_userid']  = $data[$urlId]['url_userid'];
1295         $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1296         $data[$urlId]['reward']      = translateComma(getConfig('surfbar_static_reward'));
1297         $data[$urlId]['costs']       = translateComma(getConfig('surfbar_static_costs'));
1298
1299         // Do some dirty fixing here:
1300         if (($data[$urlId]['url_status'] == 'STOPPED') && ($newStatus == 'pending')) {
1301                 // Fix for template change
1302                 $newStatus = 'continued';
1303         } // END - if
1304
1305         // Send admin notification
1306         SURFBAR_NOTIFY_ADMIN('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1307
1308         // Send user notification
1309         SURFBAR_NOTIFY_USER('url_' . $data[$urlId]['url_status'] . '_' . $newStatus, $data[$urlId]);
1310
1311         // All done!
1312         return true;
1313 }
1314
1315 // Calculate minimum value for dynamic payment model
1316 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1317         // Addon is zero by default
1318         $addon = '0';
1319
1320         // Percentage part
1321         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1322
1323         // Get total users
1324         $totalUsers = getTotalConfirmedUser();
1325
1326         // Get online users
1327         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1328
1329         // Calculate addon
1330         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1331
1332         // Get total URLs
1333         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1334
1335         // Get user's total URLs
1336         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1337
1338         // Calculate addon
1339         if ($totalUrls > 0) {
1340                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1341         } else {
1342                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1343         }
1344
1345         // Return addon
1346         return $addon;
1347 }
1348
1349 // Calculate maximum value for dynamic payment model
1350 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1351         // Addon is zero by default
1352         $addon = '0';
1353
1354         // Maximum value
1355         $max = log(2);
1356
1357         // Percentage part
1358         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1359
1360         // Get total users
1361         $totalUsers = getTotalConfirmedUser();
1362
1363         // Calculate addon
1364         $addon += abs($max * $percent * $totalUsers);
1365
1366         // Get total URLs
1367         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1368
1369         // Calculate addon
1370         $addon += abs($max * $percent * $totalUrls);
1371
1372         // Return addon
1373         return $addon;
1374 }
1375
1376 // Calculate dynamic lock
1377 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1378         // Default lock is 30 seconds
1379         $addon = 30;
1380
1381         // Get online users
1382         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1383
1384         // Calculate lock
1385         $addon = abs(log($onlineUsers / $addon + 1));
1386
1387         // Return value
1388         return $addon;
1389 }
1390
1391 // "Getter" for lock ids array
1392 function SURFBAR_GET_LOCK_IDS () {
1393         // Prepare some arrays
1394         $IDs = array();
1395         $USE = array();
1396         $ignored = array();
1397
1398         // Get all id from locks within the timestamp
1399         $result = SQL_QUERY_ESC("SELECT `locks_id`, `locks_url_id`, UNIX_TIMESTAMP(`locks_last_surfed`) AS last_surfed
1400 FROM
1401         `{?_MYSQL_PREFIX?}_surfbar_locks`
1402 WHERE
1403         `locks_userid`=%s
1404 ORDER BY
1405         `locks_id` ASC", array(getMemberId()),
1406         __FUNCTION__, __LINE__);
1407
1408         // Load all entries
1409         while ($content = SQL_FETCHARRAY($result)) {
1410                 // Debug message
1411                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1412
1413                 // Skip entries that are too old
1414                 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1415                         // Debug message
1416                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1417
1418                         // Add only if missing or bigger
1419                         if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1420                                 // Debug message
1421                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1422
1423                                 // Add this id
1424                                 $IDs[$content['url_id']] = $content['last_surfed'];
1425                                 $USE[$content['url_id']] = $content['id'];
1426                         } // END - if
1427                 } else {
1428                         // Debug message
1429                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1430
1431                         // Ignore these old entries!
1432                         $ignored[] = $content['url_id'];
1433                         unset($IDs[$content['url_id']]);
1434                         unset($USE[$content['url_id']]);
1435                 }
1436         } // END - while
1437
1438         // Free result
1439         SQL_FREERESULT($result);
1440
1441         // Return array
1442         return $USE;
1443 }
1444
1445 // "Getter" for maximum random number
1446 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1447         // Count max availabe entries
1448         $result = SQL_QUERY("SELECT
1449         sbu.url_id AS cnt
1450 FROM
1451         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1452 LEFT JOIN
1453         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1454 ON
1455         sbu.url_id=sbs.salts_url_id
1456 LEFT JOIN
1457         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1458 ON
1459         sbu.url_id=l.locks_url_id
1460 WHERE
1461         sbu.url_userid NOT IN (".implode(',', $userids).") AND
1462         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1463         sbu.url_status='ACTIVE'
1464         ".$add."
1465 GROUP BY
1466         sbu.url_id ASC", __FUNCTION__, __LINE__);
1467
1468         // Log last query
1469         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1470
1471         // Fetch max rand
1472         $maxRand = SQL_NUMROWS($result);
1473
1474         // Free result
1475         SQL_FREERESULT($result);
1476
1477         // Return value
1478         return $maxRand;
1479 }
1480
1481 // Load all URLs of the current user and return it as an array
1482 function SURFBAR_GET_USER_URLS () {
1483         // Init array
1484         $urlArray = array();
1485
1486         // Begin the query
1487         $result = SQL_QUERY_ESC("SELECT
1488         u.url_id,
1489         u.url_userid,
1490         u.url,
1491         u.url_status,
1492         u.url_views_total,
1493         u.url_views_max,
1494         u.url_views_allowed,
1495         UNIX_TIMESTAMP(u.url_registered) AS `url_registered`,
1496         UNIX_TIMESTAMP(u.url_last_locked) AS `url_last_locked`,
1497         u.url_lock_reason
1498 FROM
1499         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1500 WHERE
1501         u.url_userid=%s AND
1502         u.url_status != 'DELETED'
1503 ORDER BY
1504         u.url_id ASC",
1505         array(getMemberId()), __FUNCTION__, __LINE__);
1506
1507         // Are there entries?
1508         if (SQL_NUMROWS($result) > 0) {
1509                 // Load all rows
1510                 while ($row = SQL_FETCHARRAY($result)) {
1511                         // Add the row
1512                         $urlArray[$row['id']] = $row;
1513                 } // END - while
1514         } // END - if
1515
1516         // Free result
1517         SQL_FREERESULT($result);
1518
1519         // Return the array
1520         return $urlArray;
1521 }
1522
1523 // "Getter" for member action array for given status
1524 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1525         // Init array
1526         $returnArray = array();
1527
1528         // Get all assigned actions
1529         $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1530                 array($status), __FUNCTION__, __LINE__);
1531
1532         // Some entries there?
1533         if (SQL_NUMROWS($result) > 0) {
1534                 // Load all actions
1535                 // @TODO This can be somehow rewritten
1536                 while ($content = SQL_FETCHARRAY($result)) {
1537                         $returnArray[] = $content['action'];
1538                 } // END - if
1539         } // END - if
1540
1541         // Free result
1542         SQL_FREERESULT($result);
1543
1544         // Return result
1545         return $returnArray;
1546 }
1547
1548 // Reload to configured stop page
1549 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1550         // Internal or external?
1551         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1552                 // Reload to internal page
1553                 redirectToUrl('surfbar.php?frame=' . $page);
1554         } else {
1555                 // Reload to external page
1556                 redirectToConfiguredUrl('surfbar_pause_url');
1557         }
1558 }
1559
1560 // Determine next id for surfbar or get data for given id, always call this before you call other
1561 // getters below this function!!!
1562 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1563         // Default is no id and no random number
1564         $nextId = '0';
1565         $randNum = '0';
1566
1567         // Is the id set?
1568         if ($urlId == '0') {
1569                 // Get array with lock ids
1570                 $USE = SURFBAR_GET_LOCK_IDS();
1571
1572                 // Shall we add some URL ids to ignore?
1573                 $add = '';
1574                 if (count($USE) > 0) {
1575                         // Ignore some!
1576                         $add = " AND sbu.url_id NOT IN (";
1577                         foreach ($USE as $url_id => $lid) {
1578                                 // Add URL id
1579                                 $add .= $url_id.',';
1580                         } // END - foreach
1581
1582                         // Add closing bracket
1583                         $add = substr($add, 0, -1) . ')';
1584                 } // END - if
1585
1586                 // Determine depleted user account
1587                 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1588
1589                 // Get maximum randomness factor
1590                 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['url_userid'], $add);
1591
1592                 // If more than one URL can be called generate the random number!
1593                 if ($maxRand > 1) {
1594                         // Generate random number
1595                         $randNum = mt_rand(0, ($maxRand - 1));
1596                 } // END - if
1597
1598                 // And query the database
1599                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1600                 $result = SQL_QUERY_ESC("SELECT
1601         sbu.url_id,
1602         sbu.url_userid,
1603         sbu.url,
1604         sbs.salts_last_salt,
1605         sbu.url_views_total,
1606         sbu.url_views_max,
1607         sbu.url_views_allowed,
1608         UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1609         sbu.url_fixed_reload
1610 FROM
1611         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1612 LEFT JOIN
1613         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1614 ON
1615         sbu.url_id=sbs.salts_url_id
1616 LEFT JOIN
1617         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1618 ON
1619         sbu.url_id=l.locks_url_id
1620 WHERE
1621         sbu.url_userid NOT IN (".implode(',', $userids['url_userid']).") AND
1622         sbu.url_status='ACTIVE' AND
1623         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1624         ".$add."
1625 GROUP BY
1626         sbu.url_id
1627 ORDER BY
1628         l.locks_last_surfed ASC,
1629         sbu.url_id ASC
1630 LIMIT %s,1",
1631                         array($randNum), __FUNCTION__, __LINE__
1632                 );
1633         } else {
1634                 // Get data from specified id number
1635                 $result = SQL_QUERY_ESC("SELECT
1636         sbu.url_id,
1637         sbu.url_userid,
1638         sbu.url,
1639         sbs.salts_last_salt,
1640         sbu.url_views_total,
1641         sbu.url_views_max,
1642         sbu.url_views_allowed,
1643         UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1644         sbu.url_fixed_reload
1645 FROM
1646         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1647 LEFT JOIN
1648         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1649 ON
1650         sbu.url_id=sbs.salts_url_id
1651 LEFT JOIN
1652         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1653 ON
1654         sbu.url_id=l.locks_url_id
1655 WHERE
1656         sbu.url_userid != %s AND
1657         sbu.url_status='ACTIVE' AND
1658         sbu.url_id=%s AND
1659         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1660 LIMIT 1",
1661                         array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1662                 );
1663         }
1664
1665         // Is there an id number?
1666         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1667         if (SQL_NUMROWS($result) == 1) {
1668                 // Load/cache data
1669                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1670                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1671                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1672
1673                 // Determine waiting time
1674                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1675
1676                 // Is the last salt there?
1677                 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1678                         // Then repair it wit the static!
1679                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1680                         $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1681                 } // END - if
1682
1683                 // Fix missing last_surfed
1684                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1685                         // Fix it here
1686                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1687                         $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1688                 } // END - if
1689
1690                 // Get base/fixed reward and costs
1691                 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1692                 $GLOBALS['surfbar_cache']['costs']  = SURFBAR_DETERMINE_COSTS();
1693                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1694
1695                 // Only in dynamic model add the dynamic bonus!
1696                 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1697                         // Calculate dynamic reward/costs and add it
1698                         $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1699                         $GLOBALS['surfbar_cache']['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1700                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1701                 } // END - if
1702
1703                 // Now get the id
1704                 $nextId = SURFBAR_GET_ID();
1705         } // END - if
1706
1707         // Free result
1708         SQL_FREERESULT($result);
1709
1710         // Return result
1711         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1712         return $nextId;
1713 }
1714
1715 // -----------------------------------------------------------------------------
1716 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1717 // THE $GLOBALS['surfbar_cache'] ARRAY!
1718 // -----------------------------------------------------------------------------
1719
1720 // Initializes the surfbar
1721 function SURFBAR_INIT () {
1722         // Init cache array
1723         $GLOBALS['surfbar_cache'] = array();
1724 }
1725
1726 // Private getter for data elements
1727 function SURFBAR_GET_DATA ($element) {
1728         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1729
1730         // Default is null
1731         $data = null;
1732
1733         // Is the entry there?
1734         if (isset($GLOBALS['surfbar_cache'][$element])) {
1735                 // Then take it
1736                 $data = $GLOBALS['surfbar_cache'][$element];
1737         } else { // END - if
1738                 print('<pre>');
1739                 print_r($GLOBALS['surfbar_cache']);
1740                 print('</pre>');
1741                 debug_report_bug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
1742         }
1743
1744         // Return result
1745         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data, false);
1746         return $data;
1747 }
1748
1749 // Getter for reward from cache
1750 function SURFBAR_GET_REWARD () {
1751         // Get data element and return its contents
1752         return SURFBAR_GET_DATA('reward');
1753 }
1754
1755 // Getter for costs from cache
1756 function SURFBAR_GET_COSTS () {
1757         // Get data element and return its contents
1758         return SURFBAR_GET_DATA('costs');
1759 }
1760
1761 // Getter for URL from cache
1762 function SURFBAR_GET_URL () {
1763         // Get data element and return its contents
1764         return SURFBAR_GET_DATA('url');
1765 }
1766
1767 // Getter for salt from cache
1768 function SURFBAR_GET_SALT () {
1769         // Get data element and return its contents
1770         return SURFBAR_GET_DATA('salt');
1771 }
1772
1773 // Getter for id from cache
1774 function SURFBAR_GET_ID () {
1775         // Get data element and return its contents
1776         return SURFBAR_GET_DATA('url_id');
1777 }
1778
1779 // Getter for userid from cache
1780 function SURFBAR_GET_USERID () {
1781         // Get data element and return its contents
1782         return SURFBAR_GET_DATA('url_userid');
1783 }
1784
1785 // Getter for user reload locks
1786 function SURFBAR_GET_USER_LOCKS () {
1787         // Get data element and return its contents
1788         return SURFBAR_GET_DATA('user_locks');
1789 }
1790
1791 // Getter for reload time
1792 function SURFBAR_GET_RELOAD_TIME () {
1793         // Get data element and return its contents
1794         return SURFBAR_GET_DATA('time');
1795 }
1796
1797 // Getter for allowed views
1798 function SURFBAR_GET_VIEWS_ALLOWED () {
1799         // Get data element and return its contents
1800         return SURFBAR_GET_DATA('url_views_allowed');
1801 }
1802
1803 // Getter for maximum views
1804 function SURFBAR_GET_VIEWS_MAX () {
1805         // Get data element and return its contents
1806         return SURFBAR_GET_DATA('url_views_max');
1807 }
1808
1809 // Getter for fixed reload
1810 function SURFBAR_GET_FIXED_RELOAD () {
1811         // Get data element and return its contents
1812         return SURFBAR_GET_DATA('url_fixed_reload');
1813 }
1814
1815 // Getter for surf lock
1816 function SURFBAR_GET_SURF_LOCK () {
1817         // Get data element and return its contents
1818         return SURFBAR_GET_DATA('surf_lock');
1819 }
1820
1821 // Getter for new status
1822 function SURFBAR_GET_NEW_STATUS () {
1823         // Get data element and return its contents
1824         return SURFBAR_GET_DATA('new_status');
1825 }
1826
1827 // [EOF]
1828 ?>