Admin user details extended, DEBUG_LOG() rewritten, random userid on refid=0 added
[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 ("".($limit + 0)."" != "".$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 ("".($limit + 0)."" != "".$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__, __LINE__, " 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         $subject = constant(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
492                 strtoupper($messageType)
493         ));
494
495         // Send the notification out
496         return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
497 }
498 // Notify the user about the performed action
499 function SURFBAR_NOTIFY_USER ($messageType, $content) {
500         // Skip notification if userid is zero
501         if ($content['uid'] == 0) {
502                 return false;
503         } // END - if
504
505         // Prepare template name
506         $templateName = sprintf("member_surfbar_%s", $messageType);
507
508         // Set default subject if following eval() wents wrong
509         $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
510
511         // Prepare subject
512         $subject = constant(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
513                 strtoupper($messageType)
514         ));
515
516         // Load template
517         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
518
519         // Send the email
520         return SEND_EMAIL($content['uid'], $subject, $mailText);
521 }
522 // Translates the limit
523 function SURFBAR_TRANSLATE_LIMIT ($limit) {
524         // Is this zero?
525         if ($limit == 0) {
526                 // Unlimited!
527                 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
528         } else {
529                 // Translate comma
530                 $return = TRANSLATE_COMMA($limit);
531         }
532
533         // Return value
534         return $return;
535 }
536 // Translate the URL status
537 function SURFBAR_TRANSLATE_STATUS ($status) {
538         // Create constant name
539         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
540
541         // Set default translated status
542         $statusTranslated = "!".$constantName."!";
543
544         // Generate eval() command
545         if (defined($constantName)) {
546                 $eval = "\$statusTranslated = ".$constantName.";";
547                 eval($eval);
548         } // END - if
549
550         // Return result
551         return $statusTranslated;
552 }
553 // Determine reward
554 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
555         global $_CONFIG;
556
557         // Static values are default
558         $reward = $_CONFIG['surfbar_static_reward'];
559
560         // Do we have static or dynamic?
561         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
562                 // "Calculate" dynamic reward
563                 if ($onlyMin) {
564                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
565                 } else {
566                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
567                 }
568         } // END - if
569
570         // Return reward
571         return $reward;
572 }
573 // Determine costs
574 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
575         global $_CONFIG;
576
577         // Static costs is default
578         $costs  = $_CONFIG['surfbar_static_costs'];
579
580         // Do we have static or dynamic?
581         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
582                 // "Calculate" dynamic costs
583                 if ($onlyMin) {
584                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
585                 } else {
586                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
587                 }
588         } // END - if
589
590         // Return costs
591         return $costs;
592 }
593 // "Calculate" dynamic add
594 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
595         // Get min/max values
596         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
597         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
598
599         // "Calculate" dynamic part and return it
600         return mt_rand($min, $max);
601 }
602 // Determine right template name
603 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
604         // Default is the frameset
605         $templateName = "surfbar_frameset";
606
607         // Any frame set? ;-)
608         if (isset($_GET['frame'])) {
609                 // Use the frame as a template name part... ;-)
610                 $templateName = sprintf("surfbar_frame_%s",
611                         SQL_ESCAPE($_GET['frame'])
612                 );
613         } // END - if
614
615         // Return result
616         return $templateName;
617 }
618 // Check if the "reload lock" of the current user is full, call this function
619 // before you call SURFBAR_CHECK_RELOAD_LOCK().
620 function SURFBAR_CHECK_RELOAD_FULL() {
621         global $SURFBAR_CACHE, $_CONFIG;
622
623         // Default is full!
624         $isFull = true;
625
626         // Cache static reload lock
627         $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
628         //DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
629
630         // Do we have dynamic model?
631         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
632                 // "Calculate" dynamic lock
633                 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
634         } // END - if
635
636         // Ask the database
637         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
638 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
639 LIMIT 1",
640                 array($GLOBALS['userid']), __FILE__, __LINE__
641         );
642
643         // Fetch row
644         list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
645
646         // Is it null?
647         if (is_null($SURFBAR_CACHE['user_locks'])) {
648                 // Then fix it to zero!
649                 $SURFBAR_CACHE['user_locks'] = 0;
650         } // END - if
651
652         // Free result
653         SQL_FREERESULT($result);
654
655         // Get total URLs
656         $total = SURFBAR_GET_TOTAL_URLS();
657
658         // Do we have some URLs in lock? Admins can always surf on own URLs!
659         //DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
660         $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
661
662         // Return result
663         return $isFull;
664 }
665 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
666 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
667         // Determine depleted user account
668         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
669
670         // Is the exlude userid set?
671         if ($excludeUserId > 0) {
672                 // Then add it
673                 $UIDs['uid'][$excludeUserId] = $excludeUserId;
674         } // END - if
675
676         // Get amount from database
677         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
678 FROM "._MYSQL_PREFIX."_surfbar_urls
679 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
680                 array($status), __FILE__, __LINE__
681         );
682
683         // Fetch row
684         list($cnt) = SQL_FETCHROW($result);
685
686         // Free result
687         SQL_FREERESULT($result);
688
689         // Return result
690         return $cnt;
691 }
692 // Check wether the user is allowed to book more URLs
693 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
694         global $_CONFIG;
695
696         // Is this admin and userid is zero or does the user has some URLs left to book?
697         return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
698 }
699 // Get total amount of URLs of given status for current user
700 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
701         global $_CONFIG;
702
703         // Is the user 0 and user is logged in?
704         if (($uid == 0) && (IS_MEMBER())) {
705                 // Then use this userid
706                 $uid = $GLOBALS['userid'];
707         } elseif ($uid == 0) {
708                 // Error!
709                 return ($_CONFIG['surfbar_max_order'] + 1);
710         }
711
712         // Default is all URLs
713         $ADD = "";
714
715         // Is the status set?
716         if (is_array($status)) {
717                 // Only URLs with these status
718                 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
719         } elseif (!empty($status)) {
720                 // Only URLs with this status
721                 $ADD = sprintf(" AND status='%s'", $status);
722         } elseif (is_array($exclude)) {
723                 // Exclude URLs with these status
724                 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
725         } elseif (!empty($exclude)) {
726                 // Exclude URLs with this status
727                 $ADD = sprintf(" AND status != '%s'", $exclude);
728         }
729
730         // Get amount from database
731         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
732 FROM "._MYSQL_PREFIX."_surfbar_urls
733 WHERE userid=%s".$ADD."
734 LIMIT %s",
735                 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
736         );
737
738         // Fetch row
739         list($cnt) = SQL_FETCHROW($result);
740
741         // Free result
742         SQL_FREERESULT($result);
743
744         // Return result
745         return $cnt;
746 }
747 // Generate a validation code for the given id number
748 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
749         global $_CONFIG, $SURFBAR_CACHE;
750
751         // @TODO Invalid salt should be refused
752         $SURFBAR_CACHE['salt'] = "INVALID";
753
754         // Get code length from config
755         $length = $_CONFIG['code_length'];
756
757         // Fix length to 10
758         if ($length == 0) $length = 10;
759
760         // Generate a code until the length matches
761         $valCode = "";
762         while (strlen($valCode) != $length) {
763                 // Is the salt set?
764                 if (empty($salt)) {
765                         // Generate random hashed string
766                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
767                         //DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."");
768                 } else {
769                         // Use this as salt!
770                         $SURFBAR_CACHE['salt'] = $salt;
771                         //DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."");
772                 }
773
774                 // ... and now the validation code
775                 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
776                 //DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}");
777         } // END - while
778
779         // Hash it with md5() and salt it with the random string
780         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
781
782         // Finally encrypt it PGP-like and return it
783         $valHashedCode = generatePassString($hashedCode);
784
785         // Return hashed value
786         //DEBUG_LOG(__FUNCTION__, __LINE__, "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__, __LINE__, "---".$code."|".$check."---");
801         //DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$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__, __LINE__, "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__, __LINE__, "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__, __LINE__, "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__, __LINE__, "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__, __LINE__, "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__, __LINE__, "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                 'uid'      => array(),
920                 'points'   => array(),
921                 'notified' => array(),
922         );
923
924         // Do we have a current user id?
925         if ((IS_MEMBER()) && ($limit == 0)) {
926                 // Then add this as well
927                 $UIDs['uid'][$GLOBALS['userid']]      = $GLOBALS['userid'];
928                 $UIDs['points'][$GLOBALS['userid']]   = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
929                 $UIDs['notified'][$GLOBALS['userid']] = 0;
930
931                 // Get all userid except logged in one
932                 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
933 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
934 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
935 ON u.userid=d.userid
936 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
937 GROUP BY u.userid
938 ORDER BY u.userid ASC",
939                         array($GLOBALS['userid']), __FILE__, __LINE__);
940         } else {
941                 // Get all userid
942                 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
943 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
944 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
945 ON u.userid=d.userid
946 WHERE u.status='ACTIVE'
947 GROUP BY u.userid
948 ORDER BY u.userid ASC", __FILE__, __LINE__);
949         }
950
951         // Load all userid
952         while (list($uid, $notified) = SQL_FETCHROW($result)) {
953                 // Get total points
954                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
955                 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}");
956
957                 // Shall we add this to ignore?
958                 if ($points <= $limit) {
959                         // Ignore this one!
960                         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!");
961                         $UIDs['uid'][$uid] = $uid;
962                         $UIDs['points'][$uid] = $points;
963                         $UIDs['notified'][$uid] = $notified;
964                 } // END - if
965         } // END - while
966
967         // Free result
968         SQL_FREERESULT($result);
969
970         // Debug message
971         //DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
972
973         // Return result
974         return $UIDs;
975 }
976 // Determine how many users are Online in surfbar
977 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
978         global $_CONFIG;
979
980         // Count all users in surfbar modue and return the value
981         $result = SQL_QUERY_ESC("SELECT id
982 FROM "._MYSQL_PREFIX."_surfbar_stats
983 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
984 GROUP BY userid",
985                 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
986
987         // Fetch count
988         $cnt = SQL_NUMROWS($result);
989
990         // Free result
991         SQL_FREERESULT($result);
992
993         // Return result
994         return $cnt;
995 }
996 // Determine waiting time for one URL 
997 function SURFBAR_DETERMINE_WAIT_TIME () {
998         global $_CONFIG;
999
1000         // Static time is default
1001         $time = $_CONFIG['surfbar_static_time'];
1002
1003         // Which payment model do we have?
1004         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1005                 // "Calculate" dynamic time
1006                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1007         } // END - if
1008
1009         // Return value
1010         return $time;
1011 }
1012 // Changes the status of an URL from given to other
1013 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1014         global $_CONFIG;
1015
1016         // Get URL data for status comparison if missing
1017         if (count($data) == 0) {
1018                 $data = SURFBAR_GET_URL_DATA($urlId);
1019         } // END - if
1020
1021         // Is the status like prevStatus is saying?
1022         if ($data[$urlId]['status'] != $prevStatus) {
1023                 // No, then abort here
1024                 return false;
1025         } // END - if
1026
1027
1028         // Update the status now
1029         // ---------------------- Commented out for debugging member actions! -----------------------
1030         //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1031         //      array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1032         // ---------------------- Commented out for debugging member actions! -----------------------
1033
1034         // Was that fine?
1035         if (SQL_AFFECTEDROWS() != 1) {
1036                 // No, something went wrong
1037                 return false;
1038         } // END - if
1039
1040         // Prepare content for notification routines
1041         $data[$urlId]['uid']         = $data[$urlId]['userid'];
1042         $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1043         $data[$urlId]['reward']      = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
1044         $data[$urlId]['costs']       = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
1045         $data[$urlId]['status']      = SURFBAR_TRANSLATE_STATUS($newStatus);
1046         $data[$urlId]['registered']  = MAKE_DATETIME($data[$urlId]['registered'], "2");
1047         $newStatus = strtolower($newStatus);
1048
1049         // Send admin notification
1050         SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
1051
1052         // Send user notification
1053         SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
1054
1055         // All done!
1056         return true;
1057 }
1058 // Calculate minimum value for dynamic payment model
1059 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1060         global $_CONFIG;
1061
1062         // Addon is zero by default
1063         $addon = 0;
1064
1065         // Percentage part
1066         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1067
1068         // Get total users
1069         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1070
1071         // Get online users
1072         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1073
1074         // Calculate addon
1075         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1076
1077         // Get total URLs
1078         $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1079
1080         // Get user's total URLs
1081         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1082
1083         // Calculate addon
1084         if ($totalUrls > 0) {
1085                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1086         } else {
1087                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1088         }
1089
1090         // Return addon
1091         return $addon;
1092 }
1093 // Calculate maximum value for dynamic payment model
1094 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1095         global $_CONFIG;
1096
1097         // Addon is zero by default
1098         $addon = 0;
1099
1100         // Maximum value
1101         $max = log(2);
1102
1103         // Percentage part
1104         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1105
1106         // Get total users
1107         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1108
1109         // Calculate addon
1110         $addon += abs($max * $percent * $totalUsers);
1111
1112         // Get total URLs
1113         $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1114
1115         // Calculate addon
1116         $addon += abs($max * $percent * $totalUrls);
1117
1118         // Return addon
1119         return $addon;
1120 }
1121 // Calculate dynamic lock
1122 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1123         global $_CONFIG;
1124
1125         // Default lock is 30 seconds
1126         $addon = 30;
1127
1128         // Get online users
1129         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1130
1131         // Calculate lock
1132         $addon = abs(log($onlineUsers / $addon + 1));
1133
1134         // Return value
1135         return $addon;
1136 }
1137 // "Getter" for lock ids array
1138 function SURFBAR_GET_LOCK_IDS () {
1139         // Prepare some arrays
1140         $IDs = array();
1141         $USE = array();
1142         $ignored = array();
1143
1144         // Get all id from locks within the timestamp
1145         $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1146 FROM
1147         "._MYSQL_PREFIX."_surfbar_locks
1148 WHERE
1149         userid=%s
1150 ORDER BY
1151         id ASC", array($GLOBALS['userid']),
1152                 __FILE__, __LINE__);
1153
1154         // Load all entries
1155         while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1156                 // Debug message
1157                 //DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
1158
1159                 // Skip entries that are too old
1160                 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1161                         // Debug message
1162                         //DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}");
1163
1164                         // Add only if missing or bigger
1165                         if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1166                                 // Debug message
1167                                 //DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}");
1168
1169                                 // Add this ID
1170                                 $IDs[$url] = $last;
1171                                 $USE[$url] = $lid;
1172                         } // END - if
1173                 } else {
1174                         // Debug message
1175                         //DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}");
1176
1177                         // Ignore these old entries!
1178                         $ignored[] = $url;
1179                         unset($IDs[$url]);
1180                         unset($USE[$url]);
1181                 }
1182         } // END - while
1183
1184         // Free result
1185         SQL_FREERESULT($result);
1186
1187         // Return array
1188         return $USE;
1189 }
1190 // "Getter" for maximum random number
1191 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1192         global $_CONFIG;
1193         // Count max availabe entries
1194         $result = SQL_QUERY("SELECT sbu.id AS cnt
1195 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1196 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1197 ON sbu.id=sbs.url_id
1198 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1199 ON sbu.id=l.url_id
1200 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."
1201 GROUP BY sbu.id", __FILE__, __LINE__);
1202
1203         // Log last query
1204         //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1205
1206         // Fetch max rand
1207         $maxRand = SQL_NUMROWS($result);
1208
1209         // Free result
1210         SQL_FREERESULT($result);
1211
1212         // Return value
1213         return $maxRand;
1214 }
1215 // Load all URLs of the current user and return it as an array
1216 function SURFBAR_GET_USER_URLS () {
1217         // Init array
1218         $URLs = array();
1219
1220         // Begin the query
1221         $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
1222 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1223 WHERE u.userid=%s AND u.status != 'DELETED'
1224 ORDER BY u.id ASC",
1225                 array($GLOBALS['userid']), __FILE__, __LINE__);
1226
1227         // Are there entries?
1228         if (SQL_NUMROWS($result) > 0) {
1229                 // Load all rows
1230                 while ($row = SQL_FETCHARRAY($result)) {
1231                         // Add the row
1232                         $URLs[$row['id']] = $row;
1233                 } // END - while
1234         } // END - if
1235
1236         // Free result
1237         SQL_FREERESULT($result);
1238
1239         // Return the array
1240         return $URLs;
1241 }
1242 // "Getter" for member action array for given status
1243 function SURFBAR_GET_ACTION_ARRAY ($status) {
1244         // Init array
1245         $returnArray = array();
1246
1247         // Get all assigned actions
1248         $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1249                 array($status), __FILE__, __LINE__);
1250
1251         // Some entries there?
1252         if (SQL_NUMROWS($result) > 0) {
1253                 // Load all actions
1254                 while (list($action) = SQL_FETCHROW($result)) {
1255                         $returnArray[] = $action;
1256                 } // END - if
1257         } // END - if
1258
1259         // Free result
1260         SQL_FREERESULT($result);
1261
1262         // Return result
1263         return $returnArray;
1264 }
1265 // Reload to configured stop page
1266 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1267         global $_CONFIG;
1268
1269         // Internal or external?
1270         if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1271                 // Reload to internal page
1272                 LOAD_URL("surfbar.php?frame=".$page);
1273         } else {
1274                 // Reload to external page
1275                 LOAD_URL($_CONFIG['surfbar_pause_url']);
1276         }
1277 }
1278
1279 // Determine next id for surfbar or get data for given id, always call this before you call other
1280 // getters below this function!!!
1281 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1282         global $SURFBAR_CACHE, $_CONFIG;
1283
1284         // Default is no id and no random number
1285         $nextId = 0;
1286         $randNum = 0;
1287
1288         // Is the ID set?
1289         if ($urlId == 0) {
1290                 // Get array with lock ids
1291                 $USE = SURFBAR_GET_LOCK_IDS();
1292
1293                 // Shall we add some URL ids to ignore?
1294                 $ADD = "";
1295                 if (count($USE) > 0) {
1296                         // Ignore some!
1297                         $ADD = " AND sbu.id NOT IN (";
1298                         foreach ($USE as $url_id => $lid) {
1299                                 // Add URL id
1300                                 $ADD .= $url_id.",";
1301                         } // END - foreach
1302
1303                         // Add closing bracket
1304                         $ADD = substr($ADD, 0, -1) . ")";
1305                 } // END - if
1306
1307                 // Determine depleted user account
1308                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1309
1310                 // Get maximum randomness factor
1311                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1312
1313                 // If more than one URL can be called generate the random number!
1314                 if ($maxRand > 1) {
1315                         // Generate random number
1316                         $randNum = mt_rand(0, ($maxRand - 1));
1317                 } // END - if
1318
1319                 // And query the database
1320                 //DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1321                 $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
1322 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1323 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1324 ON sbu.id=sbs.url_id
1325 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1326 ON sbu.id=l.url_id
1327 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."
1328 GROUP BY sbu.id
1329 ORDER BY l.last_surfed ASC, sbu.id ASC
1330 LIMIT %s,1",
1331                         array($randNum), __FILE__, __LINE__
1332                 );
1333         } else {
1334                 // Get data from specified id number
1335                 $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
1336 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1337 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1338 ON sbu.id=sbs.url_id
1339 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1340 ON sbu.id=l.url_id
1341 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))
1342 LIMIT 1",
1343                         array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1344                 );
1345         }
1346
1347         // Is there an id number?
1348         //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1349         if (SQL_NUMROWS($result) == 1) {
1350                 // Load/cache data
1351                 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE");
1352                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1353                 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER");
1354
1355                 // Determine waiting time
1356                 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1357
1358                 // Is the last salt there?
1359                 if (is_null($SURFBAR_CACHE['last_salt'])) {
1360                         // Then repair it wit the static!
1361                         //DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!");
1362                         $SURFBAR_CACHE['last_salt'] = "";
1363                 } // END - if
1364
1365                 // Fix missing last_surfed
1366                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1367                         // Fix it here
1368                         //DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!");
1369                         $SURFBAR_CACHE['last_surfed'] = 0;
1370                 } // END - if
1371
1372                 // Get base/fixed reward and costs
1373                 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1374                 $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
1375                 //DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1376
1377                 // Only in dynamic model add the dynamic bonus!
1378                 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1379                         // Calculate dynamic reward/costs and add it
1380                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1381                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1382                         //DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1383                 } // END - if
1384
1385                 // Now get the id
1386                 $nextId = SURFBAR_GET_ID();
1387         } // END - if
1388
1389         // Free result
1390         SQL_FREERESULT($result);
1391
1392         // Return result
1393         //DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}");
1394         return $nextId;
1395 }
1396 // -----------------------------------------------------------------------------
1397 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1398 // $SURFBAR_CACHE ARRAY!
1399 // -----------------------------------------------------------------------------
1400 // Private getter for data elements
1401 function SURFBAR_GET_DATA ($element) {
1402         global $SURFBAR_CACHE;
1403         //DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}");
1404
1405         // Default is null
1406         $data = null;
1407
1408         // Is the entry there?
1409         if (isset($SURFBAR_CACHE[$element])) {
1410                 // Then take it
1411                 $data = $SURFBAR_CACHE[$element];
1412         } else { // END - if
1413                 print("<pre>");
1414                 print_r($SURFBAR_CACHE);
1415                 debug_print_backtrace();
1416                 die("</pre>");
1417         }
1418
1419         // Return result
1420         //DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}");
1421         return $data;
1422 }
1423 // Getter for reward from cache
1424 function SURFBAR_GET_REWARD () {
1425         // Get data element and return its contents
1426         return SURFBAR_GET_DATA('reward');
1427 }
1428 // Getter for costs from cache
1429 function SURFBAR_GET_COSTS () {
1430         // Get data element and return its contents
1431         return SURFBAR_GET_DATA('costs');
1432 }
1433 // Getter for URL from cache
1434 function SURFBAR_GET_URL () {
1435         // Get data element and return its contents
1436         return SURFBAR_GET_DATA('url');
1437 }
1438 // Getter for salt from cache
1439 function SURFBAR_GET_SALT () {
1440         // Get data element and return its contents
1441         return SURFBAR_GET_DATA('salt');
1442 }
1443 // Getter for id from cache
1444 function SURFBAR_GET_ID () {
1445         // Get data element and return its contents
1446         return SURFBAR_GET_DATA('id');
1447 }
1448 // Getter for userid from cache
1449 function SURFBAR_GET_USERID () {
1450         // Get data element and return its contents
1451         return SURFBAR_GET_DATA('userid');
1452 }
1453 // Getter for user reload locks
1454 function SURFBAR_GET_USER_RELOAD_LOCK () {
1455         // Get data element and return its contents
1456         return SURFBAR_GET_DATA('user_locks');
1457 }
1458 // Getter for reload time
1459 function SURFBAR_GET_RELOAD_TIME () {
1460         // Get data element and return its contents
1461         return SURFBAR_GET_DATA('time');
1462 }
1463 // Getter for allowed views
1464 function SURFBAR_GET_ALLOWED_VIEWS () {
1465         // Get data element and return its contents
1466         return SURFBAR_GET_DATA('views_allowed');
1467 }
1468 //
1469 ?>