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