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