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