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