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