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