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