Surfbar continued and some rewrites/fixes:
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // -----------------------------------------------------------------------------
41 //                               Admin functions
42 // -----------------------------------------------------------------------------
43 //
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url, $limit) {
46         // Do some pre-checks
47         if (!IS_ADMIN()) {
48                 // Not an admin
49                 return false;
50         } elseif (!VALIDATE_URL($url)) {
51                 // URL invalid
52                 return false;
53         } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54                 // URL already found in surfbar!
55                 return false;
56         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
57                 // No more allowed!
58                 return false;
59         } elseif ("".($limit + 0)."" != "".$limit."") {
60                 // Invalid amount entered
61                 return false;
62         }
63
64         // Register the new URL
65         return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", $limit);
66 }
67 // Admin unlocked an email so we can migrate the URL
68 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
69         // Do some pre-checks
70         if (!IS_ADMIN()) {
71                 // Not an admin
72                 return false;
73         } elseif (!VALIDATE_URL($url)) {
74                 // URL invalid
75                 return false;
76         } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
77                 // URL already found in surfbar!
78                 return false;
79         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
80                 // No more allowed!
81                 return false;
82         }
83
84         // Register the new URL
85         return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
86 }
87 // Admin function for unlocking URLs
88 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
89         // Is this an admin or invalid array?
90         if (!IS_ADMIN()) {
91                 // Not admin or invalid IDs array
92                 return false;
93         } elseif (!is_array($IDs)) {
94                 // No array
95                 return false;
96         } elseif (count($IDs) == 0) {
97                 // Empty array
98                 return false;
99         }
100
101         // Set to true to make AND expression valid if first URL got unlocked
102         $done = true;
103
104         // Update the status for all ids
105         foreach ($IDs as $id => $dummy) {
106                 // Test all ids through (ignores failed)
107                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
108         } // END - if
109
110         // Return total status
111         return $done;
112 }
113 // Admin function for rejecting URLs
114 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
115         // Is this an admin or invalid array?
116         if (!IS_ADMIN()) {
117                 // Not admin or invalid IDs array
118                 return false;
119         } elseif (!is_array($IDs)) {
120                 // No array
121                 return false;
122         } elseif (count($IDs) == 0) {
123                 // Empty array
124                 return false;
125         }
126
127         // Set to true to make AND expression valid if first URL got unlocked
128         $done = true;
129
130         // Update the status for all ids
131         foreach ($IDs as $id => $dummy) {
132                 // Test all ids through (ignores failed)
133                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
134         } // END - if
135
136         // Return total status
137         return $done;
138 }
139 //
140 // -----------------------------------------------------------------------------
141 //                               Member functions
142 // -----------------------------------------------------------------------------
143 //
144 // Member has added an URL
145 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
146         global $_CONFIG;
147
148         // Do some pre-checks
149         if (!IS_MEMBER()) {
150                 // Not a member
151                 return false;
152         } elseif (!VALIDATE_URL($url)) {
153                 // URL invalid
154                 return false;
155         } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
156                 // URL already found in surfbar!
157                 return false;
158         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
159                 // No more allowed!
160                 return false;
161         } elseif ("".($limit + 0)."" != "".$limit."") {
162                 // Invalid amount entered
163                 return false;
164         }
165
166         // Register the new URL
167         return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", $limit);
168 }
169 // Create list of actions depending on status for the user
170 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
171         // Load all actions in an array for given status
172         $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
173
174         // Init HTML code
175         $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
176 <tr>\n";
177
178         // Calculate width
179         $width = round(100 / count($actionArray));
180
181         // "Walk" through all actions and create forms
182         foreach ($actionArray as $actionId=>$action) {
183                 // Add form for this action
184                 $OUT .= sprintf("       <td align=\"center\" width=\"%d%%\">
185                 <form action=\"".URL."/modules.php?module=login&amp;what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
186                         <input type=\"hidden\" name=\"id\" value=\"%s\" />
187                         <input type=\"hidden\" name=\"action\" value=\"%s\" />
188                         <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
189                 </form>
190         </td>\n",
191                         $width,
192                         bigintval($urlId),
193                         strtolower($action),
194                         strtoupper($action),
195                         strtoupper($action)
196                 );
197         } // END - foreach
198
199         // Close table
200         $OUT .= "</tr>
201 </table>\n";
202
203         // Return code
204         return $OUT;
205 }
206 // Do the member form request
207 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
208         global $SURFBAR_CACHE;
209
210         // By default no action is performed
211         $performed = false;
212
213         // Is this a member?
214         if (!IS_MEMBER()) {
215                 // No member!
216                 return false;
217         } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
218                 // Important form elements are missing!
219                 return false;
220         } elseif (!isset($URLs[$formData['id']])) {
221                 // ID not found in cache
222                 return false;
223         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
224                 // Action not allowed for current URL status
225                 return false;
226         }
227
228         // Create the function name for selected action
229         $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper(SQL_ESCAPE($formData['action'])));
230
231         // Is the function there?
232         if (function_exists($functionName)) {
233                 // Add new status
234                 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
235
236                 // Extract URL data for call-back
237                 $urlData = array($URLs[$formData['id']]);
238
239                 // Action found so execute it
240                 $performed = call_user_func_array($functionName, $urlData);
241         } else {
242                 // Log invalid request
243                 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
244                 ADD_FATAL(sprintf("Invalid member action! action=%s,id=%s,function=%s", $formData['action'], $formData['id'], $functionName));
245         }
246
247         // Return status
248         return $performed;
249 }
250 // Validate if the requested action can be performed on current URL status
251 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
252         global $SURFBAR_CACHE;
253
254         // Search for the requested action/status combination in database
255         $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
256                 array($action, $status), __FILE__, __LINE__);
257
258         // Is the entry there?
259         $isValid = (SQL_NUMROWS($result) == 1);
260
261         // Fetch the new status if found
262         if ($isValid) {
263                 // Load new status
264                 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
265         } // END - if
266
267         // Free result
268         SQL_FREERESULT($result);
269
270         // Return status
271         return $isValid;
272 }
273 //
274 // -----------------------------------------------------------------------------
275 //                               Member actions
276 // -----------------------------------------------------------------------------
277 //
278 // Retreat a booked URL
279 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
280         // Create the data array for next function call
281         $data = array(
282                 $urlData['id'] => $urlData
283         );
284
285         // Simply change the status here
286         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
287 }
288 // Book an URL now (from migration)
289 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
290         // Create the data array for next function call
291         $data = array(
292                 $urlData['id'] => $urlData
293         );
294
295         // Simply change the status here
296         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
297 }
298 // Show edit form or do the changes
299 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
300         // Is the "execute" flag there?
301         if (isset($urlData['execute'])) {
302                 // Execute the changes
303                 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
304         } // END - if
305
306         // Display form
307         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
308 }
309 // Show delete form or do the changes
310 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
311         // Is the "execute" flag there?
312         if (isset($urlData['execute'])) {
313                 // Execute the changes
314                 return SURFBAR_MEMBER_EXECUTE_ACTION("del", $urlData);
315         } // END - if
316
317         // Display form
318         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("del", $urlData);
319 }
320 // Display selected "action form"
321 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
322         // Translate some data
323         $urlData['registered']    = MAKE_DATETIME($urlData['registered'], "2");
324         $urlData['views_total']   = TRANSLATE_COMMA($urlData['views_total']);
325         $urlData['views_max']     = TRANSLATE_COMMA($urlData['views_max']);
326         $urlData['views_allowed'] = TRANSLATE_COMMA($urlData['views_allowed']);
327         $urlData['last_locked']   = MAKE_DATETIME($urlData['last_locked'], "2");
328
329         // Is the lock reason empty?
330         if (empty($urlData['lock_reason'])) {
331                 // Fix it to three dashes
332                 $urlData['lock_reason'] = "---";
333         } // END - if
334
335         // Default is not limited
336         $urlData['limited_yes'] = "";
337         $urlData['limited_no']  = " checked=\"checked\"";
338         $urlData['limited']     = "false";
339
340         // Is this URL limited?
341         if ($urlData['views_max'] > 0) {
342                 // Then rewrite form data
343                 $urlData['limited_yes'] = " checked=\"checked\"";
344                 $urlData['limited_no']  = "";
345                 $urlData['limited']     = "true";
346         } // END - if
347
348         // Load the form and display it
349         LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
350
351         // All fine by default ... ;-)
352         return true;
353 }
354 //
355 // -----------------------------------------------------------------------------
356 //                           Self-maintenance functions
357 // -----------------------------------------------------------------------------
358 //
359 // Main function
360 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
361         // Handle URLs which limit has depleted so we can stop them
362         SURFBAR_HANDLE_DEPLETED_VIEWS();
363
364         // Handle low-points amounts
365         SURFBAR_HANDLE_LOW_POINTS();
366 }
367 // Handle URLs which limit has depleted
368 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
369         // Get all URLs
370         $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND status='ACTIVE'");
371
372         // Do we have some entries?
373         if (count($urlArray) > 0) {
374                 // Then handle all!
375                 foreach ($urlArray as $id => $urlData) {
376                         // Backup data
377                         $data = $urlData;
378
379                         // Rewrite array for next call
380                         $urlData[$id] = $data;
381
382                         // Handle the status
383                         SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
384                 } // END - foreach
385         } // END - if
386 }
387 // Alert users which have URLs booked and are low on points amount
388 function SURFBAR_HANDLE_LOW_POINTS () {
389         global $_CONFIG;
390
391         // Get all userids
392         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS($_CONFIG['surfbar_warn_low_points']);
393
394         // "Walk" through all URLs
395         foreach ($UIDs['uid'] as $uid => $dummy) {
396                 // Is the last notification far enougth away to notify again?
397                 if ((time() - $UIDs['notified'][$uid]) >= $_CONFIG['surfbar_low_interval']) {
398                         // Prepare content
399                         $content = array(
400                                 'uid'      => $uid,
401                                 'low'      => TRANSLATE_COMMA($_CONFIG['surfbar_warn_low_points']),
402                                 'points'   => TRANSLATE_COMMA($UIDs['points'][$uid]),
403                                 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
404                                 'interval' => CREATE_FANCY_TIME($_CONFIG['surfbar_low_interval'])
405                         );
406
407                         // Notify this user
408                         SURFBAR_NOTIFY_USER("low_points", $content);
409
410                         // Update last notified
411                         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
412                                 array($uid), __FILE__, __LINE__);
413                 } // END - if
414         } // END - foreach
415 }
416 //
417 // -----------------------------------------------------------------------------
418 //                               Generic functions
419 // -----------------------------------------------------------------------------
420 //
421 // Looks up by an URL
422 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
423         // Now lookup that given URL by itself
424         $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
425
426         // Was it found?
427         return (count($urlArray) > 0);
428 }
429 // Load URL data by given search term and column
430 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
431         global $lastUrlData;
432
433         // By default nothing is found
434         $lastUrlData = array();
435
436         // Is the column an id number?
437         if (($column == "id") || ($column == "userid")) {
438                 // Extra secure input
439                 $searchTerm = bigintval($searchTerm);
440         } // END - if
441
442         // If the column is "id" there can be only one entry
443         $limit = "";
444         if ($column == "id") {
445                 $limit = "LIMIT 1";
446         } // END - if
447
448         // Look up the record
449         $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed
450 FROM "._MYSQL_PREFIX."_surfbar_urls
451 WHERE %s='%s'".$add."
452 ORDER BY %s %s
453 %s",
454                 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
455
456         // Is there at least one record?
457         if (SQL_NUMROWS($result) > 0) {
458                 // Then load all!
459                 while ($dataRow = SQL_FETCHARRAY($result)) {
460                         // Shall we group these results?
461                         if ($group == "id") {
462                                 // Add the row by id as index
463                                 $lastUrlData[$dataRow['id']] = $dataRow;
464                         } else {
465                                 // Group entries
466                                 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
467                         }
468                 } // END - while
469         } // END - if
470
471         // Free the result
472         SQL_FREERESULT($result);
473
474         // Return the result
475         return $lastUrlData;
476 }
477 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
478 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $limit=0) {
479         global $_CONFIG;
480
481         // Make sure by the user registered URLs are always pending
482         if ($addMode == "reg") $status = "PENDING";
483
484         // Prepare content
485         $content = array(
486                 'url'         => $url,
487                 'frametester' => FRAMETESTER($url),
488                 'uid'         => $uid,
489                 'status'      => $status,
490                 'limit'       => $limit
491         );
492
493         // Insert the URL into database
494         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
495
496         // Is this ID valid?
497         if ($content['insert_id'] == 0) {
498                 // INSERT did not insert any data!
499                 return false;
500         } // END - if
501
502         // Translate status and limit
503         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
504         $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
505
506         // If in reg-mode we notify admin
507         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
508                 // Notify admin even when he as unlocked an email
509                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
510         } // END - if
511
512         // Send mail to user
513         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
514
515         // Return the insert id
516         return $content['insert_id'];
517 }
518 // Inserts an url by given data array and return the insert id
519 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
520         // Get userid
521         $uid = bigintval($urlData['uid']);
522
523         // Is the id set?
524         if (empty($uid)) $uid = 0;
525
526         // Just run the insert query for now
527         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid,url,status,views_max,views_allowed) VALUES (%s,'%s','%s',%s,%s)",
528                 array(
529                         $uid,
530                         $urlData['url'],
531                         $urlData['status'],
532                         $urlData['limit'],
533                         $urlData['limit']
534                 ), __FILE__, __LINE__
535         );
536
537         // Return insert id
538         return SQL_INSERTID();
539 }
540 // Notify admin(s) with a selected message and content
541 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
542         // Prepare template name
543         $templateName = sprintf("admin_surfbar_%s", $messageType);
544
545         // Set default subject if following eval() wents wrong
546         $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
547
548         // Prepare subject
549         $subject = constant(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
550                 strtoupper($messageType)
551         ));
552
553         // Send the notification out
554         return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
555 }
556 // Notify the user about the performed action
557 function SURFBAR_NOTIFY_USER ($messageType, $content) {
558         // Skip notification if userid is zero
559         if ($content['uid'] == 0) {
560                 return false;
561         } // END - if
562
563         // Prepare template name
564         $templateName = sprintf("member_surfbar_%s", $messageType);
565
566         // Set default subject if following eval() wents wrong
567         $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
568
569         // Prepare subject
570         $subject = constant(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
571                 strtoupper($messageType)
572         ));
573
574         // Load template
575         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
576
577         // Send the email
578         return SEND_EMAIL($content['uid'], $subject, $mailText);
579 }
580 // Translates the limit
581 function SURFBAR_TRANSLATE_LIMIT ($limit) {
582         // Is this zero?
583         if ($limit == 0) {
584                 // Unlimited!
585                 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
586         } else {
587                 // Translate comma
588                 $return = TRANSLATE_COMMA($limit);
589         }
590
591         // Return value
592         return $return;
593 }
594 // Translate the URL status
595 function SURFBAR_TRANSLATE_STATUS ($status) {
596         // Create constant name
597         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
598
599         // Set default translated status
600         $statusTranslated = "!".$constantName."!";
601
602         // Is the constant there?
603         if (defined($constantName)) {
604                 // Then get it's value
605                 $statusTranslated = constant($constantName);
606         } // END - if
607
608         // Return result
609         return $statusTranslated;
610 }
611 // Determine reward
612 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
613         global $_CONFIG;
614
615         // Static values are default
616         $reward = $_CONFIG['surfbar_static_reward'];
617
618         // Do we have static or dynamic?
619         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
620                 // "Calculate" dynamic reward
621                 if ($onlyMin) {
622                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
623                 } else {
624                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
625                 }
626         } // END - if
627
628         // Return reward
629         return $reward;
630 }
631 // Determine costs
632 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
633         global $_CONFIG;
634
635         // Static costs is default
636         $costs  = $_CONFIG['surfbar_static_costs'];
637
638         // Do we have static or dynamic?
639         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
640                 // "Calculate" dynamic costs
641                 if ($onlyMin) {
642                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
643                 } else {
644                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
645                 }
646         } // END - if
647
648         // Return costs
649         return $costs;
650 }
651 // "Calculate" dynamic add
652 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
653         // Get min/max values
654         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
655         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
656
657         // "Calculate" dynamic part and return it
658         return mt_rand($min, $max);
659 }
660 // Determine right template name
661 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
662         // Default is the frameset
663         $templateName = "surfbar_frameset";
664
665         // Any frame set? ;-)
666         if (isset($_GET['frame'])) {
667                 // Use the frame as a template name part... ;-)
668                 $templateName = sprintf("surfbar_frame_%s",
669                         SQL_ESCAPE($_GET['frame'])
670                 );
671         } // END - if
672
673         // Return result
674         return $templateName;
675 }
676 // Check if the "reload lock" of the current user is full, call this function
677 // before you call SURFBAR_CHECK_RELOAD_LOCK().
678 function SURFBAR_CHECK_RELOAD_FULL() {
679         global $SURFBAR_CACHE, $_CONFIG;
680
681         // Default is full!
682         $isFull = true;
683
684         // Cache static reload lock
685         $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
686         //DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."", false);
687
688         // Do we have dynamic model?
689         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
690                 // "Calculate" dynamic lock
691                 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
692         } // END - if
693
694         // Ask the database
695         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
696 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
697 LIMIT 1",
698                 array($GLOBALS['userid']), __FILE__, __LINE__
699         );
700
701         // Fetch row
702         list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
703
704         // Is it null?
705         if (is_null($SURFBAR_CACHE['user_locks'])) {
706                 // Then fix it to zero!
707                 $SURFBAR_CACHE['user_locks'] = 0;
708         } // END - if
709
710         // Free result
711         SQL_FREERESULT($result);
712
713         // Get total URLs
714         $total = SURFBAR_GET_TOTAL_URLS();
715
716         // Do we have some URLs in lock? Admins can always surf on own URLs!
717         //DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}", false);
718         $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
719
720         // Return result
721         return $isFull;
722 }
723 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
724 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
725         // Determine depleted user account
726         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
727
728         // Is the exlude userid set?
729         if ($excludeUserId > 0) {
730                 // Then add it
731                 $UIDs['uid'][$excludeUserId] = $excludeUserId;
732         } // END - if
733
734         // Get amount from database
735         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
736 FROM "._MYSQL_PREFIX."_surfbar_urls
737 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
738                 array($status), __FILE__, __LINE__
739         );
740
741         // Fetch row
742         list($cnt) = SQL_FETCHROW($result);
743
744         // Free result
745         SQL_FREERESULT($result);
746
747         // Return result
748         return $cnt;
749 }
750 // Check wether the user is allowed to book more URLs
751 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
752         global $_CONFIG;
753
754         // Is this admin and userid is zero or does the user has some URLs left to book?
755         return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
756 }
757 // Get total amount of URLs of given status for current user
758 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
759         global $_CONFIG;
760
761         // Is the user 0 and user is logged in?
762         if (($uid == 0) && (IS_MEMBER())) {
763                 // Then use this userid
764                 $uid = $GLOBALS['userid'];
765         } elseif ($uid == 0) {
766                 // Error!
767                 return ($_CONFIG['surfbar_max_order'] + 1);
768         }
769
770         // Default is all URLs
771         $ADD = "";
772
773         // Is the status set?
774         if (is_array($status)) {
775                 // Only URLs with these status
776                 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
777         } elseif (!empty($status)) {
778                 // Only URLs with this status
779                 $ADD = sprintf(" AND status='%s'", $status);
780         } elseif (is_array($exclude)) {
781                 // Exclude URLs with these status
782                 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
783         } elseif (!empty($exclude)) {
784                 // Exclude URLs with this status
785                 $ADD = sprintf(" AND status != '%s'", $exclude);
786         }
787
788         // Get amount from database
789         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
790 FROM "._MYSQL_PREFIX."_surfbar_urls
791 WHERE userid=%s".$ADD."
792 LIMIT %s",
793                 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
794         );
795
796         // Fetch row
797         list($cnt) = SQL_FETCHROW($result);
798
799         // Free result
800         SQL_FREERESULT($result);
801
802         // Return result
803         return $cnt;
804 }
805 // Generate a validation code for the given id number
806 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
807         global $_CONFIG, $SURFBAR_CACHE;
808
809         // @TODO Invalid salt should be refused
810         $SURFBAR_CACHE['salt'] = "INVALID";
811
812         // Get code length from config
813         $length = $_CONFIG['code_length'];
814
815         // Fix length to 10
816         if ($length == 0) $length = 10;
817
818         // Generate a code until the length matches
819         $valCode = "";
820         while (strlen($valCode) != $length) {
821                 // Is the salt set?
822                 if (empty($salt)) {
823                         // Generate random hashed string
824                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
825                         //DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
826                 } else {
827                         // Use this as salt!
828                         $SURFBAR_CACHE['salt'] = $salt;
829                         //DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
830                 }
831
832                 // ... and now the validation code
833                 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
834                 //DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
835         } // END - while
836
837         // Hash it with md5() and salt it with the random string
838         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
839
840         // Finally encrypt it PGP-like and return it
841         $valHashedCode = generatePassString($hashedCode);
842
843         // Return hashed value
844         //DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
845         return $valHashedCode;
846 }
847 // Check validation code
848 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
849         global $SURFBAR_CACHE;
850
851         // Secure id number
852         $urlId = bigintval($urlId);
853
854         // Now generate the code again
855         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
856
857         // Return result of checking hashes and salts
858         //DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
859         //DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
860         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
861 }
862 // Lockdown the userid/id combination (reload lock)
863 function SURFBAR_LOCKDOWN_ID ($urlId) {
864         //* DEBUG: */ print "LOCK!");
865         ///* DEBUG: */ return;
866         // Just add it to the database
867         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES (%s, %s)",
868                 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
869
870         // Remove the salt from database
871         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
872                 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
873 }
874 // Pay points to the user and remove it from the sender
875 function SURFBAR_PAY_POINTS ($urlId) {
876         // Remove it from the URL owner
877         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
878         if (SURFBAR_GET_USERID() > 0) {
879                 SUB_POINTS("surfbar", SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
880         } // END - if
881
882         // Book it to the user
883         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
884         ADD_POINTS_REFSYSTEM("surfbar", $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
885 }
886 // Updates the statistics of current URL/userid
887 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
888         global $_CONFIG;
889
890         // Init add
891         $ADD = "";
892
893         // Get allowed views
894         $allowed = SURFBAR_GET_ALLOWED_VIEWS();
895
896         // Do we have a limit?
897         if ($allowed > 0) {
898                 // Then count views_max down!
899                 $ADD .= ",views_max=views_max-1";
900         } // END - if
901
902         // Update URL stats
903         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
904                 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
905
906         // Update the stats entry
907         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
908                 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
909
910         // Was that update okay?
911         if (SQL_AFFECTEDROWS() < 1) {
912                 // No, then insert entry
913                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES (%s,%s,1)",
914                         array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
915         } // END - if
916
917         // Update total/daily/weekly/monthly counter
918         $_CONFIG['surfbar_total_counter']++;
919         $_CONFIG['surfbar_daily_counter']++;
920         $_CONFIG['surfbar_weekly_counter']++;
921         $_CONFIG['surfbar_monthly_counter']++;
922
923         // Update config as well
924         UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
925 }
926 // Update the salt for validation and statistics
927 function SURFBAR_UPDATE_SALT_STATS () {
928         // Update statistics record
929         SURFBAR_UPDATE_INSERT_STATS_RECORD();
930
931         // Simply store the salt from cache away in database...
932         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
933                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
934
935         // Debug message
936         //DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
937
938         // Was that okay?
939         if (SQL_AFFECTEDROWS() < 1) {
940                 // Insert missing entry!
941                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
942                         array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
943         } // END - if
944
945         // Debug message
946         //DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
947
948         // Return if the update was okay
949         return (SQL_AFFECTEDROWS() == 1);
950 }
951 // Check if the reload lock is active for given id
952 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
953         //DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
954         // Ask the database
955         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
956 FROM "._MYSQL_PREFIX."_surfbar_locks
957 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
958 ORDER BY last_surfed ASC
959 LIMIT 1",
960                 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
961         );
962
963         // Fetch counter
964         list($cnt) = SQL_FETCHROW($result);
965
966         // Free result
967         SQL_FREERESULT($result);
968
969         // Return check
970         //DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."", false);
971         return ($cnt == 1);
972 }
973 // Determine which user hash no more points left
974 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
975         // Init array
976         $UIDs = array(
977                 'uid'      => array(),
978                 'points'   => array(),
979                 'notified' => array(),
980         );
981
982         // Do we have a current user id?
983         if ((IS_MEMBER()) && ($limit == 0)) {
984                 // Then add this as well
985                 $UIDs['uid'][$GLOBALS['userid']]      = $GLOBALS['userid'];
986                 $UIDs['points'][$GLOBALS['userid']]   = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
987                 $UIDs['notified'][$GLOBALS['userid']] = 0;
988
989                 // Get all userid except logged in one
990                 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
991 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
992 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
993 ON u.userid=d.userid
994 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
995 GROUP BY u.userid
996 ORDER BY u.userid ASC",
997                         array($GLOBALS['userid']), __FILE__, __LINE__);
998         } else {
999                 // Get all userid
1000                 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1001 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1002 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
1003 ON u.userid=d.userid
1004 WHERE u.status='ACTIVE'
1005 GROUP BY u.userid
1006 ORDER BY u.userid ASC", __FILE__, __LINE__);
1007         }
1008
1009         // Load all userid
1010         while (list($uid, $notified) = SQL_FETCHROW($result)) {
1011                 // Get total points
1012                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
1013                 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
1014
1015                 // Shall we add this to ignore?
1016                 if ($points <= $limit) {
1017                         // Ignore this one!
1018                         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
1019                         $UIDs['uid'][$uid] = $uid;
1020                         $UIDs['points'][$uid] = $points;
1021                         $UIDs['notified'][$uid] = $notified;
1022                 } // END - if
1023         } // END - while
1024
1025         // Free result
1026         SQL_FREERESULT($result);
1027
1028         // Debug message
1029         //DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1030
1031         // Return result
1032         return $UIDs;
1033 }
1034 // Determine how many users are Online in surfbar
1035 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1036         global $_CONFIG;
1037
1038         // Count all users in surfbar modue and return the value
1039         $result = SQL_QUERY_ESC("SELECT id
1040 FROM "._MYSQL_PREFIX."_surfbar_stats
1041 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1042 GROUP BY userid",
1043                 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
1044
1045         // Fetch count
1046         $cnt = SQL_NUMROWS($result);
1047
1048         // Free result
1049         SQL_FREERESULT($result);
1050
1051         // Return result
1052         return $cnt;
1053 }
1054 // Determine waiting time for one URL 
1055 function SURFBAR_DETERMINE_WAIT_TIME () {
1056         global $_CONFIG;
1057
1058         // Static time is default
1059         $time = $_CONFIG['surfbar_static_time'];
1060
1061         // Which payment model do we have?
1062         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1063                 // "Calculate" dynamic time
1064                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1065         } // END - if
1066
1067         // Return value
1068         return $time;
1069 }
1070 // Changes the status of an URL from given to other
1071 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1072         global $_CONFIG;
1073
1074         // Get URL data for status comparison if missing
1075         if ((!is_array($data)) || (count($data) == 0)) {
1076                 // Fetch missing URL data
1077                 $data = SURFBAR_GET_URL_DATA($urlId);
1078         } // END - if
1079
1080         // Is the status like prevStatus is saying?
1081         if ($data[$urlId]['status'] != $prevStatus) {
1082                 // No, then abort here
1083                 return false;
1084         } // END - if
1085
1086
1087         // Update the status now
1088         // ---------- Comment out for debugging/developing member actions! ---------
1089         //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1090         //      array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1091         // ---------- Comment out for debugging/developing member actions! ---------
1092
1093         // Was that fine?
1094         if (SQL_AFFECTEDROWS() != 1) {
1095                 // No, something went wrong
1096                 return false;
1097         } // END - if
1098
1099         // Prepare content for notification routines
1100         $data[$urlId]['uid']         = $data[$urlId]['userid'];
1101         $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1102         $data[$urlId]['reward']      = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
1103         $data[$urlId]['costs']       = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
1104         $data[$urlId]['status']      = SURFBAR_TRANSLATE_STATUS($newStatus);
1105         $data[$urlId]['registered']  = MAKE_DATETIME($data[$urlId]['registered'], "2");
1106         $newStatus = strtolower($newStatus);
1107
1108         // Send admin notification
1109         SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
1110
1111         // Send user notification
1112         SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
1113
1114         // All done!
1115         return true;
1116 }
1117 // Calculate minimum value for dynamic payment model
1118 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1119         global $_CONFIG;
1120
1121         // Addon is zero by default
1122         $addon = 0;
1123
1124         // Percentage part
1125         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1126
1127         // Get total users
1128         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1129
1130         // Get online users
1131         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1132
1133         // Calculate addon
1134         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1135
1136         // Get total URLs
1137         $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1138
1139         // Get user's total URLs
1140         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1141
1142         // Calculate addon
1143         if ($totalUrls > 0) {
1144                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1145         } else {
1146                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1147         }
1148
1149         // Return addon
1150         return $addon;
1151 }
1152 // Calculate maximum value for dynamic payment model
1153 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1154         global $_CONFIG;
1155
1156         // Addon is zero by default
1157         $addon = 0;
1158
1159         // Maximum value
1160         $max = log(2);
1161
1162         // Percentage part
1163         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1164
1165         // Get total users
1166         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1167
1168         // Calculate addon
1169         $addon += abs($max * $percent * $totalUsers);
1170
1171         // Get total URLs
1172         $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1173
1174         // Calculate addon
1175         $addon += abs($max * $percent * $totalUrls);
1176
1177         // Return addon
1178         return $addon;
1179 }
1180 // Calculate dynamic lock
1181 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1182         global $_CONFIG;
1183
1184         // Default lock is 30 seconds
1185         $addon = 30;
1186
1187         // Get online users
1188         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1189
1190         // Calculate lock
1191         $addon = abs(log($onlineUsers / $addon + 1));
1192
1193         // Return value
1194         return $addon;
1195 }
1196 // "Getter" for lock ids array
1197 function SURFBAR_GET_LOCK_IDS () {
1198         // Prepare some arrays
1199         $IDs = array();
1200         $USE = array();
1201         $ignored = array();
1202
1203         // Get all id from locks within the timestamp
1204         $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1205 FROM
1206         "._MYSQL_PREFIX."_surfbar_locks
1207 WHERE
1208         userid=%s
1209 ORDER BY
1210         id ASC", array($GLOBALS['userid']),
1211                 __FILE__, __LINE__);
1212
1213         // Load all entries
1214         while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1215                 // Debug message
1216                 //DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."", false);
1217
1218                 // Skip entries that are too old
1219                 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1220                         // Debug message
1221                         //DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1222
1223                         // Add only if missing or bigger
1224                         if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1225                                 // Debug message
1226                                 //DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1227
1228                                 // Add this ID
1229                                 $IDs[$url] = $last;
1230                                 $USE[$url] = $lid;
1231                         } // END - if
1232                 } else {
1233                         // Debug message
1234                         //DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1235
1236                         // Ignore these old entries!
1237                         $ignored[] = $url;
1238                         unset($IDs[$url]);
1239                         unset($USE[$url]);
1240                 }
1241         } // END - while
1242
1243         // Free result
1244         SQL_FREERESULT($result);
1245
1246         // Return array
1247         return $USE;
1248 }
1249 // "Getter" for maximum random number
1250 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1251         global $_CONFIG;
1252         // Count max availabe entries
1253         $result = SQL_QUERY("SELECT sbu.id AS cnt
1254 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1255 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1256 ON sbu.id=sbs.url_id
1257 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1258 ON sbu.id=l.url_id
1259 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0)) AND sbu.status='ACTIVE'".$ADD."
1260 GROUP BY sbu.id", __FILE__, __LINE__);
1261
1262         // Log last query
1263         //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1264
1265         // Fetch max rand
1266         $maxRand = SQL_NUMROWS($result);
1267
1268         // Free result
1269         SQL_FREERESULT($result);
1270
1271         // Return value
1272         return $maxRand;
1273 }
1274 // Load all URLs of the current user and return it as an array
1275 function SURFBAR_GET_USER_URLS () {
1276         // Init array
1277         $URLs = array();
1278
1279         // Begin the query
1280         $result = SQL_QUERY_ESC("SELECT u.id, u.userid, u.url, u.views_total, u.views_max, u.views_allowed, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
1281 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1282 WHERE u.userid=%s AND u.status != 'DELETED'
1283 ORDER BY u.id ASC",
1284                 array($GLOBALS['userid']), __FILE__, __LINE__);
1285
1286         // Are there entries?
1287         if (SQL_NUMROWS($result) > 0) {
1288                 // Load all rows
1289                 while ($row = SQL_FETCHARRAY($result)) {
1290                         // Add the row
1291                         $URLs[$row['id']] = $row;
1292                 } // END - while
1293         } // END - if
1294
1295         // Free result
1296         SQL_FREERESULT($result);
1297
1298         // Return the array
1299         return $URLs;
1300 }
1301 // "Getter" for member action array for given status
1302 function SURFBAR_GET_ACTION_ARRAY ($status) {
1303         // Init array
1304         $returnArray = array();
1305
1306         // Get all assigned actions
1307         $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1308                 array($status), __FILE__, __LINE__);
1309
1310         // Some entries there?
1311         if (SQL_NUMROWS($result) > 0) {
1312                 // Load all actions
1313                 while (list($action) = SQL_FETCHROW($result)) {
1314                         $returnArray[] = $action;
1315                 } // END - if
1316         } // END - if
1317
1318         // Free result
1319         SQL_FREERESULT($result);
1320
1321         // Return result
1322         return $returnArray;
1323 }
1324 // Reload to configured stop page
1325 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1326         global $_CONFIG;
1327
1328         // Internal or external?
1329         if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1330                 // Reload to internal page
1331                 LOAD_URL("surfbar.php?frame=".$page);
1332         } else {
1333                 // Reload to external page
1334                 LOAD_URL($_CONFIG['surfbar_pause_url']);
1335         }
1336 }
1337
1338 // Determine next id for surfbar or get data for given id, always call this before you call other
1339 // getters below this function!!!
1340 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1341         global $SURFBAR_CACHE, $_CONFIG;
1342
1343         // Default is no id and no random number
1344         $nextId = 0;
1345         $randNum = 0;
1346
1347         // Is the ID set?
1348         if ($urlId == 0) {
1349                 // Get array with lock ids
1350                 $USE = SURFBAR_GET_LOCK_IDS();
1351
1352                 // Shall we add some URL ids to ignore?
1353                 $ADD = "";
1354                 if (count($USE) > 0) {
1355                         // Ignore some!
1356                         $ADD = " AND sbu.id NOT IN (";
1357                         foreach ($USE as $url_id => $lid) {
1358                                 // Add URL id
1359                                 $ADD .= $url_id.",";
1360                         } // END - foreach
1361
1362                         // Add closing bracket
1363                         $ADD = substr($ADD, 0, -1) . ")";
1364                 } // END - if
1365
1366                 // Determine depleted user account
1367                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1368
1369                 // Get maximum randomness factor
1370                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1371
1372                 // If more than one URL can be called generate the random number!
1373                 if ($maxRand > 1) {
1374                         // Generate random number
1375                         $randNum = mt_rand(0, ($maxRand - 1));
1376                 } // END - if
1377
1378                 // And query the database
1379                 //DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."", false);
1380                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1381 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1382 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1383 ON sbu.id=sbs.url_id
1384 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1385 ON sbu.id=l.url_id
1386 WHERE sbu.userid NOT IN (".implode(",", $UIDs['uid']).") AND sbu.status='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$ADD."
1387 GROUP BY sbu.id
1388 ORDER BY l.last_surfed ASC, sbu.id ASC
1389 LIMIT %s,1",
1390                         array($randNum), __FILE__, __LINE__
1391                 );
1392         } else {
1393                 // Get data from specified id number
1394                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1395 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1396 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1397 ON sbu.id=sbs.url_id
1398 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1399 ON sbu.id=l.url_id
1400 WHERE sbu.userid != %s AND sbu.status='ACTIVE' AND sbu.id=%s AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))
1401 LIMIT 1",
1402                         array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1403                 );
1404         }
1405
1406         // Is there an id number?
1407         //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1408         if (SQL_NUMROWS($result) == 1) {
1409                 // Load/cache data
1410                 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1411                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1412                 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1413
1414                 // Determine waiting time
1415                 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1416
1417                 // Is the last salt there?
1418                 if (is_null($SURFBAR_CACHE['last_salt'])) {
1419                         // Then repair it wit the static!
1420                         //DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1421                         $SURFBAR_CACHE['last_salt'] = "";
1422                 } // END - if
1423
1424                 // Fix missing last_surfed
1425                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1426                         // Fix it here
1427                         //DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1428                         $SURFBAR_CACHE['last_surfed'] = 0;
1429                 } // END - if
1430
1431                 // Get base/fixed reward and costs
1432                 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1433                 $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
1434                 //DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1435
1436                 // Only in dynamic model add the dynamic bonus!
1437                 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1438                         // Calculate dynamic reward/costs and add it
1439                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1440                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1441                         //DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1442                 } // END - if
1443
1444                 // Now get the id
1445                 $nextId = SURFBAR_GET_ID();
1446         } // END - if
1447
1448         // Free result
1449         SQL_FREERESULT($result);
1450
1451         // Return result
1452         //DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1453         return $nextId;
1454 }
1455 // -----------------------------------------------------------------------------
1456 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1457 // $SURFBAR_CACHE ARRAY!
1458 // -----------------------------------------------------------------------------
1459 // Private getter for data elements
1460 function SURFBAR_GET_DATA ($element) {
1461         global $SURFBAR_CACHE;
1462         //DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1463
1464         // Default is null
1465         $data = null;
1466
1467         // Is the entry there?
1468         if (isset($SURFBAR_CACHE[$element])) {
1469                 // Then take it
1470                 $data = $SURFBAR_CACHE[$element];
1471         } else { // END - if
1472                 print("<pre>");
1473                 print_r($SURFBAR_CACHE);
1474                 debug_print_backtrace();
1475                 die("</pre>");
1476         }
1477
1478         // Return result
1479         //DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1480         return $data;
1481 }
1482 // Getter for reward from cache
1483 function SURFBAR_GET_REWARD () {
1484         // Get data element and return its contents
1485         return SURFBAR_GET_DATA('reward');
1486 }
1487 // Getter for costs from cache
1488 function SURFBAR_GET_COSTS () {
1489         // Get data element and return its contents
1490         return SURFBAR_GET_DATA('costs');
1491 }
1492 // Getter for URL from cache
1493 function SURFBAR_GET_URL () {
1494         // Get data element and return its contents
1495         return SURFBAR_GET_DATA('url');
1496 }
1497 // Getter for salt from cache
1498 function SURFBAR_GET_SALT () {
1499         // Get data element and return its contents
1500         return SURFBAR_GET_DATA('salt');
1501 }
1502 // Getter for id from cache
1503 function SURFBAR_GET_ID () {
1504         // Get data element and return its contents
1505         return SURFBAR_GET_DATA('id');
1506 }
1507 // Getter for userid from cache
1508 function SURFBAR_GET_USERID () {
1509         // Get data element and return its contents
1510         return SURFBAR_GET_DATA('userid');
1511 }
1512 // Getter for user reload locks
1513 function SURFBAR_GET_USER_RELOAD_LOCK () {
1514         // Get data element and return its contents
1515         return SURFBAR_GET_DATA('user_locks');
1516 }
1517 // Getter for reload time
1518 function SURFBAR_GET_RELOAD_TIME () {
1519         // Get data element and return its contents
1520         return SURFBAR_GET_DATA('time');
1521 }
1522 // Getter for allowed views
1523 function SURFBAR_GET_ALLOWED_VIEWS () {
1524         // Get data element and return its contents
1525         return SURFBAR_GET_DATA('views_allowed');
1526 }
1527 //
1528 ?>