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