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