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